From 9caa14a8a0231ddbb5e48a3b1bd08ea454671459 Mon Sep 17 00:00:00 2001 From: amanstep Date: Fri, 13 Mar 2026 16:55:18 +0530 Subject: [PATCH 1/4] fix: fixed vulnerabilities --- dist/index.js | 180447 ++++++++++++++++++++++--------------------- dist/index.js.map | 2 +- dist/licenses.txt | 19 - osv-scanner.toml | 75 + package.json | 9 +- yarn.lock | 761 +- 6 files changed, 90944 insertions(+), 90369 deletions(-) create mode 100644 osv-scanner.toml diff --git a/dist/index.js b/dist/index.js index c1f3f3c..ab1fd9a 100644 --- a/dist/index.js +++ b/dist/index.js @@ -11525,13 +11525,13 @@ function saveCacheV2(paths, key, options, enableCrossOsArchive = false) { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Timestamp = void 0; -const runtime_1 = __nccwpck_require__(37001); -const runtime_2 = __nccwpck_require__(37001); -const runtime_3 = __nccwpck_require__(37001); -const runtime_4 = __nccwpck_require__(37001); -const runtime_5 = __nccwpck_require__(37001); -const runtime_6 = __nccwpck_require__(37001); -const runtime_7 = __nccwpck_require__(37001); +const runtime_1 = __nccwpck_require__(4061); +const runtime_2 = __nccwpck_require__(4061); +const runtime_3 = __nccwpck_require__(4061); +const runtime_4 = __nccwpck_require__(4061); +const runtime_5 = __nccwpck_require__(4061); +const runtime_6 = __nccwpck_require__(4061); +const runtime_7 = __nccwpck_require__(4061); // @generated message type with reflection information, may provide speed optimized methods class Timestamp$Type extends runtime_7.MessageType { constructor() { @@ -11672,11 +11672,11 @@ exports.CacheService = exports.LookupCacheEntryResponse = exports.LookupCacheEnt // @generated from protobuf file "results/api/v1/cache.proto" (package "github.actions.results.api.v1", syntax proto3) // tslint:disable const runtime_rpc_1 = __nccwpck_require__(60012); -const runtime_1 = __nccwpck_require__(37001); -const runtime_2 = __nccwpck_require__(37001); -const runtime_3 = __nccwpck_require__(37001); -const runtime_4 = __nccwpck_require__(37001); -const runtime_5 = __nccwpck_require__(37001); +const runtime_1 = __nccwpck_require__(4061); +const runtime_2 = __nccwpck_require__(4061); +const runtime_3 = __nccwpck_require__(4061); +const runtime_4 = __nccwpck_require__(4061); +const runtime_5 = __nccwpck_require__(4061); const cacheentry_1 = __nccwpck_require__(53639); const cachemetadata_1 = __nccwpck_require__(67988); // @generated message type with reflection information, may provide speed optimized methods @@ -13014,11 +13014,11 @@ function handleCacheServiceLookupCacheEntryProtobuf(ctx, service, data, intercep Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CacheEntry = void 0; -const runtime_1 = __nccwpck_require__(37001); -const runtime_2 = __nccwpck_require__(37001); -const runtime_3 = __nccwpck_require__(37001); -const runtime_4 = __nccwpck_require__(37001); -const runtime_5 = __nccwpck_require__(37001); +const runtime_1 = __nccwpck_require__(4061); +const runtime_2 = __nccwpck_require__(4061); +const runtime_3 = __nccwpck_require__(4061); +const runtime_4 = __nccwpck_require__(4061); +const runtime_5 = __nccwpck_require__(4061); const timestamp_1 = __nccwpck_require__(24469); // @generated message type with reflection information, may provide speed optimized methods class CacheEntry$Type extends runtime_5.MessageType { @@ -13127,11 +13127,11 @@ exports.CacheEntry = new CacheEntry$Type(); Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CacheMetadata = void 0; -const runtime_1 = __nccwpck_require__(37001); -const runtime_2 = __nccwpck_require__(37001); -const runtime_3 = __nccwpck_require__(37001); -const runtime_4 = __nccwpck_require__(37001); -const runtime_5 = __nccwpck_require__(37001); +const runtime_1 = __nccwpck_require__(4061); +const runtime_2 = __nccwpck_require__(4061); +const runtime_3 = __nccwpck_require__(4061); +const runtime_4 = __nccwpck_require__(4061); +const runtime_5 = __nccwpck_require__(4061); const cachescope_1 = __nccwpck_require__(83749); // @generated message type with reflection information, may provide speed optimized methods class CacheMetadata$Type extends runtime_5.MessageType { @@ -13198,11 +13198,11 @@ exports.CacheMetadata = new CacheMetadata$Type(); Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CacheScope = void 0; -const runtime_1 = __nccwpck_require__(37001); -const runtime_2 = __nccwpck_require__(37001); -const runtime_3 = __nccwpck_require__(37001); -const runtime_4 = __nccwpck_require__(37001); -const runtime_5 = __nccwpck_require__(37001); +const runtime_1 = __nccwpck_require__(4061); +const runtime_2 = __nccwpck_require__(4061); +const runtime_3 = __nccwpck_require__(4061); +const runtime_4 = __nccwpck_require__(4061); +const runtime_5 = __nccwpck_require__(4061); // @generated message type with reflection information, may provide speed optimized methods class CacheScope$Type extends runtime_5.MessageType { constructor() { @@ -215188,7 +215188,7 @@ exports.KubernetesObjectApi = KubernetesObjectApi; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.OpenIDConnectAuth = void 0; -const openid_client_1 = __nccwpck_require__(22881); +const openid_client_1 = __nccwpck_require__(53140); const rfc4648_1 = __nccwpck_require__(97417); const util_1 = __nccwpck_require__(73837); class OpenIDConnectAuth { @@ -216735,22382 +216735,18787 @@ module.exports = { /***/ }), -/***/ 35132: +/***/ 67551: /***/ ((module) => { -const CODES = { - JOSEAlgNotWhitelisted: 'ERR_JOSE_ALG_NOT_WHITELISTED', - JOSECritNotUnderstood: 'ERR_JOSE_CRIT_NOT_UNDERSTOOD', - JOSEInvalidEncoding: 'ERR_JOSE_INVALID_ENCODING', - JOSEMultiError: 'ERR_JOSE_MULTIPLE_ERRORS', - JOSENotSupported: 'ERR_JOSE_NOT_SUPPORTED', - JWEDecryptionFailed: 'ERR_JWE_DECRYPTION_FAILED', - JWEInvalid: 'ERR_JWE_INVALID', - JWKImportFailed: 'ERR_JWK_IMPORT_FAILED', - JWKInvalid: 'ERR_JWK_INVALID', - JWKKeySupport: 'ERR_JWK_KEY_SUPPORT', - JWKSNoMatchingKey: 'ERR_JWKS_NO_MATCHING_KEY', - JWSInvalid: 'ERR_JWS_INVALID', - JWSVerificationFailed: 'ERR_JWS_VERIFICATION_FAILED', - JWTClaimInvalid: 'ERR_JWT_CLAIM_INVALID', - JWTExpired: 'ERR_JWT_EXPIRED', - JWTMalformed: 'ERR_JWT_MALFORMED' -} +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. -const DEFAULT_MESSAGES = { - JWEDecryptionFailed: 'decryption operation failed', - JWEInvalid: 'JWE invalid', - JWKSNoMatchingKey: 'no matching key found in the KeyStore', - JWSInvalid: 'JWS invalid', - JWSVerificationFailed: 'signature verification failed' -} +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. -class JOSEError extends Error { - constructor (message) { - super(message) - if (message === undefined) { - this.message = DEFAULT_MESSAGES[this.constructor.name] - } - this.name = this.constructor.name - this.code = CODES[this.constructor.name] - Error.captureStackTrace(this, this.constructor) - } -} +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ -const isMulti = e => e instanceof JOSEMultiError -class JOSEMultiError extends JOSEError { - constructor (errors) { - super() - let i - while ((i = errors.findIndex(isMulti)) && i !== -1) { - errors.splice(i, 1, ...errors[i]) +/* global global, define, System, Reflect, Promise */ +var __extends; +var __assign; +var __rest; +var __decorate; +var __param; +var __metadata; +var __awaiter; +var __generator; +var __exportStar; +var __values; +var __read; +var __spread; +var __spreadArrays; +var __await; +var __asyncGenerator; +var __asyncDelegator; +var __asyncValues; +var __makeTemplateObject; +var __importStar; +var __importDefault; +var __classPrivateFieldGet; +var __classPrivateFieldSet; +var __createBinding; +(function (factory) { + var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; + if (typeof define === "function" && define.amd) { + define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); } - Object.defineProperty(this, 'errors', { value: errors }) - } - - * [Symbol.iterator] () { - for (const error of this.errors) { - yield error + else if ( true && typeof module.exports === "object") { + factory(createExporter(root, createExporter(module.exports))); } - } -} -module.exports.JOSEError = JOSEError - -module.exports.JOSEAlgNotWhitelisted = class JOSEAlgNotWhitelisted extends JOSEError {} -module.exports.JOSECritNotUnderstood = class JOSECritNotUnderstood extends JOSEError {} -module.exports.JOSEInvalidEncoding = class JOSEInvalidEncoding extends JOSEError {} -module.exports.JOSEMultiError = JOSEMultiError -module.exports.JOSENotSupported = class JOSENotSupported extends JOSEError {} - -module.exports.JWEDecryptionFailed = class JWEDecryptionFailed extends JOSEError {} -module.exports.JWEInvalid = class JWEInvalid extends JOSEError {} - -module.exports.JWKImportFailed = class JWKImportFailed extends JOSEError {} -module.exports.JWKInvalid = class JWKInvalid extends JOSEError {} -module.exports.JWKKeySupport = class JWKKeySupport extends JOSEError {} - -module.exports.JWKSNoMatchingKey = class JWKSNoMatchingKey extends JOSEError {} - -module.exports.JWSInvalid = class JWSInvalid extends JOSEError {} -module.exports.JWSVerificationFailed = class JWSVerificationFailed extends JOSEError {} - -class JWTClaimInvalid extends JOSEError { - constructor (message, claim = 'unspecified', reason = 'unspecified') { - super(message) - this.claim = claim - this.reason = reason - } -} -module.exports.JWTClaimInvalid = JWTClaimInvalid -module.exports.JWTExpired = class JWTExpired extends JWTClaimInvalid {} -module.exports.JWTMalformed = class JWTMalformed extends JOSEError {} - - -/***/ }), - -/***/ 3006: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const oids = __nccwpck_require__(33875) - -module.exports = function () { - this.seq().obj( - this.key('algorithm').objid(oids), - this.key('parameters').optional().choice({ namedCurve: this.objid(oids), null: this.null_() }) - ) -} - - -/***/ }), - -/***/ 19377: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const oids = __nccwpck_require__(33875) - -module.exports = function () { - this.seq().obj( - this.key('version').int(), - this.key('privateKey').octstr(), - this.key('parameters').explicit(0).optional().choice({ namedCurve: this.objid(oids) }), - this.key('publicKey').explicit(1).optional().bitstr() - ) -} - - -/***/ }), - -/***/ 77456: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const asn1 = __nccwpck_require__(39436) - -const types = new Map() - -const AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', __nccwpck_require__(3006)) -types.set('AlgorithmIdentifier', AlgorithmIdentifier) - -const ECPrivateKey = asn1.define('ECPrivateKey', __nccwpck_require__(19377)) -types.set('ECPrivateKey', ECPrivateKey) - -const PrivateKeyInfo = asn1.define('PrivateKeyInfo', __nccwpck_require__(37542)(AlgorithmIdentifier)) -types.set('PrivateKeyInfo', PrivateKeyInfo) - -const PublicKeyInfo = asn1.define('PublicKeyInfo', __nccwpck_require__(26331)(AlgorithmIdentifier)) -types.set('PublicKeyInfo', PublicKeyInfo) - -const PrivateKey = asn1.define('PrivateKey', __nccwpck_require__(10815)) -types.set('PrivateKey', PrivateKey) - -const OneAsymmetricKey = asn1.define('OneAsymmetricKey', __nccwpck_require__(64800)(AlgorithmIdentifier, PrivateKey)) -types.set('OneAsymmetricKey', OneAsymmetricKey) - -const RSAPrivateKey = asn1.define('RSAPrivateKey', __nccwpck_require__(83407)) -types.set('RSAPrivateKey', RSAPrivateKey) - -const RSAPublicKey = asn1.define('RSAPublicKey', __nccwpck_require__(457)) -types.set('RSAPublicKey', RSAPublicKey) - -module.exports = types - + else { + factory(createExporter(root)); + } + function createExporter(exports, previous) { + if (exports !== root) { + if (typeof Object.create === "function") { + Object.defineProperty(exports, "__esModule", { value: true }); + } + else { + exports.__esModule = true; + } + } + return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; + } +}) +(function (exporter) { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; -/***/ }), + __extends = function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; -/***/ 33875: -/***/ ((module) => { + __assign = Object.assign || function (t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; -const oids = { - '1 2 840 10045 3 1 7': 'P-256', - '1 3 132 0 10': 'secp256k1', - '1 3 132 0 34': 'P-384', - '1 3 132 0 35': 'P-521', - '1 2 840 10045 2 1': 'ecPublicKey', - '1 2 840 113549 1 1 1': 'rsaEncryption', - '1 3 101 110': 'X25519', - '1 3 101 111': 'X448', - '1 3 101 112': 'Ed25519', - '1 3 101 113': 'Ed448' -} + __rest = function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + }; -module.exports = oids + __decorate = function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + __param = function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; -/***/ }), + __metadata = function (metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + }; -/***/ 64800: -/***/ ((module) => { + __awaiter = function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; -module.exports = (AlgorithmIdentifier, PrivateKey) => function () { - this.seq().obj( - this.key('version').int(), - this.key('algorithm').use(AlgorithmIdentifier), - this.key('privateKey').use(PrivateKey) - ) -} + __generator = function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + __createBinding = function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }; -/***/ }), + __exportStar = function (m, exports) { + for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) exports[p] = m[p]; + }; -/***/ 10815: -/***/ ((module) => { + __values = function (o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; -module.exports = function () { - this.octstr().contains().obj( - this.key('privateKey').octstr() - ) -} + __read = function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + __spread = function () { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; + }; -/***/ }), + __spreadArrays = function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; + }; -/***/ 37542: -/***/ ((module) => { + __await = function (v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; -module.exports = (AlgorithmIdentifier) => function () { - this.seq().obj( - this.key('version').int(), - this.key('algorithm').use(AlgorithmIdentifier), - this.key('privateKey').octstr() - ) -} + __asyncGenerator = function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + }; + __asyncDelegator = function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } + }; -/***/ }), + __asyncValues = function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + }; -/***/ 26331: -/***/ ((module) => { + __makeTemplateObject = function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; + }; -module.exports = AlgorithmIdentifier => function () { - this.seq().obj( - this.key('algorithm').use(AlgorithmIdentifier), - this.key('publicKey').bitstr() - ) -} + __importStar = function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; + }; + __importDefault = function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; -/***/ }), + __classPrivateFieldGet = function (receiver, privateMap) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to get private field on non-instance"); + } + return privateMap.get(receiver); + }; -/***/ 83407: -/***/ ((module) => { + __classPrivateFieldSet = function (receiver, privateMap, value) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to set private field on non-instance"); + } + privateMap.set(receiver, value); + return value; + }; -module.exports = function () { - this.seq().obj( - this.key('version').int({ 0: 'two-prime', 1: 'multi' }), - this.key('n').int(), - this.key('e').int(), - this.key('d').int(), - this.key('p').int(), - this.key('q').int(), - this.key('dp').int(), - this.key('dq').int(), - this.key('qi').int() - ) -} + exporter("__extends", __extends); + exporter("__assign", __assign); + exporter("__rest", __rest); + exporter("__decorate", __decorate); + exporter("__param", __param); + exporter("__metadata", __metadata); + exporter("__awaiter", __awaiter); + exporter("__generator", __generator); + exporter("__exportStar", __exportStar); + exporter("__createBinding", __createBinding); + exporter("__values", __values); + exporter("__read", __read); + exporter("__spread", __spread); + exporter("__spreadArrays", __spreadArrays); + exporter("__await", __await); + exporter("__asyncGenerator", __asyncGenerator); + exporter("__asyncDelegator", __asyncDelegator); + exporter("__asyncValues", __asyncValues); + exporter("__makeTemplateObject", __makeTemplateObject); + exporter("__importStar", __importStar); + exporter("__importDefault", __importDefault); + exporter("__classPrivateFieldGet", __classPrivateFieldGet); + exporter("__classPrivateFieldSet", __classPrivateFieldSet); +}); /***/ }), -/***/ 457: +/***/ 40334: /***/ ((module) => { -module.exports = function () { - this.seq().obj( - this.key('n').int(), - this.key('e').int() - ) -} - - -/***/ }), - -/***/ 93312: -/***/ ((module) => { +"use strict"; -let encode -let encodeBuffer -if (Buffer.isEncoding('base64url')) { - encode = (input, encoding = 'utf8') => Buffer.from(input, encoding).toString('base64url') - encodeBuffer = (buf) => buf.toString('base64url') -} else { - const fromBase64 = (base64) => base64.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_') - encode = (input, encoding = 'utf8') => fromBase64(Buffer.from(input, encoding).toString('base64')) - encodeBuffer = (buf) => fromBase64(buf.toString('base64')) -} +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 decodeToBuffer = (input) => { - return Buffer.from(input, 'base64') -} +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + createTokenAuth: () => createTokenAuth +}); +module.exports = __toCommonJS(dist_src_exports); -const decode = (input, encoding = 'utf8') => { - return decodeToBuffer(input).toString(encoding) +// 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 + }; } -const b64uJSON = { - encode: (input) => { - return encode(JSON.stringify(input)) - }, - decode: (input, encoding = 'utf8') => { - return JSON.parse(decode(input, encoding)) +// pkg/dist-src/with-authorization-prefix.js +function withAuthorizationPrefix(token) { + if (token.split(/\./).length === 3) { + return `bearer ${token}`; } + return `token ${token}`; } -b64uJSON.decode.try = (input, encoding = 'utf8') => { - try { - return b64uJSON.decode(input, encoding) - } catch (err) { - return decode(input, encoding) - } +// 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); } -const bnToBuf = (bn) => { - let hex = BigInt(bn).toString(16) - if (hex.length % 2) { - hex = `0${hex}` +// pkg/dist-src/index.js +var createTokenAuth = function createTokenAuth2(token) { + if (!token) { + throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); } - - const len = hex.length / 2 - const u8 = new Uint8Array(len) - - let i = 0 - let j = 0 - while (i < len) { - u8[i] = parseInt(hex.slice(j, j + 2), 16) - i += 1 - j += 2 + if (typeof token !== "string") { + throw new Error( + "[@octokit/auth-token] Token passed to createTokenAuth is not a string" + ); } - - return u8 -} - -const encodeBigInt = (bn) => encodeBuffer(Buffer.from(bnToBuf(bn))) - -module.exports.decode = decode -module.exports.decodeToBuffer = decodeToBuffer -module.exports.encode = encode -module.exports.encodeBuffer = encodeBuffer -module.exports.JSON = b64uJSON -module.exports.encodeBigInt = encodeBigInt - - -/***/ }), - -/***/ 62928: -/***/ ((module) => { - -module.exports.KEYOBJECT = Symbol('KEYOBJECT') -module.exports.PRIVATE_MEMBERS = Symbol('PRIVATE_MEMBERS') -module.exports.PUBLIC_MEMBERS = Symbol('PUBLIC_MEMBERS') -module.exports.THUMBPRINT_MATERIAL = Symbol('THUMBPRINT_MATERIAL') -module.exports.JWK_MEMBERS = Symbol('JWK_MEMBERS') -module.exports.KEY_MANAGEMENT_ENCRYPT = Symbol('KEY_MANAGEMENT_ENCRYPT') -module.exports.KEY_MANAGEMENT_DECRYPT = Symbol('KEY_MANAGEMENT_DECRYPT') - -const USES_MAPPING = { - sig: new Set(['sign', 'verify']), - enc: new Set(['encrypt', 'decrypt', 'wrapKey', 'unwrapKey', 'deriveKey']) -} -const OPS = new Set([...USES_MAPPING.sig, ...USES_MAPPING.enc]) -const USES = new Set(Object.keys(USES_MAPPING)) - -module.exports.USES_MAPPING = USES_MAPPING -module.exports.OPS = OPS -module.exports.USES = USES + 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); /***/ }), -/***/ 52083: -/***/ ((module) => { - -module.exports = obj => JSON.parse(JSON.stringify(obj)) - - -/***/ }), +/***/ 76762: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/***/ 64575: -/***/ ((module) => { +"use strict"; -const MAX_OCTET = 0x80 -const CLASS_UNIVERSAL = 0 -const PRIMITIVE_BIT = 0x20 -const TAG_SEQ = 0x10 -const TAG_INT = 0x02 -const ENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6) -const ENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6) +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 getParamSize = keySize => ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1) +// 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__(45030); +var import_before_after_hook = __nccwpck_require__(83682); +var import_request = __nccwpck_require__(36234); +var import_graphql = __nccwpck_require__(88467); +var import_auth_token = __nccwpck_require__(40334); -const paramBytesForAlg = { - ES256: getParamSize(256), - ES256K: getParamSize(256), - ES384: getParamSize(384), - ES512: getParamSize(521) -} +// pkg/dist-src/version.js +var VERSION = "5.1.0"; -const countPadding = (buf, start, stop) => { - let padding = 0 - while (start + padding < stop && buf[start + padding] === 0) { - ++padding +// 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; } - - const needsSign = buf[start + padding] >= MAX_OCTET - if (needsSign) { - --padding + 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; } - - return padding -} - -module.exports.derToJose = (signature, alg) => { - if (!Buffer.isBuffer(signature)) { - throw new TypeError('ECDSA signature must be a Buffer') + static { + this.plugins = []; } - - if (!paramBytesForAlg[alg]) { - throw new Error(`Unknown algorithm "${alg}"`) + /** + * 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); - const paramBytes = paramBytesForAlg[alg] - // the DER encoded param should at most be the param size, plus a padding - // zero, since due to being a signed integer - const maxEncodedParamLength = paramBytes + 1 +/***/ }), - const inputLength = signature.length +/***/ 59440: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - let offset = 0 - if (signature[offset++] !== ENCODED_TAG_SEQ) { - throw new Error('Could not find expected "seq"') - } +"use strict"; - let seqLength = signature[offset++] - if (seqLength === (MAX_OCTET | 1)) { - seqLength = signature[offset++] +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 (inputLength - offset < seqLength) { - throw new Error(`"seq" specified length of ${seqLength}", only ${inputLength - offset}" remaining`) - } +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + endpoint: () => endpoint +}); +module.exports = __toCommonJS(dist_src_exports); - if (signature[offset++] !== ENCODED_TAG_INT) { - throw new Error('Could not find expected "int" for "r"') - } +// pkg/dist-src/defaults.js +var import_universal_user_agent = __nccwpck_require__(45030); - const rLength = signature[offset++] +// pkg/dist-src/version.js +var VERSION = "9.0.6"; - if (inputLength - offset - 2 < rLength) { - throw new Error(`"r" specified length of "${rLength}", only "${inputLength - offset - 2}" available`) +// 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: "" } +}; - if (maxEncodedParamLength < rLength) { - throw new Error(`"r" specified length of "${rLength}", max of "${maxEncodedParamLength}" is acceptable`) +// 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; + }, {}); +} - const rOffset = offset - offset += rLength - - if (signature[offset++] !== ENCODED_TAG_INT) { - throw new Error('Could not find expected "int" for "s"') - } +// 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); +} - const sLength = signature[offset++] +// 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; +} - if (inputLength - offset !== sLength) { - throw new Error(`"s" specified length of "${sLength}", expected "${inputLength - offset}"`) +// 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; +} - if (maxEncodedParamLength < sLength) { - throw new Error(`"s" specified length of "${sLength}", max of "${maxEncodedParamLength}" is acceptable`) +// 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); } - - const sOffset = offset - offset += sLength - - if (offset !== inputLength) { - throw new Error(`Expected to consume entire buffer, but "${inputLength - offset}" bytes remain`) + 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 rPadding = paramBytes - rLength - - const sPadding = paramBytes - sLength - - const dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength) - - for (offset = 0; offset < rPadding; ++offset) { - dst[offset] = 0 +// 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; } - signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength) - - offset = paramBytes + return url + separator + names.map((name) => { + if (name === "q") { + return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); + } + return `${name}=${encodeURIComponent(parameters[name])}`; + }).join("&"); +} - for (const o = offset; offset < o + sPadding; ++offset) { - dst[offset] = 0 +// pkg/dist-src/util/extract-url-variable-names.js +var urlVariableRegex = /\{[^{}}]+\}/g; +function removeNonChars(variableName) { + return variableName.replace(/(?:^\W+)|(?:(? a.concat(b), []); } -module.exports.joseToDer = (signature, alg) => { - if (!Buffer.isBuffer(signature)) { - throw new TypeError('ECDSA signature must be a Buffer') +// 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; +} - if (!paramBytesForAlg[alg]) { - throw new TypeError(`Unknown algorithm "${alg}"`) +// 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; } - - const paramBytes = paramBytesForAlg[alg] - - const signatureBytes = signature.length - if (signatureBytes !== paramBytes * 2) { - throw new Error(`"${alg}" signatures must be "${paramBytes * 2}" bytes, saw "${signatureBytes}"`) - } - - const rPadding = countPadding(signature, 0, paramBytes) - const sPadding = countPadding(signature, paramBytes, signature.length) - const rLength = paramBytes - rPadding - const sLength = paramBytes - sPadding - - const rsBytes = 1 + 1 + rLength + 1 + 1 + sLength - - const shortLength = rsBytes < MAX_OCTET - - const dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes) - - let offset = 0 - dst[offset++] = ENCODED_TAG_SEQ - if (shortLength) { - // Bit 8 has value "0" - // bits 7-1 give the length. - dst[offset++] = rsBytes +} +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 { - // Bit 8 of first octet has value "1" - // bits 7-1 give the number of additional length octets. - dst[offset++] = MAX_OCTET | 1 // eslint-disable-line no-tabs - // length, base 256 - dst[offset++] = rsBytes & 0xff + if (operator === ";") { + if (isDefined(value)) { + result.push(encodeUnreserved(key)); + } + } else if (value === "" && (operator === "&" || operator === "?")) { + result.push(encodeUnreserved(key) + "="); + } else if (value === "") { + result.push(""); + } } - dst[offset++] = ENCODED_TAG_INT - dst[offset++] = rLength - if (rPadding < 0) { - dst[offset++] = 0 - offset += signature.copy(dst, offset, 0, paramBytes) + 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 { - offset += signature.copy(dst, offset, rPadding, paramBytes) + return template.replace(/\/$/, ""); } - dst[offset++] = ENCODED_TAG_INT - dst[offset++] = sLength - if (sPadding < 0) { - dst[offset++] = 0 - signature.copy(dst, offset, paramBytes) +} + +// 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(/(? { + 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 { - signature.copy(dst, offset, paramBytes + sPadding) + if ("data" in remainingParameters) { + body = remainingParameters.data; + } else { + if (Object.keys(remainingParameters).length) { + body = remainingParameters; + } + } } - - return dst + 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)); +} -/***/ }), - -/***/ 33773: -/***/ ((module) => { +// 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 = (date) => Math.floor(date.getTime() / 1000) +// pkg/dist-src/index.js +var endpoint = withDefaults(null, DEFAULTS); +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 3796: +/***/ 88467: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const { randomBytes } = __nccwpck_require__(6113) - -const { IVLENGTHS } = __nccwpck_require__(47359) +"use strict"; -module.exports = alg => randomBytes(IVLENGTHS.get(alg) / 8) +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__(36234); +var import_universal_user_agent = __nccwpck_require__(45030); -/***/ }), +// pkg/dist-src/version.js +var VERSION = "7.0.2"; -/***/ 7090: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// pkg/dist-src/with-defaults.js +var import_request2 = __nccwpck_require__(36234); -const errors = __nccwpck_require__(35132) -const Key = __nccwpck_require__(99795) -const importKey = __nccwpck_require__(77722) -const { KeyStore } = __nccwpck_require__(44201) +// pkg/dist-src/graphql.js +var import_request = __nccwpck_require__(36234); -module.exports = (input, keyStoreAllowed = false) => { - if (input instanceof Key) { - return input +// 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); + } } +}; - if (input instanceof KeyStore) { - if (!keyStoreAllowed) { - throw new TypeError('key argument for this operation must not be a JWKS.KeyStore instance') +// 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` + ) + ); } - - return input } - - try { - return importKey(input) - } catch (err) { - if (err instanceof errors.JOSEError && !(err instanceof errors.JWKImportFailed)) { - throw err + 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; } - - let msg - if (keyStoreAllowed) { - msg = 'key must be an instance of a key instantiated by JWK.asKey, a valid JWK.asKey input, or a JWKS.KeyStore instance' - } else { - msg = 'key must be an instance of a key instantiated by JWK.asKey, or a valid JWK.asKey input' + if (!result.variables) { + result.variables = {}; } - - throw new TypeError(msg) + 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 + }); +} -/***/ }), - -/***/ 48899: -/***/ ((module) => { - -module.exports = (a = {}, b = {}) => { - const keysA = Object.keys(a) - const keysB = new Set(Object.keys(b)) - return !keysA.some((ka) => keysB.has(ka)) +// 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); /***/ }), -/***/ 50243: +/***/ 64193: /***/ ((module) => { -module.exports = a => !!a && a.constructor === Object - - -/***/ }), - -/***/ 31032: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { keyObjectSupported } = __nccwpck_require__(57494) - -let createPublicKey -let createPrivateKey -let createSecretKey -let KeyObject -let asInput - -if (keyObjectSupported) { - ({ createPublicKey, createPrivateKey, createSecretKey, KeyObject } = __nccwpck_require__(6113)) - asInput = (input) => input -} else { - const { EOL } = __nccwpck_require__(22037) +"use strict"; - const errors = __nccwpck_require__(35132) - const isObject = __nccwpck_require__(50243) - const asn1 = __nccwpck_require__(77456) - const toInput = Symbol('toInput') +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 namedCurve = Symbol('namedCurve') +// 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); - asInput = (keyObject, needsPublic) => { - if (keyObject instanceof KeyObject) { - return keyObject[toInput](needsPublic) - } +// pkg/dist-src/version.js +var VERSION = "9.2.2"; - return createSecretKey(keyObject)[toInput](needsPublic) +// pkg/dist-src/normalize-paginated-list-response.js +function normalizePaginatedListResponse(response) { + if (!response.data) { + return { + ...response, + data: [] + }; } - - const pemToDer = pem => Buffer.from(pem.replace(/(?:-----(?:BEGIN|END)(?: (?:RSA|EC))? (?:PRIVATE|PUBLIC) KEY-----|\s)/g, ''), 'base64') - const derToPem = (der, label) => `-----BEGIN ${label}-----${EOL}${(der.toString('base64').match(/.{1,64}/g) || []).join(EOL)}${EOL}-----END ${label}-----` - const unsupported = (input) => { - const label = typeof input === 'string' ? input : `OID ${input.join('.')}` - throw new errors.JOSENotSupported(`${label} is not supported in your Node.js runtime 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; } + if (typeof repositorySelection !== "undefined") { + response.data.repository_selection = repositorySelection; + } + response.data.total_count = totalCount; + return response; +} - KeyObject = class KeyObject { - export ({ cipher, passphrase, type, format } = {}) { - if (this._type === 'secret') { - return this._buffer - } - - if (this._type === 'public') { - if (this.asymmetricKeyType === 'rsa') { - switch (type) { - case 'pkcs1': - if (format === 'pem') { - return this._pem - } - - return pemToDer(this._pem) - case 'spki': { - const PublicKeyInfo = asn1.get('PublicKeyInfo') - const pem = PublicKeyInfo.encode({ - algorithm: { - algorithm: 'rsaEncryption', - parameters: { type: 'null' } - }, - publicKey: { - unused: 0, - data: pemToDer(this._pem) - } - }, 'pem', { label: 'PUBLIC KEY' }) - - return format === 'pem' ? pem : pemToDer(pem) - } - default: - throw new TypeError(`The value ${type} is invalid for option "type"`) - } - } - - if (this.asymmetricKeyType === 'ec') { - if (type !== 'spki') { - throw new TypeError(`The value ${type} is invalid for option "type"`) - } - - if (format === 'pem') { - return this._pem - } - - return pemToDer(this._pem) - } - } - - if (this._type === 'private') { - if (passphrase !== undefined || cipher !== undefined) { - throw new errors.JOSENotSupported('encrypted private keys are not supported in your Node.js runtime version') - } - - if (type === 'pkcs8') { - if (this._pkcs8) { - if (format === 'der' && typeof this._pkcs8 === 'string') { - return pemToDer(this._pkcs8) - } - - if (format === 'pem' && Buffer.isBuffer(this._pkcs8)) { - return derToPem(this._pkcs8, 'PRIVATE KEY') +// 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: [] } - - return this._pkcs8 - } - - if (this.asymmetricKeyType === 'rsa') { - const parsed = this._asn1 - const RSAPrivateKey = asn1.get('RSAPrivateKey') - const privateKey = RSAPrivateKey.encode(parsed) - const PrivateKeyInfo = asn1.get('PrivateKeyInfo') - const pkcs8 = PrivateKeyInfo.encode({ - version: 0, - privateKey, - algorithm: { - algorithm: 'rsaEncryption', - parameters: { type: 'null' } - } - }) - - this._pkcs8 = pkcs8 - - return this.export({ type, format }) - } - - if (this.asymmetricKeyType === 'ec') { - const parsed = this._asn1 - const ECPrivateKey = asn1.get('ECPrivateKey') - const privateKey = ECPrivateKey.encode({ - version: parsed.version, - privateKey: parsed.privateKey, - publicKey: parsed.publicKey - }) - const PrivateKeyInfo = asn1.get('PrivateKeyInfo') - const pkcs8 = PrivateKeyInfo.encode({ - version: 0, - privateKey, - algorithm: { - algorithm: 'ecPublicKey', - parameters: this._asn1.parameters - } - }) - - this._pkcs8 = pkcs8 - - return this.export({ type, format }) - } - } - - if (this.asymmetricKeyType === 'rsa' && type === 'pkcs1') { - if (format === 'pem') { - return this._pem - } - - return pemToDer(this._pem) - } else if (this.asymmetricKeyType === 'ec' && type === 'sec1') { - if (format === 'pem') { - return this._pem - } - - return pemToDer(this._pem) - } else { - throw new TypeError(`The value ${type} is invalid for option "type"`) + }; } } - } + }) + }; +} - get type () { - return this._type +// 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; } - - get asymmetricKeyType () { - return this._asymmetricKeyType + let earlyExit = false; + function done() { + earlyExit = true; } - - get symmetricKeySize () { - return this._symmetricKeySize + results = results.concat( + mapFn ? mapFn(result.value, done) : result.value.data + ); + if (earlyExit) { + return results; } + return gather(octokit, results, iterator2, mapFn); + }); +} - [toInput] (needsPublic) { - switch (this._type) { - case 'secret': - return this._buffer - case 'public': - return this._pem - default: - if (needsPublic) { - if (!('_pub' in this)) { - this._pub = createPublicKey(this) - } +// pkg/dist-src/compose-paginate.js +var composePaginateRest = Object.assign(paginate, { + iterator +}); - return this._pub[toInput](false) - } +// 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" +]; - return this._pem - } - } +// pkg/dist-src/paginating-endpoints.js +function isPaginatingEndpoint(arg) { + if (typeof arg === "string") { + return paginatingEndpoints.includes(arg); + } else { + return false; } +} - createSecretKey = (buffer) => { - if (!Buffer.isBuffer(buffer) || !buffer.length) { - throw new TypeError('input must be a non-empty Buffer instance') - } +// 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); - const keyObject = new KeyObject() - keyObject._buffer = Buffer.from(buffer) - keyObject._symmetricKeySize = buffer.length - keyObject._type = 'secret' - return keyObject - } +/***/ }), - createPublicKey = (input) => { - if (input instanceof KeyObject) { - if (input.type !== 'private') { - throw new TypeError(`Invalid key object type ${input.type}, expected private.`) - } +/***/ 83044: +/***/ ((module) => { - switch (input.asymmetricKeyType) { - case 'ec': { - const PublicKeyInfo = asn1.get('PublicKeyInfo') - const key = PublicKeyInfo.encode({ - algorithm: { - algorithm: 'ecPublicKey', - parameters: input._asn1.parameters - }, - publicKey: input._asn1.publicKey - }) +"use strict"; - return createPublicKey({ key, format: 'der', type: 'spki' }) - } - case 'rsa': { - const RSAPublicKey = asn1.get('RSAPublicKey') - const key = RSAPublicKey.encode(input._asn1) - return createPublicKey({ key, format: 'der', type: 'pkcs1' }) - } - } - } +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 (typeof input === 'string' || Buffer.isBuffer(input)) { - input = { key: input, format: 'pem' } - } +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + legacyRestEndpointMethods: () => legacyRestEndpointMethods, + restEndpointMethods: () => restEndpointMethods +}); +module.exports = __toCommonJS(dist_src_exports); - if (!isObject(input)) { - throw new TypeError('input must be a string, Buffer or an object') - } +// pkg/dist-src/version.js +var VERSION = "10.3.0"; - const { format, passphrase } = input - let { key, type } = input - - if (typeof key !== 'string' && !Buffer.isBuffer(key)) { - throw new TypeError('key must be a string or Buffer') - } - - if (format !== 'pem' && format !== 'der') { - throw new TypeError('format must be one of "pem" or "der"') - } - - let label - if (format === 'pem') { - key = key.toString() - switch (key.split(/\r?\n/g)[0].toString()) { - case '-----BEGIN PUBLIC KEY-----': - type = 'spki' - label = 'PUBLIC KEY' - break - case '-----BEGIN RSA PUBLIC KEY-----': - type = 'pkcs1' - label = 'RSA PUBLIC KEY' - break - case '-----BEGIN CERTIFICATE-----': - throw new errors.JOSENotSupported('X.509 certificates are not supported in your Node.js runtime version') - case '-----BEGIN PRIVATE KEY-----': - case '-----BEGIN EC PRIVATE KEY-----': - case '-----BEGIN RSA PRIVATE KEY-----': - return createPublicKey(createPrivateKey(key)) - default: - throw new TypeError('unknown/unsupported PEM type') - } - } - - switch (type) { - case 'spki': { - const PublicKeyInfo = asn1.get('PublicKeyInfo') - const parsed = PublicKeyInfo.decode(key, format, { label }) - - let type, keyObject - switch (parsed.algorithm.algorithm) { - case 'ecPublicKey': { - keyObject = new KeyObject() - keyObject._asn1 = parsed - keyObject._asymmetricKeyType = 'ec' - keyObject._type = 'public' - keyObject._pem = PublicKeyInfo.encode(parsed, 'pem', { label: 'PUBLIC KEY' }) - - break - } - case 'rsaEncryption': { - type = 'pkcs1' - keyObject = createPublicKey({ type, key: parsed.publicKey.data, format: 'der' }) - break - } - default: - unsupported(parsed.algorithm.algorithm) - } - - return keyObject - } - case 'pkcs1': { - const RSAPublicKey = asn1.get('RSAPublicKey') - const parsed = RSAPublicKey.decode(key, format, { label }) - - // special case when private pkcs1 PEM / DER is used with createPublicKey - if (parsed.n === BigInt(0)) { - return createPublicKey(createPrivateKey({ key, format, type, passphrase })) - } - - const keyObject = new KeyObject() - keyObject._asn1 = parsed - keyObject._asymmetricKeyType = 'rsa' - keyObject._type = 'public' - keyObject._pem = RSAPublicKey.encode(parsed, 'pem', { label: 'RSA PUBLIC KEY' }) - - return keyObject - } - case 'pkcs8': - case 'sec1': - return createPublicKey(createPrivateKey({ format, key, type, passphrase })) - default: - throw new TypeError(`The value ${type} is invalid for option "type"`) - } - } - - createPrivateKey = (input, hints) => { - if (typeof input === 'string' || Buffer.isBuffer(input)) { - input = { key: input, format: 'pem' } - } - - if (!isObject(input)) { - throw new TypeError('input must be a string, Buffer or an object') - } - - const { format, passphrase } = input - let { key, type } = input - - if (typeof key !== 'string' && !Buffer.isBuffer(key)) { - throw new TypeError('key must be a string or Buffer') - } - - if (passphrase !== undefined) { - throw new errors.JOSENotSupported('encrypted private keys are not supported in your Node.js runtime version') - } - - if (format !== 'pem' && format !== 'der') { - throw new TypeError('format must be one of "pem" or "der"') - } - - let label - if (format === 'pem') { - key = key.toString() - switch (key.split(/\r?\n/g)[0].toString()) { - case '-----BEGIN PRIVATE KEY-----': - type = 'pkcs8' - label = 'PRIVATE KEY' - break - case '-----BEGIN EC PRIVATE KEY-----': - type = 'sec1' - label = 'EC PRIVATE KEY' - break - case '-----BEGIN RSA PRIVATE KEY-----': - type = 'pkcs1' - label = 'RSA PRIVATE KEY' - break - default: - throw new TypeError('unknown/unsupported PEM type') - } - } - - switch (type) { - case 'pkcs8': { - const PrivateKeyInfo = asn1.get('PrivateKeyInfo') - const parsed = PrivateKeyInfo.decode(key, format, { label }) - - let type, keyObject - switch (parsed.algorithm.algorithm) { - case 'ecPublicKey': { - type = 'sec1' - keyObject = createPrivateKey({ type, key: parsed.privateKey, format: 'der' }, { [namedCurve]: parsed.algorithm.parameters.value }) - break - } - case 'rsaEncryption': { - type = 'pkcs1' - keyObject = createPrivateKey({ type, key: parsed.privateKey, format: 'der' }) - break - } - default: - unsupported(parsed.algorithm.algorithm) - } - - keyObject._pkcs8 = key - return keyObject - } - case 'pkcs1': { - const RSAPrivateKey = asn1.get('RSAPrivateKey') - const parsed = RSAPrivateKey.decode(key, format, { label }) - - const keyObject = new KeyObject() - keyObject._asn1 = parsed - keyObject._asymmetricKeyType = 'rsa' - keyObject._type = 'private' - keyObject._pem = RSAPrivateKey.encode(parsed, 'pem', { label: 'RSA PRIVATE KEY' }) - - return keyObject - } - case 'sec1': { - const ECPrivateKey = asn1.get('ECPrivateKey') - let parsed = ECPrivateKey.decode(key, format, { label }) - - if (!('parameters' in parsed) && !hints[namedCurve]) { - throw new Error('invalid sec1') - } else if (!('parameters' in parsed)) { - parsed = { ...parsed, parameters: { type: 'namedCurve', value: hints[namedCurve] } } - } - - const keyObject = new KeyObject() - keyObject._asn1 = parsed - keyObject._asymmetricKeyType = 'ec' - keyObject._type = 'private' - keyObject._pem = ECPrivateKey.encode(parsed, 'pem', { label: 'EC PRIVATE KEY' }) - - return keyObject - } - default: - throw new TypeError(`The value ${type} is invalid for option "type"`) - } - } -} - -module.exports = { createPublicKey, createPrivateKey, createSecretKey, KeyObject, asInput } - - -/***/ }), - -/***/ 65394: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { EOL } = __nccwpck_require__(22037) - -const errors = __nccwpck_require__(35132) - -const { keyObjectSupported } = __nccwpck_require__(57494) -const { createPublicKey } = __nccwpck_require__(31032) -const base64url = __nccwpck_require__(93312) -const asn1 = __nccwpck_require__(77456) -const computePrimes = __nccwpck_require__(4438) -const { OKP_CURVES, EC_CURVES } = __nccwpck_require__(47359) - -const formatPem = (base64pem, descriptor) => `-----BEGIN ${descriptor} KEY-----${EOL}${(base64pem.match(/.{1,64}/g) || []).join(EOL)}${EOL}-----END ${descriptor} KEY-----` - -const okpToJWK = { - private (crv, keyObject) { - const der = keyObject.export({ type: 'pkcs8', format: 'der' }) - const OneAsymmetricKey = asn1.get('OneAsymmetricKey') - const { privateKey: { privateKey: d } } = OneAsymmetricKey.decode(der) - - return { - ...okpToJWK.public(crv, createPublicKey(keyObject)), - d: base64url.encodeBuffer(d) - } - }, - public (crv, keyObject) { - const der = keyObject.export({ type: 'spki', format: 'der' }) - - const PublicKeyInfo = asn1.get('PublicKeyInfo') - - const { publicKey: { data: x } } = PublicKeyInfo.decode(der) - - return { - kty: 'OKP', - crv, - x: base64url.encodeBuffer(x) - } - } -} - -const keyObjectToJWK = { - rsa: { - private (keyObject) { - const der = keyObject.export({ type: 'pkcs8', format: 'der' }) - - const PrivateKeyInfo = asn1.get('PrivateKeyInfo') - const RSAPrivateKey = asn1.get('RSAPrivateKey') - - const { privateKey } = PrivateKeyInfo.decode(der) - const { version, n, e, d, p, q, dp, dq, qi } = RSAPrivateKey.decode(privateKey) - - if (version !== 'two-prime') { - throw new errors.JOSENotSupported('Private RSA keys with more than two primes are not supported') - } - - return { - kty: 'RSA', - n: base64url.encodeBigInt(n), - e: base64url.encodeBigInt(e), - d: base64url.encodeBigInt(d), - p: base64url.encodeBigInt(p), - q: base64url.encodeBigInt(q), - dp: base64url.encodeBigInt(dp), - dq: base64url.encodeBigInt(dq), - qi: base64url.encodeBigInt(qi) - } - }, - public (keyObject) { - const der = keyObject.export({ type: 'spki', format: 'der' }) - - const PublicKeyInfo = asn1.get('PublicKeyInfo') - const RSAPublicKey = asn1.get('RSAPublicKey') - - const { publicKey: { data: publicKey } } = PublicKeyInfo.decode(der) - const { n, e } = RSAPublicKey.decode(publicKey) - - return { - kty: 'RSA', - n: base64url.encodeBigInt(n), - e: base64url.encodeBigInt(e) - } - } +// 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}" + ] }, - ec: { - private (keyObject) { - const der = keyObject.export({ type: 'pkcs8', format: 'der' }) - - const PrivateKeyInfo = asn1.get('PrivateKeyInfo') - const ECPrivateKey = asn1.get('ECPrivateKey') - - const { privateKey, algorithm: { parameters: { value: crv } } } = PrivateKeyInfo.decode(der) - const { privateKey: d, publicKey } = ECPrivateKey.decode(privateKey) - - if (typeof publicKey === 'undefined') { - if (keyObjectSupported) { - return { - ...keyObjectToJWK.ec.public(createPublicKey(keyObject)), - d: base64url.encodeBuffer(d) - } - } - - throw new errors.JOSENotSupported('Private EC keys without the public key embedded are not supported in your Node.js runtime version') - } - - const x = publicKey.data.slice(1, ((publicKey.data.length - 1) / 2) + 1) - const y = publicKey.data.slice(((publicKey.data.length - 1) / 2) + 1) - - return { - kty: 'EC', - crv, - d: base64url.encodeBuffer(d), - x: base64url.encodeBuffer(x), - y: base64url.encodeBuffer(y) - } - }, - public (keyObject) { - const der = keyObject.export({ type: 'spki', format: 'der' }) - - const PublicKeyInfo = asn1.get('PublicKeyInfo') - - const { publicKey: { data: publicKey }, algorithm: { parameters: { value: crv } } } = PublicKeyInfo.decode(der) - - const x = publicKey.slice(1, ((publicKey.length - 1) / 2) + 1) - const y = publicKey.slice(((publicKey.length - 1) / 2) + 1) - - return { - kty: 'EC', - crv, - x: base64url.encodeBuffer(x), - y: base64url.encodeBuffer(y) - } - } + 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}"] }, - ed25519: { - private (keyObject) { - return okpToJWK.private('Ed25519', keyObject) - }, - public (keyObject) { - return okpToJWK.public('Ed25519', keyObject) - } + 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"] }, - ed448: { - private (keyObject) { - return okpToJWK.private('Ed448', keyObject) - }, - public (keyObject) { - return okpToJWK.public('Ed448', keyObject) - } + 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" + ] }, - x25519: { - private (keyObject) { - return okpToJWK.private('X25519', keyObject) - }, - public (keyObject) { - return okpToJWK.public('X25519', keyObject) - } + 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}"] }, - x448: { - private (keyObject) { - return okpToJWK.private('X448', keyObject) - }, - public (keyObject) { - return okpToJWK.public('X448', keyObject) - } - } -} - -module.exports.keyObjectToJWK = (keyObject) => { - if (keyObject.type === 'private') { - return keyObjectToJWK[keyObject.asymmetricKeyType].private(keyObject) - } - - return keyObjectToJWK[keyObject.asymmetricKeyType].public(keyObject) -} - -const concatEcPublicKey = (x, y) => ({ - unused: 0, - data: Buffer.concat([ - Buffer.alloc(1, 4), - base64url.decodeToBuffer(x), - base64url.decodeToBuffer(y) - ]) -}) - -const jwkToPem = { - RSA: { - private (jwk, { calculateMissingRSAPrimes }) { - const RSAPrivateKey = asn1.get('RSAPrivateKey') - - if ('oth' in jwk) { - throw new errors.JOSENotSupported('Private RSA keys with more than two primes are not supported') - } - - if (jwk.p || jwk.q || jwk.dp || jwk.dq || jwk.qi) { - if (!(jwk.p && jwk.q && jwk.dp && jwk.dq && jwk.qi)) { - throw new errors.JWKInvalid('all other private key parameters must be present when any one of them is present') - } - } else if (calculateMissingRSAPrimes) { - jwk = computePrimes(jwk) - } else if (!calculateMissingRSAPrimes) { - throw new errors.JOSENotSupported('importing private RSA keys without all other private key parameters is not enabled, see documentation and its advisory on how and when its ok to enable it') - } - - return RSAPrivateKey.encode({ - version: 0, - n: BigInt(`0x${base64url.decodeToBuffer(jwk.n).toString('hex')}`), - e: BigInt(`0x${base64url.decodeToBuffer(jwk.e).toString('hex')}`), - d: BigInt(`0x${base64url.decodeToBuffer(jwk.d).toString('hex')}`), - p: BigInt(`0x${base64url.decodeToBuffer(jwk.p).toString('hex')}`), - q: BigInt(`0x${base64url.decodeToBuffer(jwk.q).toString('hex')}`), - dp: BigInt(`0x${base64url.decodeToBuffer(jwk.dp).toString('hex')}`), - dq: BigInt(`0x${base64url.decodeToBuffer(jwk.dq).toString('hex')}`), - qi: BigInt(`0x${base64url.decodeToBuffer(jwk.qi).toString('hex')}`) - }, 'pem', { label: 'RSA PRIVATE KEY' }) - }, - public (jwk) { - const RSAPublicKey = asn1.get('RSAPublicKey') - - return RSAPublicKey.encode({ - version: 0, - n: BigInt(`0x${base64url.decodeToBuffer(jwk.n).toString('hex')}`), - e: BigInt(`0x${base64url.decodeToBuffer(jwk.e).toString('hex')}`) - }, 'pem', { label: 'RSA PUBLIC KEY' }) - } + 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"] }, - EC: { - private (jwk) { - const ECPrivateKey = asn1.get('ECPrivateKey') - - return ECPrivateKey.encode({ - version: 1, - privateKey: base64url.decodeToBuffer(jwk.d), - parameters: { type: 'namedCurve', value: jwk.crv }, - publicKey: concatEcPublicKey(jwk.x, jwk.y) - }, 'pem', { label: 'EC PRIVATE KEY' }) - }, - public (jwk) { - const PublicKeyInfo = asn1.get('PublicKeyInfo') - - return PublicKeyInfo.encode({ - algorithm: { - algorithm: 'ecPublicKey', - parameters: { type: 'namedCurve', value: jwk.crv } - }, - publicKey: concatEcPublicKey(jwk.x, jwk.y) - }, 'pem', { label: 'PUBLIC KEY' }) - } + codesOfConduct: { + getAllCodesOfConduct: ["GET /codes_of_conduct"], + getConductCode: ["GET /codes_of_conduct/{key}"] }, - OKP: { - private (jwk) { - const OneAsymmetricKey = asn1.get('OneAsymmetricKey') - - const b64 = OneAsymmetricKey.encode({ - version: 0, - privateKey: { privateKey: base64url.decodeToBuffer(jwk.d) }, - algorithm: { algorithm: jwk.crv } - }, 'der') - - // TODO: WHYYY? https://github.com/indutny/asn1.js/issues/110 - b64.write('04', 12, 1, 'hex') - - return formatPem(b64.toString('base64'), 'PRIVATE') - }, - public (jwk) { - const PublicKeyInfo = asn1.get('PublicKeyInfo') - - return PublicKeyInfo.encode({ - algorithm: { algorithm: jwk.crv }, - publicKey: { - unused: 0, - data: base64url.decodeToBuffer(jwk.x) - } - }, 'pem', { label: 'PUBLIC KEY' }) - } - } -} - -module.exports.jwkToPem = (jwk, { calculateMissingRSAPrimes = false } = {}) => { - switch (jwk.kty) { - case 'EC': - if (!EC_CURVES.has(jwk.crv)) { - throw new errors.JOSENotSupported(`unsupported EC key curve: ${jwk.crv}`) - } - break - case 'OKP': - if (!OKP_CURVES.has(jwk.crv)) { - throw new errors.JOSENotSupported(`unsupported OKP key curve: ${jwk.crv}`) - } - break - case 'RSA': - break - default: - throw new errors.JOSENotSupported(`unsupported key type: ${jwk.kty}`) - } - - if (jwk.d) { - return jwkToPem[jwk.kty].private(jwk, { calculateMissingRSAPrimes }) - } - - return jwkToPem[jwk.kty].public(jwk) -} - - -/***/ }), - -/***/ 41518: -/***/ ((module) => { - -module.exports = alg => `sha${alg.substr(2, 3)}` - - -/***/ }), - -/***/ 4438: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { randomBytes } = __nccwpck_require__(6113) - -const base64url = __nccwpck_require__(93312) -const errors = __nccwpck_require__(35132) - -const ZERO = BigInt(0) -const ONE = BigInt(1) -const TWO = BigInt(2) - -const toJWKParameter = (n) => { - const hex = n.toString(16) - return base64url.encodeBuffer(Buffer.from(hex.length % 2 ? `0${hex}` : hex, 'hex')) -} -const fromBuffer = buf => BigInt(`0x${buf.toString('hex')}`) -const bitLength = n => n.toString(2).length - -const eGcdX = (a, b) => { - let x = ZERO - let y = ONE - let u = ONE - let v = ZERO - - while (a !== ZERO) { - const q = b / a - const r = b % a - const m = x - (u * q) - const n = y - (v * q) - b = a - a = r - x = u - y = v - u = m - v = n - } - return x -} - -const gcd = (a, b) => { - let shift = ZERO - while (!((a | b) & ONE)) { - a >>= ONE - b >>= ONE - shift++ - } - while (!(a & ONE)) { - a >>= ONE - } - do { - while (!(b & ONE)) { - b >>= ONE - } - if (a > b) { - const x = a - a = b - b = x - } - b -= a - } while (b) - - return a << shift -} - -const modPow = (a, b, n) => { - a = toZn(a, n) - let result = ONE - let x = a - while (b > 0) { - const leastSignificantBit = b % TWO - b = b / TWO - if (leastSignificantBit === ONE) { - result = result * x - result = result % n - } - x = x * x - x = x % n - } - return result -} - -const randBetween = (min, max) => { - const interval = max - min - const bitLen = bitLength(interval) - let rnd - do { - rnd = fromBuffer(randBits(bitLen)) - } while (rnd > interval) - return rnd + min -} - -const randBits = (bitLength) => { - const byteLength = Math.ceil(bitLength / 8) - const rndBytes = randomBytes(byteLength) - // Fill with 0's the extra bits - rndBytes[0] = rndBytes[0] & (2 ** (bitLength % 8) - 1) - return rndBytes -} - -const toZn = (a, n) => { - a = a % n - return (a < 0) ? a + n : a -} - -const odd = (n) => { - let r = n - while (r % TWO === ZERO) { - r = r / TWO - } - return r -} - -// not sold on these values -const maxCountWhileNoY = 30 -const maxCountWhileInot0 = 22 - -const getPrimeFactors = (e, d, n) => { - const r = odd(e * d - ONE) - - let countWhileNoY = 0 - let y - do { - countWhileNoY++ - if (countWhileNoY === maxCountWhileNoY) { - throw new errors.JWKImportFailed('failed to calculate missing primes') - } - - let countWhileInot0 = 0 - let i = modPow(randBetween(TWO, n), r, n) - let o = ZERO - while (i !== ONE) { - countWhileInot0++ - if (countWhileInot0 === maxCountWhileInot0) { - throw new errors.JWKImportFailed('failed to calculate missing primes') + 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" } - o = i - i = (i * i) % n - } - if (o !== (n - ONE)) { - y = o - } - } while (!y) - - const p = gcd(y - ONE, n) - const q = n / p - - return p > q ? { p, q } : { p: q, q: p } -} - -module.exports = (jwk) => { - const e = fromBuffer(base64url.decodeToBuffer(jwk.e)) - const d = fromBuffer(base64url.decodeToBuffer(jwk.d)) - const n = fromBuffer(base64url.decodeToBuffer(jwk.n)) - - if (d >= n) { - throw new errors.JWKInvalid('invalid RSA private exponent') - } - - const { p, q } = getPrimeFactors(e, d, n) - const dp = d % (p - ONE) - const dq = d % (q - ONE) - const qi = toZn(eGcdX(toZn(q, p), p), p) - - return { - ...jwk, - p: toJWKParameter(p), - q: toJWKParameter(q), - dp: toJWKParameter(dp), - dq: toJWKParameter(dq), - qi: toJWKParameter(qi) - } -} - - -/***/ }), - -/***/ 57494: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { diffieHellman, KeyObject, sign, verify } = __nccwpck_require__(6113) - -const [major, minor] = process.version.substr(1).split('.').map(x => parseInt(x, 10)) - -module.exports = { - oaepHashSupported: major > 12 || (major === 12 && minor >= 9), - keyObjectSupported: !!KeyObject && major >= 12, - edDSASupported: !!sign && !!verify, - dsaEncodingSupported: major > 13 || (major === 13 && minor >= 2) || (major === 12 && minor >= 16), - improvedDH: !!diffieHellman -} - - -/***/ }), - -/***/ 84096: -/***/ ((module) => { - -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)$/i - -module.exports = (str) => { - const matched = REGEX.exec(str) - - if (!matched) { - throw new TypeError(`invalid time period format ("${str}")`) - } - - const value = parseFloat(matched[1]) - const unit = matched[2].toLowerCase() - - switch (unit) { - case 'sec': - case 'secs': - case 'second': - case 'seconds': - case 's': - return Math.round(value) - case 'minute': - case 'minutes': - case 'min': - case 'mins': - case 'm': - return Math.round(value * minute) - case 'hour': - case 'hours': - case 'hr': - case 'hrs': - case 'h': - return Math.round(value * hour) - case 'day': - case 'days': - case 'd': - return Math.round(value * day) - case 'week': - case 'weeks': - case 'w': - return Math.round(value * week) - case 'year': - case 'years': - case 'yr': - case 'yrs': - case 'y': - return Math.round(value * year) - } -} - - -/***/ }), - -/***/ 15300: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { timingSafeEqual: TSE } = __nccwpck_require__(6113) - -const paddedBuffer = (input, length) => { - if (input.length === length) { - return input - } - - const buffer = Buffer.alloc(length) - input.copy(buffer) - return buffer -} - -const timingSafeEqual = (a, b) => { - const length = Math.max(a.length, b.length) - return TSE(paddedBuffer(a, length), paddedBuffer(b, length)) -} - -module.exports = timingSafeEqual - - -/***/ }), - -/***/ 82267: -/***/ ((module) => { - -const MAX_INT32 = Math.pow(2, 32) - -module.exports = (value, buf = Buffer.allocUnsafe(8)) => { - const high = Math.floor(value / MAX_INT32) - const low = value % MAX_INT32 - - buf.writeUInt32BE(high, 0) - buf.writeUInt32BE(low, 4) - return buf -} - - -/***/ }), - -/***/ 85822: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { JOSECritNotUnderstood, JWSInvalid } = __nccwpck_require__(35132) - -const DEFINED = new Set([ - 'alg', 'jku', 'jwk', 'kid', 'x5u', 'x5c', 'x5t', 'x5t#S256', 'typ', 'cty', - 'crit', 'enc', 'zip', 'epk', 'apu', 'apv', 'iv', 'tag', 'p2s', 'p2c' -]) - -module.exports = function validateCrit (Err, protectedHeader, unprotectedHeader, understood) { - if (protectedHeader && 'crit' in protectedHeader) { - if ( - !Array.isArray(protectedHeader.crit) || - protectedHeader.crit.length === 0 || - protectedHeader.crit.some(s => typeof s !== 'string' || !s) - ) { - throw new Err('"crit" Header Parameter MUST be an array of non-empty strings when present') - } - const whitelisted = new Set(understood) - const combined = { ...protectedHeader, ...unprotectedHeader } - protectedHeader.crit.forEach((parameter) => { - if (DEFINED.has(parameter)) { - throw new Err(`The critical list contains a non-extension Header Parameter ${parameter}`) + ], + 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" } - if (!whitelisted.has(parameter)) { - throw new JOSECritNotUnderstood(`critical "${parameter}" is not understood`) + ], + 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" } - if (parameter === 'b64') { - if (!('b64' in protectedHeader)) { - throw new JWSInvalid('"b64" critical parameter must be integrity protected') - } - if (typeof protectedHeader.b64 !== 'boolean') { - throw new JWSInvalid('"b64" critical parameter must be a boolean') - } - } else if (!(parameter in combined)) { - throw new Err(`critical parameter "${parameter}" is missing`) + ], + 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" } - }) - } - if (unprotectedHeader && 'crit' in unprotectedHeader) { - throw new Err('"crit" Header Parameter MUST be integrity protected when present') - } -} - - -/***/ }), - -/***/ 87115: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = { - JWE: __nccwpck_require__(22307), - JWK: __nccwpck_require__(2297), - JWKS: __nccwpck_require__(27397), - JWS: __nccwpck_require__(49830), - JWT: __nccwpck_require__(40449), - errors: __nccwpck_require__(35132) -} - - -/***/ }), - -/***/ 26468: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { createCipheriv, createDecipheriv, getCiphers } = __nccwpck_require__(6113) - -const uint64be = __nccwpck_require__(82267) -const timingSafeEqual = __nccwpck_require__(15300) -const { KEYOBJECT } = __nccwpck_require__(62928) -const { JWEInvalid, JWEDecryptionFailed } = __nccwpck_require__(35132) - -const checkInput = function (size, iv, tag) { - if (iv.length !== 16) { - throw new JWEInvalid('invalid iv') - } - if (arguments.length === 3) { - if (tag.length !== size / 8) { - throw new JWEInvalid('invalid tag') - } - } -} - -const encrypt = (size, sign, { [KEYOBJECT]: keyObject }, cleartext, { iv, aad = Buffer.alloc(0) }) => { - const key = keyObject.export() - checkInput(size, iv) - - const keySize = size / 8 - const encKey = key.slice(keySize) - const cipher = createCipheriv(`aes-${size}-cbc`, encKey, iv) - const ciphertext = Buffer.concat([cipher.update(cleartext), cipher.final()]) - const macData = Buffer.concat([aad, iv, ciphertext, uint64be(aad.length * 8)]) - - const macKey = key.slice(0, keySize) - const tag = sign({ [KEYOBJECT]: macKey }, macData).slice(0, keySize) - - return { ciphertext, tag } -} - -const decrypt = (size, sign, { [KEYOBJECT]: keyObject }, ciphertext, { iv, tag = Buffer.alloc(0), aad = Buffer.alloc(0) }) => { - checkInput(size, iv, tag) - - const keySize = size / 8 - const key = keyObject.export() - const encKey = key.slice(keySize) - const macKey = key.slice(0, keySize) - - const macData = Buffer.concat([aad, iv, ciphertext, uint64be(aad.length * 8)]) - const expectedTag = sign({ [KEYOBJECT]: macKey }, macData, tag).slice(0, keySize) - const macCheckPassed = timingSafeEqual(tag, expectedTag) - - if (!macCheckPassed) { - throw new JWEDecryptionFailed() - } - - let cleartext - try { - const cipher = createDecipheriv(`aes-${size}-cbc`, encKey, iv) - cleartext = Buffer.concat([cipher.update(ciphertext), cipher.final()]) - } catch (err) {} - - if (!cleartext) { - throw new JWEDecryptionFailed() - } - - return cleartext -} - -module.exports = (JWA, JWK) => { - ['A128CBC-HS256', 'A192CBC-HS384', 'A256CBC-HS512'].forEach((jwaAlg) => { - const size = parseInt(jwaAlg.substr(1, 3), 10) - const sign = JWA.sign.get(`HS${size * 2}`) - if (getCiphers().includes(`aes-${size}-cbc`)) { - JWA.encrypt.set(jwaAlg, encrypt.bind(undefined, size, sign)) - JWA.decrypt.set(jwaAlg, decrypt.bind(undefined, size, sign)) - JWK.oct.encrypt[jwaAlg] = JWK.oct.decrypt[jwaAlg] = key => (key.use === 'enc' || key.use === undefined) && key.length / 2 === size - } - }) -} - - -/***/ }), - -/***/ 69480: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { createCipheriv, createDecipheriv, getCiphers } = __nccwpck_require__(6113) - -const { KEYOBJECT } = __nccwpck_require__(62928) -const { JWEInvalid, JWEDecryptionFailed } = __nccwpck_require__(35132) -const { asInput } = __nccwpck_require__(31032) - -const checkInput = function (size, iv, tag) { - if (iv.length !== 12) { - throw new JWEInvalid('invalid iv') - } - if (arguments.length === 3) { - if (tag.length !== 16) { - throw new JWEInvalid('invalid tag') - } - } -} - -const encrypt = (size, { [KEYOBJECT]: keyObject }, cleartext, { iv, aad = Buffer.alloc(0) }) => { - const key = asInput(keyObject, false) - checkInput(size, iv) - - const cipher = createCipheriv(`aes-${size}-gcm`, key, iv, { authTagLength: 16 }) - cipher.setAAD(aad) - - const ciphertext = Buffer.concat([cipher.update(cleartext), cipher.final()]) - const tag = cipher.getAuthTag() - - return { ciphertext, tag } -} - -const decrypt = (size, { [KEYOBJECT]: keyObject }, ciphertext, { iv, tag = Buffer.alloc(0), aad = Buffer.alloc(0) }) => { - const key = asInput(keyObject, false) - checkInput(size, iv, tag) - - try { - const cipher = createDecipheriv(`aes-${size}-gcm`, key, iv, { authTagLength: 16 }) - cipher.setAuthTag(tag) - cipher.setAAD(aad) - - return Buffer.concat([cipher.update(ciphertext), cipher.final()]) - } catch (err) { - throw new JWEDecryptionFailed() - } -} - -module.exports = (JWA, JWK) => { - ['A128GCM', 'A192GCM', 'A256GCM'].forEach((jwaAlg) => { - const size = parseInt(jwaAlg.substr(1, 3), 10) - if (getCiphers().includes(`aes-${size}-gcm`)) { - JWA.encrypt.set(jwaAlg, encrypt.bind(undefined, size)) - JWA.decrypt.set(jwaAlg, decrypt.bind(undefined, size)) - JWK.oct.encrypt[jwaAlg] = JWK.oct.decrypt[jwaAlg] = key => (key.use === 'enc' || key.use === undefined) && key.length === size - } - }) -} - - -/***/ }), - -/***/ 15066: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const generateIV = __nccwpck_require__(3796) -const base64url = __nccwpck_require__(93312) - -module.exports = (JWA, JWK) => { - ['A128GCMKW', 'A192GCMKW', 'A256GCMKW'].forEach((jwaAlg) => { - const encAlg = jwaAlg.substr(0, 7) - const size = parseInt(jwaAlg.substr(1, 3), 10) - const encrypt = JWA.encrypt.get(encAlg) - const decrypt = JWA.decrypt.get(encAlg) - - if (encrypt && decrypt) { - JWA.keyManagementEncrypt.set(jwaAlg, (key, payload) => { - const iv = generateIV(jwaAlg) - const { ciphertext, tag } = encrypt(key, payload, { iv }) - return { - wrapped: ciphertext, - header: { tag: base64url.encodeBuffer(tag), iv: base64url.encodeBuffer(iv) } - } - }) - JWA.keyManagementDecrypt.set(jwaAlg, decrypt) - JWK.oct.wrapKey[jwaAlg] = JWK.oct.unwrapKey[jwaAlg] = key => (key.use === 'enc' || key.use === undefined) && key.length === size - } - }) -} - - -/***/ }), - -/***/ 50253: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { createCipheriv, createDecipheriv, getCiphers } = __nccwpck_require__(6113) - -const { KEYOBJECT } = __nccwpck_require__(62928) -const { asInput } = __nccwpck_require__(31032) - -const checkInput = (data) => { - if (data !== undefined && data.length % 8 !== 0) { - throw new Error('invalid data length') - } -} - -const wrapKey = (alg, { [KEYOBJECT]: keyObject }, payload) => { - const key = asInput(keyObject, false) - const cipher = createCipheriv(alg, key, Buffer.alloc(8, 'a6', 'hex')) - - return { wrapped: Buffer.concat([cipher.update(payload), cipher.final()]) } -} - -const unwrapKey = (alg, { [KEYOBJECT]: keyObject }, payload) => { - const key = asInput(keyObject, false) - checkInput(payload) - const cipher = createDecipheriv(alg, key, Buffer.alloc(8, 'a6', 'hex')) - - return Buffer.concat([cipher.update(payload), cipher.final()]) -} - -module.exports = (JWA, JWK) => { - ['A128KW', 'A192KW', 'A256KW'].forEach((jwaAlg) => { - const size = parseInt(jwaAlg.substr(1, 3), 10) - const alg = `aes${size}-wrap` - if (getCiphers().includes(alg)) { - JWA.keyManagementEncrypt.set(jwaAlg, wrapKey.bind(undefined, alg)) - JWA.keyManagementDecrypt.set(jwaAlg, unwrapKey.bind(undefined, alg)) - JWK.oct.wrapKey[jwaAlg] = JWK.oct.unwrapKey[jwaAlg] = key => (key.use === 'enc' || key.use === undefined) && key.length === size - } - }) -} - - -/***/ }), - -/***/ 53791: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { improvedDH } = __nccwpck_require__(57494) - -if (improvedDH) { - const { diffieHellman } = __nccwpck_require__(6113) - - const { KeyObject } = __nccwpck_require__(31032) - const importKey = __nccwpck_require__(77722) - - module.exports = ({ keyObject: privateKey }, publicKey) => { - if (!(publicKey instanceof KeyObject)) { - ({ keyObject: publicKey } = importKey(publicKey)) - } - - return diffieHellman({ privateKey, publicKey }) - } -} else { - const { createECDH, constants: { POINT_CONVERSION_UNCOMPRESSED } } = __nccwpck_require__(6113) - - const base64url = __nccwpck_require__(93312) - - const crvToCurve = (crv) => { - switch (crv) { - case 'P-256': - return 'prime256v1' - case 'P-384': - return 'secp384r1' - case 'P-521': - return 'secp521r1' - } - } - - const UNCOMPRESSED = Buffer.alloc(1, POINT_CONVERSION_UNCOMPRESSED) - const pubToBuffer = (x, y) => Buffer.concat([UNCOMPRESSED, base64url.decodeToBuffer(x), base64url.decodeToBuffer(y)]) - - module.exports = ({ crv, d }, { x, y }) => { - const curve = crvToCurve(crv) - const exchange = createECDH(curve) - - exchange.setPrivateKey(base64url.decodeToBuffer(d)) - - return exchange.computeSecret(pubToBuffer(x, y)) - } -} - - -/***/ }), - -/***/ 95320: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { createHash } = __nccwpck_require__(6113) -const ecdhComputeSecret = __nccwpck_require__(53791) - -const concat = (key, length, value) => { - const iterations = Math.ceil(length / 32) - let res - - for (let iter = 1; iter <= iterations; iter++) { - const buf = Buffer.allocUnsafe(4 + key.length + value.length) - buf.writeUInt32BE(iter, 0) - key.copy(buf, 4) - value.copy(buf, 4 + key.length) - if (!res) { - res = createHash('sha256').update(buf).digest() - } else { - res = Buffer.concat([res, createHash('sha256').update(buf).digest()]) - } - } - - return res.slice(0, length) -} - -const uint32be = (value, buf = Buffer.allocUnsafe(4)) => { - buf.writeUInt32BE(value) - return buf -} - -const lengthAndInput = input => Buffer.concat([uint32be(input.length), input]) - -module.exports = (alg, keyLen, privKey, pubKey, { apu = Buffer.alloc(0), apv = Buffer.alloc(0) } = {}, computeSecret = ecdhComputeSecret) => { - const value = Buffer.concat([ - lengthAndInput(Buffer.from(alg)), - lengthAndInput(apu), - lengthAndInput(apv), - uint32be(keyLen) - ]) - - const sharedSecret = computeSecret(privKey, pubKey) - return concat(sharedSecret, keyLen / 8, value) -} - - -/***/ }), - -/***/ 99214: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { improvedDH } = __nccwpck_require__(57494) -const { KEYLENGTHS } = __nccwpck_require__(47359) -const { generateSync } = __nccwpck_require__(87042) - -const derive = __nccwpck_require__(95320) - -const wrapKey = (key, payload, { enc }) => { - const epk = generateSync(key.kty, key.crv) - - const derivedKey = derive(enc, KEYLENGTHS.get(enc), epk, key) - - return { - wrapped: derivedKey, - header: { epk: { kty: key.kty, crv: key.crv, x: epk.x, y: epk.y } } - } -} - -const unwrapKey = (key, payload, header) => { - const { enc, epk } = header - return derive(enc, KEYLENGTHS.get(enc), key, epk, header) -} - -module.exports = (JWA, JWK) => { - JWA.keyManagementEncrypt.set('ECDH-ES', wrapKey) - JWA.keyManagementDecrypt.set('ECDH-ES', unwrapKey) - JWK.EC.deriveKey['ECDH-ES'] = key => (key.use === 'enc' || key.use === undefined) && key.crv !== 'secp256k1' - - if (improvedDH) { - JWK.OKP.deriveKey['ECDH-ES'] = key => (key.use === 'enc' || key.use === undefined) && key.keyObject.asymmetricKeyType.startsWith('x') - } -} - - -/***/ }), - -/***/ 4363: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { improvedDH } = __nccwpck_require__(57494) -const { KEYOBJECT } = __nccwpck_require__(62928) -const { generateSync } = __nccwpck_require__(87042) -const { ECDH_DERIVE_LENGTHS } = __nccwpck_require__(47359) - -const derive = __nccwpck_require__(95320) - -const wrapKey = (wrap, derive, key, payload) => { - const epk = generateSync(key.kty, key.crv) - - const derivedKey = derive(epk, key, payload) - - const result = wrap({ [KEYOBJECT]: derivedKey }, payload) - result.header = result.header || {} - Object.assign(result.header, { epk: { kty: key.kty, crv: key.crv, x: epk.x, y: epk.y } }) - - return result -} - -const unwrapKey = (unwrap, derive, key, payload, header) => { - const { epk } = header - const derivedKey = derive(key, epk, header) - - return unwrap({ [KEYOBJECT]: derivedKey }, payload, header) -} - -module.exports = (JWA, JWK) => { - ['ECDH-ES+A128KW', 'ECDH-ES+A192KW', 'ECDH-ES+A256KW'].forEach((jwaAlg) => { - const kw = jwaAlg.substr(-6) - const kwWrap = JWA.keyManagementEncrypt.get(kw) - const kwUnwrap = JWA.keyManagementDecrypt.get(kw) - const keylen = parseInt(jwaAlg.substr(9, 3), 10) - ECDH_DERIVE_LENGTHS.set(jwaAlg, keylen) - - if (kwWrap && kwUnwrap) { - JWA.keyManagementEncrypt.set(jwaAlg, wrapKey.bind(undefined, kwWrap, derive.bind(undefined, jwaAlg, keylen))) - JWA.keyManagementDecrypt.set(jwaAlg, unwrapKey.bind(undefined, kwUnwrap, derive.bind(undefined, jwaAlg, keylen))) - JWK.EC.deriveKey[jwaAlg] = key => (key.use === 'enc' || key.use === undefined) && key.crv !== 'secp256k1' - - if (improvedDH) { - JWK.OKP.deriveKey[jwaAlg] = key => (key.use === 'enc' || key.use === undefined) && key.keyObject.asymmetricKeyType.startsWith('x') + ], + 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" } - } - }) -} -module.exports.wrapKey = wrapKey -module.exports.unwrapKey = unwrapKey - - -/***/ }), - -/***/ 92251: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { sign: signOneShot, verify: verifyOneShot, createSign, createVerify, getCurves } = __nccwpck_require__(6113) - -const { derToJose, joseToDer } = __nccwpck_require__(64575) -const { KEYOBJECT } = __nccwpck_require__(62928) -const resolveNodeAlg = __nccwpck_require__(41518) -const { asInput } = __nccwpck_require__(31032) -const { dsaEncodingSupported } = __nccwpck_require__(57494) - -let sign, verify - -if (dsaEncodingSupported) { - sign = (jwaAlg, nodeAlg, { [KEYOBJECT]: keyObject }, payload) => { - if (typeof payload === 'string') { - payload = Buffer.from(payload) - } - return signOneShot(nodeAlg, payload, { key: asInput(keyObject, false), dsaEncoding: 'ieee-p1363' }) - } - verify = (jwaAlg, nodeAlg, { [KEYOBJECT]: keyObject }, payload, signature) => { - try { - return verifyOneShot(nodeAlg, payload, { key: asInput(keyObject, true), dsaEncoding: 'ieee-p1363' }, signature) - } catch (err) { - return false - } - } -} else { - sign = (jwaAlg, nodeAlg, { [KEYOBJECT]: keyObject }, payload) => { - return derToJose(createSign(nodeAlg).update(payload).sign(asInput(keyObject, false)), jwaAlg) - } - verify = (jwaAlg, nodeAlg, { [KEYOBJECT]: keyObject }, payload, signature) => { - try { - return createVerify(nodeAlg).update(payload).verify(asInput(keyObject, true), joseToDer(signature, jwaAlg)) - } catch (err) { - return false - } - } -} - -const crvToAlg = (crv) => { - switch (crv) { - case 'P-256': - return 'ES256' - case 'secp256k1': - return 'ES256K' - case 'P-384': - return 'ES384' - case 'P-521': - return 'ES512' - } -} - -module.exports = (JWA, JWK) => { - const algs = [] - - if (getCurves().includes('prime256v1')) { - algs.push('ES256') - } - - if (getCurves().includes('secp256k1')) { - algs.push('ES256K') - } - - if (getCurves().includes('secp384r1')) { - algs.push('ES384') - } - - if (getCurves().includes('secp521r1')) { - algs.push('ES512') - } - - algs.forEach((jwaAlg) => { - const nodeAlg = resolveNodeAlg(jwaAlg) - JWA.sign.set(jwaAlg, sign.bind(undefined, jwaAlg, nodeAlg)) - JWA.verify.set(jwaAlg, verify.bind(undefined, jwaAlg, nodeAlg)) - JWK.EC.sign[jwaAlg] = key => key.private && JWK.EC.verify[jwaAlg](key) - JWK.EC.verify[jwaAlg] = key => (key.use === 'sig' || key.use === undefined) && crvToAlg(key.crv) === jwaAlg - }) -} - - -/***/ }), - -/***/ 6307: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { sign: signOneShot, verify: verifyOneShot } = __nccwpck_require__(6113) - -const { KEYOBJECT } = __nccwpck_require__(62928) -const { edDSASupported } = __nccwpck_require__(57494) - -const sign = ({ [KEYOBJECT]: keyObject }, payload) => { - if (typeof payload === 'string') { - payload = Buffer.from(payload) - } - return signOneShot(undefined, payload, keyObject) -} - -const verify = ({ [KEYOBJECT]: keyObject }, payload, signature) => { - return verifyOneShot(undefined, payload, keyObject, signature) -} - -module.exports = (JWA, JWK) => { - if (edDSASupported) { - JWA.sign.set('EdDSA', sign) - JWA.verify.set('EdDSA', verify) - JWK.OKP.sign.EdDSA = key => key.private && JWK.OKP.verify.EdDSA(key) - JWK.OKP.verify.EdDSA = key => (key.use === 'sig' || key.use === undefined) && key.keyObject.asymmetricKeyType.startsWith('ed') - } -} - - -/***/ }), - -/***/ 71367: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { createHmac } = __nccwpck_require__(6113) - -const { KEYOBJECT } = __nccwpck_require__(62928) -const timingSafeEqual = __nccwpck_require__(15300) -const resolveNodeAlg = __nccwpck_require__(41518) -const { asInput } = __nccwpck_require__(31032) - -const sign = (jwaAlg, hmacAlg, { [KEYOBJECT]: keyObject }, payload) => { - const hmac = createHmac(hmacAlg, asInput(keyObject, false)) - hmac.update(payload) - return hmac.digest() -} - -const verify = (jwaAlg, hmacAlg, key, payload, signature) => { - const expected = sign(jwaAlg, hmacAlg, key, payload) - const actual = signature - - return timingSafeEqual(actual, expected) -} - -module.exports = (JWA, JWK) => { - ['HS256', 'HS384', 'HS512'].forEach((jwaAlg) => { - const hmacAlg = resolveNodeAlg(jwaAlg) - JWA.sign.set(jwaAlg, sign.bind(undefined, jwaAlg, hmacAlg)) - JWA.verify.set(jwaAlg, verify.bind(undefined, jwaAlg, hmacAlg)) - JWK.oct.sign[jwaAlg] = JWK.oct.verify[jwaAlg] = key => key.use === 'sig' || key.use === undefined - }) -} - - -/***/ }), - -/***/ 40423: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { JWKKeySupport, JOSENotSupported } = __nccwpck_require__(35132) -const { KEY_MANAGEMENT_ENCRYPT, KEY_MANAGEMENT_DECRYPT } = __nccwpck_require__(62928) - -const { JWA, JWK } = __nccwpck_require__(47359) - -// sign, verify -__nccwpck_require__(71367)(JWA, JWK) -__nccwpck_require__(92251)(JWA, JWK) -__nccwpck_require__(6307)(JWA, JWK) -__nccwpck_require__(90112)(JWA, JWK) -__nccwpck_require__(75778)(JWA, JWK) -__nccwpck_require__(62875)(JWA) - -// encrypt, decrypt -__nccwpck_require__(26468)(JWA, JWK) -__nccwpck_require__(69480)(JWA, JWK) - -// wrapKey, unwrapKey -__nccwpck_require__(4061)(JWA, JWK) -__nccwpck_require__(50253)(JWA, JWK) -__nccwpck_require__(15066)(JWA, JWK) - -// deriveKey -__nccwpck_require__(41613)(JWA, JWK) -__nccwpck_require__(99214)(JWA, JWK) -__nccwpck_require__(4363)(JWA, JWK) - -const check = (key, op, alg) => { - const cache = `_${op}_${alg}` - - let label - let keyOp - if (op === 'keyManagementEncrypt') { - label = 'key management (encryption)' - keyOp = KEY_MANAGEMENT_ENCRYPT - } else if (op === 'keyManagementDecrypt') { - label = 'key management (decryption)' - keyOp = KEY_MANAGEMENT_DECRYPT - } - - if (cache in key) { - if (key[cache]) { - return - } - throw new JWKKeySupport(`the key does not support ${alg} ${label || op} algorithm`) - } - - let value = true - if (!JWA[op].has(alg)) { - throw new JOSENotSupported(`unsupported ${label || op} alg: ${alg}`) - } else if (!key.algorithms(keyOp).has(alg)) { - value = false - } - - Object.defineProperty(key, cache, { value, enumerable: false }) - - if (!value) { - return check(key, op, alg) - } -} - -module.exports = { - check, - sign: (alg, key, payload) => { - check(key, 'sign', alg) - return JWA.sign.get(alg)(key, payload) + ], + 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" + } + ] }, - verify: (alg, key, payload, signature) => { - check(key, 'verify', alg) - return JWA.verify.get(alg)(key, payload, signature) + oidc: { + getOidcCustomSubTemplateForOrg: [ + "GET /orgs/{org}/actions/oidc/customization/sub" + ], + updateOidcCustomSubTemplateForOrg: [ + "PUT /orgs/{org}/actions/oidc/customization/sub" + ] }, - keyManagementEncrypt: (alg, key, payload, opts) => { - check(key, 'keyManagementEncrypt', alg) - return JWA.keyManagementEncrypt.get(alg)(key, payload, opts) + 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"] }, - keyManagementDecrypt: (alg, key, payload, opts) => { - check(key, 'keyManagementDecrypt', alg) - return JWA.keyManagementDecrypt.get(alg)(key, payload, opts) + 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" + ] }, - encrypt: (alg, key, cleartext, opts) => { - check(key, 'encrypt', alg) - return JWA.encrypt.get(alg)(key, cleartext, opts) + 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}"] }, - decrypt: (alg, key, ciphertext, opts) => { - check(key, 'decrypt', alg) - return JWA.decrypt.get(alg)(key, ciphertext, opts) - } -} - - -/***/ }), - -/***/ 62875: -/***/ ((module) => { - -const sign = () => Buffer.from('') -const verify = (key, payload, signature) => !signature.length - -module.exports = (JWA, JWK) => { - JWA.sign.set('none', sign) - JWA.verify.set('none', verify) -} - - -/***/ }), - -/***/ 41613: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { pbkdf2Sync: pbkdf2, randomBytes } = __nccwpck_require__(6113) - -const { KEYOBJECT } = __nccwpck_require__(62928) -const base64url = __nccwpck_require__(93312) - -const SALT_LENGTH = 16 -const NULL_BUFFER = Buffer.alloc(1, 0) - -const concatSalt = (alg, p2s) => { - return Buffer.concat([ - Buffer.from(alg, 'utf8'), - NULL_BUFFER, - p2s - ]) -} - -const wrapKey = (keylen, sha, concat, wrap, { [KEYOBJECT]: keyObject }, payload) => { - // Note that if password-based encryption is used for multiple - // recipients, it is expected that each recipient use different values - // for the PBES2 parameters "p2s" and "p2c". - // here we generate p2c between 2048 and 4096 and random p2s - const p2c = Math.floor((Math.random() * 2049) + 2048) - const p2s = randomBytes(SALT_LENGTH) - const salt = concat(p2s) - - const derivedKey = pbkdf2(keyObject.export(), salt, p2c, keylen, sha) - - const result = wrap({ [KEYOBJECT]: derivedKey }, payload) - result.header = result.header || {} - Object.assign(result.header, { p2c, p2s: base64url.encodeBuffer(p2s) }) - - return result -} - -const unwrapKey = (keylen, sha, concat, unwrap, { [KEYOBJECT]: keyObject }, payload, header) => { - const { p2s, p2c } = header - const salt = concat(p2s) - const derivedKey = pbkdf2(keyObject.export(), salt, p2c, keylen, sha) - return unwrap({ [KEYOBJECT]: derivedKey }, payload, header) -} - -module.exports = (JWA, JWK) => { - ['PBES2-HS256+A128KW', 'PBES2-HS384+A192KW', 'PBES2-HS512+A256KW'].forEach((jwaAlg) => { - const kw = jwaAlg.substr(-6) - const kwWrap = JWA.keyManagementEncrypt.get(kw) - const kwUnwrap = JWA.keyManagementDecrypt.get(kw) - const keylen = parseInt(jwaAlg.substr(13, 3), 10) / 8 - const sha = `sha${jwaAlg.substr(8, 3)}` - - if (kwWrap && kwUnwrap) { - JWA.keyManagementEncrypt.set(jwaAlg, wrapKey.bind(undefined, keylen, sha, concatSalt.bind(undefined, jwaAlg), kwWrap)) - JWA.keyManagementDecrypt.set(jwaAlg, unwrapKey.bind(undefined, keylen, sha, concatSalt.bind(undefined, jwaAlg), kwUnwrap)) - JWK.oct.deriveKey[jwaAlg] = key => key.use === 'enc' || key.use === undefined - } - }) -} - - -/***/ }), - -/***/ 4061: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { publicEncrypt, privateDecrypt, constants } = __nccwpck_require__(6113) - -const { oaepHashSupported } = __nccwpck_require__(57494) -const { KEYOBJECT } = __nccwpck_require__(62928) -const { asInput } = __nccwpck_require__(31032) - -const resolvePadding = (alg) => { - switch (alg) { - case 'RSA-OAEP': - case 'RSA-OAEP-256': - case 'RSA-OAEP-384': - case 'RSA-OAEP-512': - return constants.RSA_PKCS1_OAEP_PADDING - case 'RSA1_5': - return constants.RSA_PKCS1_PADDING - } -} - -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 - } -} - -const wrapKey = (padding, oaepHash, { [KEYOBJECT]: keyObject }, payload) => { - const key = asInput(keyObject, true) - return { wrapped: publicEncrypt({ key, oaepHash, padding }, payload) } -} - -const unwrapKey = (padding, oaepHash, { [KEYOBJECT]: keyObject }, payload) => { - const key = asInput(keyObject, false) - return privateDecrypt({ key, oaepHash, padding }, payload) -} - -const LENGTHS = { - RSA1_5: 0, - 'RSA-OAEP': 592, - 'RSA-OAEP-256': 784, - 'RSA-OAEP-384': 1040, - 'RSA-OAEP-512': 1296 -} - -module.exports = (JWA, JWK) => { - const algs = ['RSA-OAEP', 'RSA1_5'] - - if (oaepHashSupported) { - algs.splice(1, 0, 'RSA-OAEP-256', 'RSA-OAEP-384', 'RSA-OAEP-512') - } - - algs.forEach((jwaAlg) => { - const padding = resolvePadding(jwaAlg) - const oaepHash = resolveOaepHash(jwaAlg) - JWA.keyManagementEncrypt.set(jwaAlg, wrapKey.bind(undefined, padding, oaepHash)) - JWA.keyManagementDecrypt.set(jwaAlg, unwrapKey.bind(undefined, padding, oaepHash)) - JWK.RSA.wrapKey[jwaAlg] = key => (key.use === 'enc' || key.use === undefined) && key.length >= LENGTHS[jwaAlg] - JWK.RSA.unwrapKey[jwaAlg] = key => key.private && (key.use === 'enc' || key.use === undefined) && key.length >= LENGTHS[jwaAlg] - }) -} - - -/***/ }), - -/***/ 75778: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { createSign, createVerify } = __nccwpck_require__(6113) - -const { KEYOBJECT } = __nccwpck_require__(62928) -const resolveNodeAlg = __nccwpck_require__(41518) -const { asInput } = __nccwpck_require__(31032) - -const sign = (nodeAlg, { [KEYOBJECT]: keyObject }, payload) => { - return createSign(nodeAlg).update(payload).sign(asInput(keyObject, false)) -} - -const verify = (nodeAlg, { [KEYOBJECT]: keyObject }, payload, signature) => { - return createVerify(nodeAlg).update(payload).verify(asInput(keyObject, true), signature) -} - -const LENGTHS = { - RS256: 0, - RS384: 624, - RS512: 752 -} - -module.exports = (JWA, JWK) => { - ['RS256', 'RS384', 'RS512'].forEach((jwaAlg) => { - const nodeAlg = resolveNodeAlg(jwaAlg) - JWA.sign.set(jwaAlg, sign.bind(undefined, nodeAlg)) - JWA.verify.set(jwaAlg, verify.bind(undefined, nodeAlg)) - JWK.RSA.sign[jwaAlg] = key => key.private && JWK.RSA.verify[jwaAlg](key) - JWK.RSA.verify[jwaAlg] = key => (key.use === 'sig' || key.use === undefined) && key.length >= LENGTHS[jwaAlg] - }) -} - - -/***/ }), - -/***/ 90112: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { - createSign, - createVerify, - constants -} = __nccwpck_require__(6113) - -const { KEYOBJECT } = __nccwpck_require__(62928) -const resolveNodeAlg = __nccwpck_require__(41518) -const { asInput } = __nccwpck_require__(31032) - -const sign = (nodeAlg, { [KEYOBJECT]: keyObject }, payload) => { - const key = asInput(keyObject, false) - return createSign(nodeAlg).update(payload).sign({ - key, - padding: constants.RSA_PKCS1_PSS_PADDING, - saltLength: constants.RSA_PSS_SALTLEN_DIGEST - }) -} - -const verify = (nodeAlg, { [KEYOBJECT]: keyObject }, payload, signature) => { - const key = asInput(keyObject, true) - return createVerify(nodeAlg).update(payload).verify({ - key, - padding: constants.RSA_PKCS1_PSS_PADDING, - saltLength: constants.RSA_PSS_SALTLEN_DIGEST - }, signature) -} - -const LENGTHS = { - PS256: 528, - PS384: 784, - PS512: 1040 -} - -module.exports = (JWA, JWK) => { - ['PS256', 'PS384', 'PS512'].forEach((jwaAlg) => { - const nodeAlg = resolveNodeAlg(jwaAlg) - JWA.sign.set(jwaAlg, sign.bind(undefined, nodeAlg)) - JWA.verify.set(jwaAlg, verify.bind(undefined, nodeAlg)) - JWK.RSA.sign[jwaAlg] = key => key.private && JWK.RSA.verify[jwaAlg](key) - JWK.RSA.verify[jwaAlg] = key => (key.use === 'sig' || key.use === undefined) && key.length >= LENGTHS[jwaAlg] - }) -} - - -/***/ }), - -/***/ 20087: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { inflateRawSync } = __nccwpck_require__(59796) - -const base64url = __nccwpck_require__(93312) -const getKey = __nccwpck_require__(7090) -const { KeyStore } = __nccwpck_require__(27397) -const errors = __nccwpck_require__(35132) -const { check, decrypt, keyManagementDecrypt } = __nccwpck_require__(40423) -const JWK = __nccwpck_require__(2297) - -const { createSecretKey } = __nccwpck_require__(31032) -const generateCEK = __nccwpck_require__(22329) -const validateHeaders = __nccwpck_require__(77997) -const { detect: resolveSerialization } = __nccwpck_require__(14609) - -const SINGLE_RECIPIENT = new Set(['compact', 'flattened']) - -const combineHeader = (prot = {}, unprotected = {}, header = {}) => { - if (typeof prot === 'string') { - prot = base64url.JSON.decode(prot) - } - - const p2s = prot.p2s || unprotected.p2s || header.p2s - const apu = prot.apu || unprotected.apu || header.apu - const apv = prot.apv || unprotected.apv || header.apv - const iv = prot.iv || unprotected.iv || header.iv - const tag = prot.tag || unprotected.tag || header.tag - - return { - ...prot, - ...unprotected, - ...header, - ...(typeof p2s === 'string' ? { p2s: base64url.decodeToBuffer(p2s) } : undefined), - ...(typeof apu === 'string' ? { apu: base64url.decodeToBuffer(apu) } : undefined), - ...(typeof apv === 'string' ? { apv: base64url.decodeToBuffer(apv) } : undefined), - ...(typeof iv === 'string' ? { iv: base64url.decodeToBuffer(iv) } : undefined), - ...(typeof tag === 'string' ? { tag: base64url.decodeToBuffer(tag) } : undefined) - } -} - -const validateAlgorithms = (algorithms, option) => { - if (algorithms !== undefined && (!Array.isArray(algorithms) || algorithms.some(s => typeof s !== 'string' || !s))) { - throw new TypeError(`"${option}" option must be an array of non-empty strings`) - } - - if (!algorithms) { - return undefined - } - - return new Set(algorithms) -} - -/* - * @public - */ -const jweDecrypt = (skipValidateHeaders, serialization, jwe, key, { crit = [], complete = false, keyManagementAlgorithms, contentEncryptionAlgorithms, maxPBES2Count = 10000 } = {}) => { - key = getKey(key, true) - - keyManagementAlgorithms = validateAlgorithms(keyManagementAlgorithms, 'keyManagementAlgorithms') - contentEncryptionAlgorithms = validateAlgorithms(contentEncryptionAlgorithms, 'contentEncryptionAlgorithms') - - if (!Array.isArray(crit) || crit.some(s => typeof s !== 'string' || !s)) { - throw new TypeError('"crit" option must be an array of non-empty strings') - } - - if (!serialization) { - serialization = resolveSerialization(jwe) - } - - let alg, ciphertext, enc, encryptedKey, iv, opts, prot, tag, unprotected, cek, aad, header - - // treat general format with one recipient as flattened - // skips iteration and avoids multi errors in this case - if (serialization === 'general' && jwe.recipients.length === 1) { - serialization = 'flattened' - const { recipients, ...root } = jwe - jwe = { ...root, ...recipients[0] } - } - - if (SINGLE_RECIPIENT.has(serialization)) { - if (serialization === 'compact') { // compact serialization format - ([prot, encryptedKey, iv, ciphertext, tag] = jwe.split('.')) - } else { // flattened serialization format - ({ protected: prot, encrypted_key: encryptedKey, iv, ciphertext, tag, unprotected, aad, header } = jwe) - } - - if (!skipValidateHeaders) { - validateHeaders(prot, unprotected, [{ header }], true, crit) - } - - opts = combineHeader(prot, unprotected, header) - - ;({ alg, enc } = opts) - - if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) { - throw new errors.JOSEAlgNotWhitelisted('key management algorithm not whitelisted') - } - - if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) { - throw new errors.JOSEAlgNotWhitelisted('content encryption algorithm not whitelisted') - } - - if (key instanceof KeyStore) { - const keystore = key - let keys - if (opts.alg === 'dir') { - keys = keystore.all({ kid: opts.kid, alg: opts.enc, key_ops: ['decrypt'] }) - } else { - keys = keystore.all({ kid: opts.kid, alg: opts.alg, key_ops: ['unwrapKey'] }) - } - switch (keys.length) { - case 0: - throw new errors.JWKSNoMatchingKey() - case 1: - // treat the call as if a Key instance was passed in - // skips iteration and avoids multi errors in this case - key = keys[0] - break - default: { - const errs = [] - for (const key of keys) { - try { - return jweDecrypt(true, serialization, jwe, key, { - crit, - complete, - contentEncryptionAlgorithms: contentEncryptionAlgorithms ? [...contentEncryptionAlgorithms] : undefined, - keyManagementAlgorithms: keyManagementAlgorithms ? [...keyManagementAlgorithms] : undefined - }) - } catch (err) { - errs.push(err) - continue - } - } - - const multi = new errors.JOSEMultiError(errs) - if ([...multi].some(e => e instanceof errors.JWEDecryptionFailed)) { - throw new errors.JWEDecryptionFailed() - } - throw multi - } - } - } - - check(key, ...(alg === 'dir' ? ['decrypt', enc] : ['keyManagementDecrypt', alg])) - - if (alg.startsWith('PBES2')) { - if (opts && opts.p2c > maxPBES2Count) { - throw new errors.JWEInvalid('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds') - } - } - - try { - if (alg === 'dir') { - cek = JWK.asKey(key, { alg: enc, use: 'enc' }) - } else if (alg === 'ECDH-ES') { - const unwrapped = keyManagementDecrypt(alg, key, undefined, opts) - cek = JWK.asKey(createSecretKey(unwrapped), { alg: enc, use: 'enc' }) - } else { - const unwrapped = keyManagementDecrypt(alg, key, base64url.decodeToBuffer(encryptedKey), opts) - cek = JWK.asKey(createSecretKey(unwrapped), { alg: enc, use: 'enc' }) - } - } catch (err) { - // To mitigate the attacks described in RFC 3218, the - // recipient MUST NOT distinguish between format, padding, and length - // errors of encrypted keys. It is strongly recommended, in the event - // of receiving an improperly formatted key, that the recipient - // substitute a randomly generated CEK and proceed to the next step, to - // mitigate timing attacks. - cek = generateCEK(enc) - } - - let adata - if (aad) { - adata = Buffer.concat([ - Buffer.from(prot || ''), - Buffer.from('.'), - Buffer.from(aad) - ]) - } else { - adata = Buffer.from(prot || '') - } - - try { - iv = base64url.decodeToBuffer(iv) - } catch (err) {} - try { - tag = base64url.decodeToBuffer(tag) - } catch (err) {} - - let cleartext = decrypt(enc, cek, base64url.decodeToBuffer(ciphertext), { iv, tag, aad: adata }) - - if (opts.zip) { - cleartext = inflateRawSync(cleartext) - } - - if (complete) { - const result = { cleartext, key, cek } - if (aad) result.aad = aad - if (header) result.header = header - if (unprotected) result.unprotected = unprotected - if (prot) result.protected = base64url.JSON.decode(prot) - return result - } - - return cleartext - } - - validateHeaders(jwe.protected, jwe.unprotected, jwe.recipients.map(({ header }) => ({ header })), true, crit) - - // general serialization format - const { recipients, ...root } = jwe - const errs = [] - for (const recipient of recipients) { - try { - return jweDecrypt(true, 'flattened', { ...root, ...recipient }, key, { - crit, - complete, - contentEncryptionAlgorithms: contentEncryptionAlgorithms ? [...contentEncryptionAlgorithms] : undefined, - keyManagementAlgorithms: keyManagementAlgorithms ? [...keyManagementAlgorithms] : undefined - }) - } catch (err) { - errs.push(err) - continue - } - } - - const multi = new errors.JOSEMultiError(errs) - if ([...multi].some(e => e instanceof errors.JWEDecryptionFailed)) { - throw new errors.JWEDecryptionFailed() - } else if ([...multi].every(e => e instanceof errors.JWKSNoMatchingKey)) { - throw new errors.JWKSNoMatchingKey() - } - throw multi -} - -module.exports = jweDecrypt.bind(undefined, false, undefined) - - -/***/ }), - -/***/ 47154: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { deflateRawSync } = __nccwpck_require__(59796) - -const { KEYOBJECT } = __nccwpck_require__(62928) -const generateIV = __nccwpck_require__(3796) -const base64url = __nccwpck_require__(93312) -const getKey = __nccwpck_require__(7090) -const isObject = __nccwpck_require__(50243) -const { createSecretKey } = __nccwpck_require__(31032) -const deepClone = __nccwpck_require__(52083) -const importKey = __nccwpck_require__(77722) -const { JWEInvalid } = __nccwpck_require__(35132) -const { check, keyManagementEncrypt, encrypt } = __nccwpck_require__(40423) - -const serializers = __nccwpck_require__(14609) -const generateCEK = __nccwpck_require__(22329) -const validateHeaders = __nccwpck_require__(77997) - -const PROCESS_RECIPIENT = Symbol('PROCESS_RECIPIENT') - -class Encrypt { - constructor (cleartext, protectedHeader, aad, unprotectedHeader) { - if (!Buffer.isBuffer(cleartext) && typeof cleartext !== 'string') { - throw new TypeError('cleartext argument must be a Buffer or a string') - } - cleartext = Buffer.from(cleartext) - - if (aad !== undefined && !Buffer.isBuffer(aad) && typeof aad !== 'string') { - throw new TypeError('aad argument must be a Buffer or a string when provided') - } - aad = aad ? Buffer.from(aad) : undefined - - if (protectedHeader !== undefined && !isObject(protectedHeader)) { - throw new TypeError('protectedHeader argument must be a plain object when provided') - } - - if (unprotectedHeader !== undefined && !isObject(unprotectedHeader)) { - throw new TypeError('unprotectedHeader argument must be a plain object when provided') - } - - this._recipients = [] - this._cleartext = cleartext - this._aad = aad - this._unprotected = unprotectedHeader ? deepClone(unprotectedHeader) : undefined - this._protected = protectedHeader ? deepClone(protectedHeader) : undefined - } - - /* - * @public - */ - recipient (key, header) { - key = getKey(key) - - if (header !== undefined && !isObject(header)) { - throw new TypeError('header argument must be a plain object when provided') - } - - this._recipients.push({ - key, - header: header ? deepClone(header) : undefined - }) - - return this + 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; - /* - * @private - */ - [PROCESS_RECIPIENT] (recipient) { - const unprotectedHeader = this._unprotected - const protectedHeader = this._protected - const { length: recipientCount } = this._recipients - - const jweHeader = { - ...protectedHeader, - ...unprotectedHeader, - ...recipient.header - } - const { key } = recipient - - const enc = jweHeader.enc - let alg = jweHeader.alg - - if (key.use === 'sig') { - throw new TypeError('a key with "use":"sig" is not usable for encryption') +// 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()); } - - if (alg === 'dir') { - check(key, 'encrypt', enc) - } else if (alg) { - check(key, 'keyManagementEncrypt', alg) - } else { - alg = key.alg || [...key.algorithms('wrapKey')][0] || [...key.algorithms('deriveKey')][0] - - if (alg === 'ECDH-ES' && recipientCount !== 1) { - alg = [...key.algorithms('deriveKey')][1] - } - - if (!alg) { - throw new JWEInvalid('could not resolve a usable "alg" for a recipient') - } - - if (recipientCount === 1) { - if (protectedHeader) { - protectedHeader.alg = alg - } else { - this._protected = { alg } - } - } else { - if (recipient.header) { - recipient.header.alg = alg - } else { - recipient.header = { alg } - } - } + 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]; } - - let wrapped - let generatedHeader - - if (key.kty === 'oct' && alg === 'dir') { - this._cek = importKey(key[KEYOBJECT], { use: 'enc', alg: enc }) - } else { - check(this._cek, 'encrypt', enc) - ;({ wrapped, header: generatedHeader } = keyManagementEncrypt(alg, key, this._cek[KEYOBJECT].export(), { enc, alg })) - if (alg === 'ECDH-ES') { - this._cek = importKey(createSecretKey(wrapped), { use: 'enc', alg: enc }) - } + const method = endpointMethodsMap.get(scope).get(methodName); + if (!method) { + return void 0; } - - if (alg === 'dir' || alg === 'ECDH-ES') { - recipient.encrypted_key = '' + const { endpointDefaults, decorations } = method; + if (decorations) { + cache[methodName] = decorate( + octokit, + scope, + methodName, + endpointDefaults, + decorations + ); } else { - recipient.encrypted_key = base64url.encodeBuffer(wrapped) - } - - if (generatedHeader) { - recipient.generatedHeader = generatedHeader + cache[methodName] = octokit.request.defaults(endpointDefaults); } + return cache[methodName]; } - - /* - * @public - */ - encrypt (serialization) { - const serializer = serializers[serialization] - if (!serializer) { - throw new TypeError('serialization must be one of "compact", "flattened", "general"') +}; +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 (!this._recipients.length) { - throw new JWEInvalid('missing recipients') + if (decorations.renamed) { + const [newScope, newMethodName] = decorations.renamed; + octokit.log.warn( + `octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()` + ); } - - serializer.validate(this._protected, this._unprotected, this._aad, this._recipients) - - let enc = validateHeaders(this._protected, this._unprotected, this._recipients, false, this._protected ? this._protected.crit : undefined) - if (!enc) { - enc = 'A128CBC-HS256' - if (this._protected) { - this._protected.enc = enc - } else { - this._protected = { enc } + 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); } - const final = {} - this._cek = generateCEK(enc) + return requestWithDefaults(...args); + } + return Object.assign(withDecorations, requestWithDefaults); +} - for (const recipient of this._recipients) { - this[PROCESS_RECIPIENT](recipient) - } +// 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); - const iv = generateIV(enc) - final.iv = base64url.encodeBuffer(iv) - if (this._recipients.length === 1 && this._recipients[0].generatedHeader) { - const [{ generatedHeader }] = this._recipients - delete this._recipients[0].generatedHeader - this._protected = { - ...this._protected, - ...generatedHeader - } - } +/***/ }), - if (this._protected) { - final.protected = base64url.JSON.encode(this._protected) - } - final.unprotected = this._unprotected +/***/ 10537: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - let aad - if (this._aad) { - final.aad = base64url.encode(this._aad) - aad = Buffer.concat([ - Buffer.from(final.protected || ''), - Buffer.from('.'), - Buffer.from(final.aad) - ]) - } else { - aad = Buffer.from(final.protected || '') - } - - let cleartext = this._cleartext - if (this._protected && 'zip' in this._protected) { - cleartext = deflateRawSync(cleartext) - } - - const { ciphertext, tag } = encrypt(enc, this._cek, cleartext, { iv, aad }) - final.tag = base64url.encodeBuffer(tag) - final.ciphertext = base64url.encodeBuffer(ciphertext) +"use strict"; - return serializer(final, this._recipients) +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); -module.exports = Encrypt +// 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__(58932); +var import_once = __toESM(__nccwpck_require__(1223)); +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( + /(? { -const { randomBytes } = __nccwpck_require__(6113) - -const { createSecretKey } = __nccwpck_require__(31032) -const { KEYLENGTHS } = __nccwpck_require__(47359) -const Key = __nccwpck_require__(14591) - -module.exports = (alg) => { - const keyLength = KEYLENGTHS.get(alg) +"use strict"; - if (!keyLength) { - return new Key({ type: 'secret' }) +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); - return new Key(createSecretKey(randomBytes(keyLength / 8)), { use: 'enc', alg }) -} - - -/***/ }), - -/***/ 22307: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// 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__(59440); +var import_universal_user_agent = __nccwpck_require__(45030); -const Encrypt = __nccwpck_require__(47154) -const decrypt = __nccwpck_require__(20087) +// pkg/dist-src/version.js +var VERSION = "8.4.1"; -const single = (serialization, cleartext, key, protectedHeader, aad, unprotectedHeader) => { - return new Encrypt(cleartext, protectedHeader, aad, unprotectedHeader) - .recipient(key) - .encrypt(serialization) +// 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); } -module.exports.Encrypt = Encrypt -module.exports.encrypt = single.bind(undefined, 'compact') -module.exports.encrypt.flattened = single.bind(undefined, 'flattened') -module.exports.encrypt.general = single.bind(undefined, 'general') - -module.exports.decrypt = decrypt - - -/***/ }), - -/***/ 14609: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const isObject = __nccwpck_require__(50243) -let validateCrit = __nccwpck_require__(85822) - -const { JWEInvalid } = __nccwpck_require__(35132) - -validateCrit = validateCrit.bind(undefined, JWEInvalid) +// pkg/dist-src/fetch-wrapper.js +var import_request_error = __nccwpck_require__(10537); -const compactSerializer = (final, [recipient]) => { - return `${final.protected}.${recipient.encrypted_key}.${final.iv}.${final.ciphertext}.${final.tag}` -} -compactSerializer.validate = (protectedHeader, unprotectedHeader, aad, { 0: { header }, length }) => { - if (length !== 1 || aad || unprotectedHeader || header) { - throw new JWEInvalid('JWE Compact Serialization doesn\'t support multiple recipients, JWE unprotected headers or AAD') - } - validateCrit(protectedHeader, unprotectedHeader, protectedHeader ? protectedHeader.crit : undefined) +// pkg/dist-src/get-buffer-response.js +function getBufferResponse(response) { + return response.arrayBuffer(); } -const flattenedSerializer = (final, [recipient]) => { - const { header, encrypted_key: encryptedKey } = recipient - - return { - ...(final.protected ? { protected: final.protected } : undefined), - ...(final.unprotected ? { unprotected: final.unprotected } : undefined), - ...(header ? { header } : undefined), - ...(encryptedKey ? { encrypted_key: encryptedKey } : undefined), - ...(final.aad ? { aad: final.aad } : undefined), - iv: final.iv, - ciphertext: final.ciphertext, - tag: final.tag +// pkg/dist-src/fetch-wrapper.js +function fetchWrapper(requestOptions) { + var _a, _b, _c, _d; + 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); } -} -flattenedSerializer.validate = (protectedHeader, unprotectedHeader, aad, { 0: { header }, length }) => { - if (length !== 1) { - throw new JWEInvalid('Flattened JWE JSON Serialization doesn\'t support multiple recipients') + let headers = {}; + let status; + let url; + let { fetch } = globalThis; + if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { + fetch = requestOptions.request.fetch; } - validateCrit(protectedHeader, { ...unprotectedHeader, ...header }, protectedHeader ? protectedHeader.crit : undefined) -} - -const generalSerializer = (final, recipients) => { - const result = { - ...(final.protected ? { protected: final.protected } : undefined), - ...(final.unprotected ? { unprotected: final.unprotected } : undefined), - recipients: recipients.map(({ header, encrypted_key: encryptedKey, generatedHeader }) => { - if (!header && !encryptedKey && !generatedHeader) { - return false + 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, + redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, + headers: requestOptions.headers, + signal: (_d = requestOptions.request) == null ? void 0 : _d.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; } - - return { - ...(header || generatedHeader ? { header: { ...header, ...generatedHeader } } : undefined), - ...(encryptedKey ? { encrypted_key: encryptedKey } : undefined) + 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; } - }).filter(Boolean), - ...(final.aad ? { aad: final.aad } : undefined), - iv: final.iv, - ciphertext: final.ciphertext, - tag: final.tag - } - - if (!result.recipients.length) { - delete result.recipients - } - - return result -} -generalSerializer.validate = (protectedHeader, unprotectedHeader, aad, recipients) => { - recipients.forEach(({ header }) => { - validateCrit(protectedHeader, { ...header, ...unprotectedHeader }, protectedHeader ? protectedHeader.crit : undefined) - }) -} - -const isJSON = (input) => { - return isObject(input) && - typeof input.ciphertext === 'string' && - typeof input.iv === 'string' && - typeof input.tag === 'string' && - (input.unprotected === undefined || isObject(input.unprotected)) && - (input.protected === undefined || typeof input.protected === 'string') && - (input.aad === undefined || typeof input.aad === 'string') -} - -const isSingleRecipient = (input) => { - return (input.encrypted_key === undefined || typeof input.encrypted_key === 'string') && - (input.header === undefined || isObject(input.header)) -} - -const isValidRecipient = (recipient) => { - return isObject(recipient) && typeof recipient.encrypted_key === 'string' && (recipient.header === undefined || isObject(recipient.header)) + } + throw new import_request_error.RequestError(message, 500, { + request: requestOptions + }); + }); } - -const isMultiRecipient = (input) => { - if (Array.isArray(input.recipients) && input.recipients.every(isValidRecipient)) { - return true +async function getResponseData(response) { + const contentType = response.headers.get("content-type"); + if (/application\/json/.test(contentType)) { + return response.json().catch(() => response.text()).catch(() => ""); } - - return false + if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) { + return response.text(); + } + return getBufferResponse(response); } - -const detect = (input) => { - if (typeof input === 'string' && input.split('.').length === 5) { - return 'compact' +function toErrorMessage(data) { + if (typeof data === "string") + return data; + let suffix; + if ("documentation_url" in data) { + suffix = ` - ${data.documentation_url}`; + } else { + suffix = ""; } - - if (isJSON(input)) { - if (isMultiRecipient(input)) { - return 'general' - } - - if (isSingleRecipient(input)) { - return 'flattened' + if ("message" in data) { + if (Array.isArray(data.errors)) { + return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`; } + return `${data.message}${suffix}`; } - - throw new JWEInvalid('JWE malformed or invalid serialization') + return `Unknown error: ${JSON.stringify(data)}`; } -module.exports = { - compact: compactSerializer, - flattened: flattenedSerializer, - general: generalSerializer, - detect +// 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); + /***/ }), -/***/ 77997: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const isDisjoint = __nccwpck_require__(48899) -const base64url = __nccwpck_require__(93312) -let validateCrit = __nccwpck_require__(85822) -const { JWEInvalid, JOSENotSupported } = __nccwpck_require__(35132) +/***/ 57171: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -validateCrit = validateCrit.bind(undefined, JWEInvalid) +"use strict"; -module.exports = (prot, unprotected, recipients, checkAlgorithms, crit) => { - if (typeof prot === 'string') { - try { - prot = base64url.JSON.decode(prot) - } catch (err) { - throw new JWEInvalid('could not parse JWE protected header') +/* + * Copyright The OpenTelemetry 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 + * + * https://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.ContextAPI = void 0; +const NoopContextManager_1 = __nccwpck_require__(54118); +const global_utils_1 = __nccwpck_require__(85135); +const diag_1 = __nccwpck_require__(11877); +const API_NAME = 'context'; +const NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager(); +/** + * Singleton object which represents the entry point to the OpenTelemetry Context API + */ +class ContextAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { } + /** Get the singleton instance of the Context API */ + static getInstance() { + if (!this._instance) { + this._instance = new ContextAPI(); + } + return this._instance; } - } - - let alg = [] - const enc = new Set() - if (!isDisjoint(prot, unprotected) || !recipients.every(({ header }) => { - if (typeof header === 'object') { - alg.push(header.alg) - enc.add(header.enc) + /** + * Set the current context manager. + * + * @returns true if the context manager was successfully registered, else false + */ + setGlobalContextManager(contextManager) { + return (0, global_utils_1.registerGlobal)(API_NAME, contextManager, diag_1.DiagAPI.instance()); } - const combined = { ...unprotected, ...header } - validateCrit(prot, combined, crit) - if ('zip' in combined) { - throw new JWEInvalid('"zip" Header Parameter MUST be integrity protected') - } else if (prot && 'zip' in prot && prot.zip !== 'DEF') { - throw new JOSENotSupported('only "DEF" compression algorithm is supported') + /** + * Get the currently active context + */ + active() { + return this._getContextManager().active(); } - return isDisjoint(header, prot) && isDisjoint(header, unprotected) - })) { - throw new JWEInvalid('JWE Shared Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint') - } - - if (typeof prot === 'object') { - alg.push(prot.alg) - enc.add(prot.enc) - } - if (typeof unprotected === 'object') { - alg.push(unprotected.alg) - enc.add(unprotected.enc) - } - - alg = alg.filter(Boolean) - enc.delete(undefined) - - if (recipients.length !== 1) { - if (alg.includes('dir') || alg.includes('ECDH-ES')) { - throw new JWEInvalid('dir and ECDH-ES alg may only be used with a single recipient') + /** + * Execute a function with an active context + * + * @param context context to be active during function execution + * @param fn function to execute in a context + * @param thisArg optional receiver to be used for calling fn + * @param args optional arguments forwarded to fn + */ + with(context, fn, thisArg, ...args) { + return this._getContextManager().with(context, fn, thisArg, ...args); } - } - - if (checkAlgorithms) { - if (alg.length !== recipients.length) { - throw new JWEInvalid('missing Key Management algorithm') + /** + * Bind a context to a target function or event emitter + * + * @param context context to bind to the event emitter or function. Defaults to the currently active context + * @param target function or event emitter to bind + */ + bind(context, target) { + return this._getContextManager().bind(context, target); } - if (enc.size === 0) { - throw new JWEInvalid('missing Content Encryption algorithm') - } else if (enc.size !== 1) { - throw new JWEInvalid('there must only be one Content Encryption algorithm') + _getContextManager() { + return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_CONTEXT_MANAGER; } - } else { - if (enc.size > 1) { - throw new JWEInvalid('there must only be one Content Encryption algorithm') + /** Disable and remove the global context manager */ + disable() { + this._getContextManager().disable(); + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); } - } - - return [...enc][0] } - +exports.ContextAPI = ContextAPI; +//# sourceMappingURL=context.js.map /***/ }), -/***/ 87042: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const errors = __nccwpck_require__(35132) - -const importKey = __nccwpck_require__(77722) - -const RSAKey = __nccwpck_require__(52679) -const ECKey = __nccwpck_require__(36582) -const OKPKey = __nccwpck_require__(27742) -const OctKey = __nccwpck_require__(14591) +/***/ 11877: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const generate = async (kty, crvOrSize, params, generatePrivate = true) => { - switch (kty) { - case 'RSA': - return importKey( - await RSAKey.generate(crvOrSize, generatePrivate), - params - ) - case 'EC': - return importKey( - await ECKey.generate(crvOrSize, generatePrivate), - params - ) - case 'OKP': - return importKey( - await OKPKey.generate(crvOrSize, generatePrivate), - params - ) - case 'oct': - return importKey( - await OctKey.generate(crvOrSize, generatePrivate), - params - ) - default: - throw new errors.JOSENotSupported(`unsupported key type: ${kty}`) - } -} +"use strict"; -const generateSync = (kty, crvOrSize, params, generatePrivate = true) => { - switch (kty) { - case 'RSA': - return importKey(RSAKey.generateSync(crvOrSize, generatePrivate), params) - case 'EC': - return importKey(ECKey.generateSync(crvOrSize, generatePrivate), params) - case 'OKP': - return importKey(OKPKey.generateSync(crvOrSize, generatePrivate), params) - case 'oct': - return importKey(OctKey.generateSync(crvOrSize, generatePrivate), params) - default: - throw new errors.JOSENotSupported(`unsupported key type: ${kty}`) - } +/* + * Copyright The OpenTelemetry 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 + * + * https://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.DiagAPI = void 0; +const ComponentLogger_1 = __nccwpck_require__(17978); +const logLevelLogger_1 = __nccwpck_require__(99639); +const types_1 = __nccwpck_require__(78077); +const global_utils_1 = __nccwpck_require__(85135); +const API_NAME = 'diag'; +/** + * Singleton object which represents the entry point to the OpenTelemetry internal + * diagnostic API + */ +class DiagAPI { + /** + * Private internal constructor + * @private + */ + constructor() { + function _logProxy(funcName) { + return function (...args) { + const logger = (0, global_utils_1.getGlobal)('diag'); + // shortcut if logger not set + if (!logger) + return; + return logger[funcName](...args); + }; + } + // Using self local variable for minification purposes as 'this' cannot be minified + const self = this; + // DiagAPI specific functions + const setLogger = (logger, optionsOrLogLevel = { logLevel: types_1.DiagLogLevel.INFO }) => { + var _a, _b, _c; + if (logger === self) { + // There isn't much we can do here. + // Logging to the console might break the user application. + // Try to log to self. If a logger was previously registered it will receive the log. + const err = new Error('Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'); + self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message); + return false; + } + if (typeof optionsOrLogLevel === 'number') { + optionsOrLogLevel = { + logLevel: optionsOrLogLevel, + }; + } + const oldLogger = (0, global_utils_1.getGlobal)('diag'); + const newLogger = (0, logLevelLogger_1.createLogLevelDiagLogger)((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : types_1.DiagLogLevel.INFO, logger); + // There already is an logger registered. We'll let it know before overwriting it. + if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { + const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ''; + oldLogger.warn(`Current logger will be overwritten from ${stack}`); + newLogger.warn(`Current logger will overwrite one already registered from ${stack}`); + } + return (0, global_utils_1.registerGlobal)('diag', newLogger, self, true); + }; + self.setLogger = setLogger; + self.disable = () => { + (0, global_utils_1.unregisterGlobal)(API_NAME, self); + }; + self.createComponentLogger = (options) => { + return new ComponentLogger_1.DiagComponentLogger(options); + }; + self.verbose = _logProxy('verbose'); + self.debug = _logProxy('debug'); + self.info = _logProxy('info'); + self.warn = _logProxy('warn'); + self.error = _logProxy('error'); + } + /** Get the singleton instance of the DiagAPI API */ + static instance() { + if (!this._instance) { + this._instance = new DiagAPI(); + } + return this._instance; + } } - -module.exports.generate = generate -module.exports.generateSync = generateSync - +exports.DiagAPI = DiagAPI; +//# sourceMappingURL=diag.js.map /***/ }), -/***/ 77722: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { createPublicKey, createPrivateKey, createSecretKey, KeyObject } = __nccwpck_require__(31032) -const base64url = __nccwpck_require__(93312) -const isObject = __nccwpck_require__(50243) -const { jwkToPem } = __nccwpck_require__(65394) -const errors = __nccwpck_require__(35132) - -const RSAKey = __nccwpck_require__(52679) -const ECKey = __nccwpck_require__(36582) -const OKPKey = __nccwpck_require__(27742) -const OctKey = __nccwpck_require__(14591) +/***/ 17696: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const importable = new Set(['string', 'buffer', 'object']) +"use strict"; -const mergedParameters = (target = {}, source = {}) => { - return { - alg: source.alg, - key_ops: source.key_ops, - kid: source.kid, - use: source.use, - x5c: source.x5c, - x5t: source.x5t, - 'x5t#S256': source['x5t#S256'], - ...target - } +/* + * Copyright The OpenTelemetry 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 + * + * https://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.MetricsAPI = void 0; +const NoopMeterProvider_1 = __nccwpck_require__(72647); +const global_utils_1 = __nccwpck_require__(85135); +const diag_1 = __nccwpck_require__(11877); +const API_NAME = 'metrics'; +/** + * Singleton object which represents the entry point to the OpenTelemetry Metrics API + */ +class MetricsAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { } + /** Get the singleton instance of the Metrics API */ + static getInstance() { + if (!this._instance) { + this._instance = new MetricsAPI(); + } + return this._instance; + } + /** + * Set the current global meter provider. + * Returns true if the meter provider was successfully registered, else false. + */ + setGlobalMeterProvider(provider) { + return (0, global_utils_1.registerGlobal)(API_NAME, provider, diag_1.DiagAPI.instance()); + } + /** + * Returns the global meter provider. + */ + getMeterProvider() { + return (0, global_utils_1.getGlobal)(API_NAME) || NoopMeterProvider_1.NOOP_METER_PROVIDER; + } + /** + * Returns a meter from the global meter provider. + */ + getMeter(name, version, options) { + return this.getMeterProvider().getMeter(name, version, options); + } + /** Remove the global meter provider */ + disable() { + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + } } +exports.MetricsAPI = MetricsAPI; +//# sourceMappingURL=metrics.js.map -const openSSHpublicKey = /^[a-zA-Z0-9-]+ AAAA(?:[0-9A-Za-z+/])+(?:==|=)?(?: .*)?$/ - -const asKey = (key, parameters, { calculateMissingRSAPrimes = false } = {}) => { - let privateKey, publicKey, secret +/***/ }), - if (!importable.has(typeof key)) { - throw new TypeError('key argument must be a string, buffer or an object') - } +/***/ 89909: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (parameters !== undefined && !isObject(parameters)) { - throw new TypeError('parameters argument must be a plain object when provided') - } +"use strict"; - if (key instanceof KeyObject) { - switch (key.type) { - case 'private': - privateKey = key - break - case 'public': - publicKey = key - break - case 'secret': - secret = key - break +/* + * Copyright The OpenTelemetry 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 + * + * https://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.PropagationAPI = void 0; +const global_utils_1 = __nccwpck_require__(85135); +const NoopTextMapPropagator_1 = __nccwpck_require__(72368); +const TextMapPropagator_1 = __nccwpck_require__(80865); +const context_helpers_1 = __nccwpck_require__(37682); +const utils_1 = __nccwpck_require__(28136); +const diag_1 = __nccwpck_require__(11877); +const API_NAME = 'propagation'; +const NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator(); +/** + * Singleton object which represents the entry point to the OpenTelemetry Propagation API + */ +class PropagationAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { + this.createBaggage = utils_1.createBaggage; + this.getBaggage = context_helpers_1.getBaggage; + this.getActiveBaggage = context_helpers_1.getActiveBaggage; + this.setBaggage = context_helpers_1.setBaggage; + this.deleteBaggage = context_helpers_1.deleteBaggage; } - } else if (typeof key === 'object' && key && 'kty' in key && key.kty === 'oct') { // symmetric key - try { - secret = createSecretKey(base64url.decodeToBuffer(key.k)) - } catch (err) { - if (!('k' in key)) { - secret = { type: 'secret' } - } + /** Get the singleton instance of the Propagator API */ + static getInstance() { + if (!this._instance) { + this._instance = new PropagationAPI(); + } + return this._instance; } - parameters = mergedParameters(parameters, key) - } else if (typeof key === 'object' && key && 'kty' in key) { // assume JWK formatted asymmetric key - ({ calculateMissingRSAPrimes = false } = parameters || { calculateMissingRSAPrimes }) - let pem - - try { - pem = jwkToPem(key, { calculateMissingRSAPrimes }) - } catch (err) { - if (err instanceof errors.JOSEError) { - throw err - } + /** + * Set the current propagator. + * + * @returns true if the propagator was successfully registered, else false + */ + setGlobalPropagator(propagator) { + return (0, global_utils_1.registerGlobal)(API_NAME, propagator, diag_1.DiagAPI.instance()); } - - if (pem && key.d) { - privateKey = createPrivateKey(pem) - } else if (pem) { - publicKey = createPublicKey(pem) + /** + * Inject context into a carrier to be propagated inter-process + * + * @param context Context carrying tracing data to inject + * @param carrier carrier to inject context into + * @param setter Function used to set values on the carrier + */ + inject(context, carrier, setter = TextMapPropagator_1.defaultTextMapSetter) { + return this._getGlobalPropagator().inject(context, carrier, setter); } - - parameters = mergedParameters({}, key) - } else if (key && (typeof key === 'object' || typeof key === 'string')) { // | | passed to crypto.createPrivateKey or crypto.createPublicKey or passed to crypto.createSecretKey - try { - privateKey = createPrivateKey(key) - } catch (err) { - if (err instanceof errors.JOSEError) { - throw err - } + /** + * Extract context from a carrier + * + * @param context Context which the newly created context will inherit from + * @param carrier Carrier to extract context from + * @param getter Function used to extract keys from a carrier + */ + extract(context, carrier, getter = TextMapPropagator_1.defaultTextMapGetter) { + return this._getGlobalPropagator().extract(context, carrier, getter); } - - try { - publicKey = createPublicKey(key) - if (key.startsWith('-----BEGIN CERTIFICATE-----') && (!parameters || !('x5c' in parameters))) { - parameters = mergedParameters(parameters, { - x5c: [key.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g, '')] - }) - } - } catch (err) { - if (err instanceof errors.JOSEError) { - throw err - } + /** + * Return a list of all fields which may be used by the propagator. + */ + fields() { + return this._getGlobalPropagator().fields(); } - - try { - // this is to filter out invalid PEM keys and certs, i'll rather have them fail import then - // have them imported as symmetric "oct" keys - if (!key.includes('-----BEGIN') && !openSSHpublicKey.test(key.toString('ascii').replace(/[\r\n]/g, ''))) { - secret = createSecretKey(Buffer.isBuffer(key) ? key : Buffer.from(key)) - } - } catch (err) {} - } - - const keyObject = privateKey || publicKey || secret - - if (privateKey || publicKey) { - switch (keyObject.asymmetricKeyType) { - case 'rsa': - return new RSAKey(keyObject, parameters) - case 'ec': - return new ECKey(keyObject, parameters) - case 'ed25519': - case 'ed448': - case 'x25519': - case 'x448': - return new OKPKey(keyObject, parameters) - default: - throw new errors.JOSENotSupported('only RSA, EC and OKP asymmetric keys are supported') + /** Remove the global propagator */ + disable() { + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + } + _getGlobalPropagator() { + return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR; } - } else if (secret) { - return new OctKey(keyObject, parameters) - } - - throw new errors.JWKImportFailed('key import failed') -} - -module.exports = asKey - - -/***/ }), - -/***/ 2297: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const Key = __nccwpck_require__(99795) -const None = __nccwpck_require__(48114) -const EmbeddedJWK = __nccwpck_require__(59116) -const EmbeddedX5C = __nccwpck_require__(79313) -const importKey = __nccwpck_require__(77722) -const generate = __nccwpck_require__(87042) - -module.exports = { - ...generate, - asKey: importKey, - isKey: input => input instanceof Key, - None, - EmbeddedJWK, - EmbeddedX5C } - +exports.PropagationAPI = PropagationAPI; +//# sourceMappingURL=propagation.js.map /***/ }), -/***/ 99795: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { strict: assert } = __nccwpck_require__(39491) -const { inspect } = __nccwpck_require__(73837) -const { EOL } = __nccwpck_require__(22037) - -const { keyObjectSupported } = __nccwpck_require__(57494) -const { createPublicKey } = __nccwpck_require__(31032) -const { keyObjectToJWK } = __nccwpck_require__(65394) -const { - THUMBPRINT_MATERIAL, PUBLIC_MEMBERS, PRIVATE_MEMBERS, JWK_MEMBERS, KEYOBJECT, - USES_MAPPING, OPS, USES -} = __nccwpck_require__(62928) -const isObject = __nccwpck_require__(50243) -const thumbprint = __nccwpck_require__(89020) -const errors = __nccwpck_require__(35132) - -const privateApi = Symbol('privateApi') -const { JWK } = __nccwpck_require__(47359) - -class Key { - constructor (keyObject, { alg, use, kid, key_ops: ops, x5c, x5t, 'x5t#S256': x5t256 } = {}) { - if (use !== undefined) { - if (typeof use !== 'string' || !USES.has(use)) { - throw new TypeError('`use` must be either "sig" or "enc" string when provided') - } - } - - if (alg !== undefined) { - if (typeof alg !== 'string' || !alg) { - throw new TypeError('`alg` must be a non-empty string when provided') - } - } - - if (kid !== undefined) { - if (typeof kid !== 'string' || !kid) { - throw new TypeError('`kid` must be a non-empty string when provided') - } - } +/***/ 81539: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (ops !== undefined) { - if (!Array.isArray(ops) || !ops.length || ops.some(o => typeof o !== 'string')) { - throw new TypeError('`key_ops` must be a non-empty array of strings when provided') - } - ops = Array.from(new Set(ops)).filter(x => OPS.has(x)) - } +"use strict"; - if (ops && use) { - if ( - (use === 'enc' && ops.some(x => USES_MAPPING.sig.has(x))) || - (use === 'sig' && ops.some(x => USES_MAPPING.enc.has(x))) - ) { - throw new errors.JWKInvalid('inconsistent JWK "use" and "key_ops"') - } - } - - if (keyObjectSupported && x5c !== undefined) { - if (!Array.isArray(x5c) || !x5c.length || x5c.some(c => typeof c !== 'string')) { - throw new TypeError('`x5c` must be an array of one or more PKIX certificates when provided') - } - - x5c.forEach((cert, i) => { - let publicKey - try { - publicKey = createPublicKey({ - key: `-----BEGIN CERTIFICATE-----${EOL}${(cert.match(/.{1,64}/g) || []).join(EOL)}${EOL}-----END CERTIFICATE-----`, format: 'pem' - }) - } catch (err) { - throw new errors.JWKInvalid(`\`x5c\` member at index ${i} is not a valid base64-encoded DER PKIX certificate`) - } - if (i === 0) { - try { - assert.deepEqual( - publicKey.export({ type: 'spki', format: 'der' }), - (keyObject.type === 'public' ? keyObject : createPublicKey(keyObject)).export({ type: 'spki', format: 'der' }) - ) - } catch (err) { - throw new errors.JWKInvalid('The key in the first `x5c` certificate MUST match the public key represented by the JWK') - } +/* + * Copyright The OpenTelemetry 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 + * + * https://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.TraceAPI = void 0; +const global_utils_1 = __nccwpck_require__(85135); +const ProxyTracerProvider_1 = __nccwpck_require__(2285); +const spancontext_utils_1 = __nccwpck_require__(49745); +const context_utils_1 = __nccwpck_require__(23326); +const diag_1 = __nccwpck_require__(11877); +const API_NAME = 'trace'; +/** + * Singleton object which represents the entry point to the OpenTelemetry Tracing API + */ +class TraceAPI { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { + this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); + this.wrapSpanContext = spancontext_utils_1.wrapSpanContext; + this.isSpanContextValid = spancontext_utils_1.isSpanContextValid; + this.deleteSpan = context_utils_1.deleteSpan; + this.getSpan = context_utils_1.getSpan; + this.getActiveSpan = context_utils_1.getActiveSpan; + this.getSpanContext = context_utils_1.getSpanContext; + this.setSpan = context_utils_1.setSpan; + this.setSpanContext = context_utils_1.setSpanContext; + } + /** Get the singleton instance of the Trace API */ + static getInstance() { + if (!this._instance) { + this._instance = new TraceAPI(); } - }) + return this._instance; } - - Object.defineProperties(this, { - [KEYOBJECT]: { value: isObject(keyObject) ? undefined : keyObject }, - keyObject: { - get () { - if (!keyObjectSupported) { - throw new errors.JOSENotSupported('KeyObject class is not supported in your Node.js runtime version') - } - - return this[KEYOBJECT] + /** + * Set the current global tracer. + * + * @returns true if the tracer provider was successfully registered, else false + */ + setGlobalTracerProvider(provider) { + const success = (0, global_utils_1.registerGlobal)(API_NAME, this._proxyTracerProvider, diag_1.DiagAPI.instance()); + if (success) { + this._proxyTracerProvider.setDelegate(provider); } - }, - type: { value: keyObject.type }, - private: { value: keyObject.type === 'private' }, - public: { value: keyObject.type === 'public' }, - secret: { value: keyObject.type === 'secret' }, - alg: { value: alg, enumerable: alg !== undefined }, - use: { value: use, enumerable: use !== undefined }, - x5c: { - enumerable: x5c !== undefined, - ...(x5c ? { get () { return [...x5c] } } : { value: undefined }) - }, - key_ops: { - enumerable: ops !== undefined, - ...(ops ? { get () { return [...ops] } } : { value: undefined }) - }, - kid: { - enumerable: true, - ...(kid - ? { value: kid } - : { - get () { - Object.defineProperty(this, 'kid', { value: this.thumbprint, configurable: false }) - return this.kid - }, - configurable: true - }) - }, - ...(x5c - ? { - x5t: { - enumerable: true, - ...(x5t - ? { value: x5t } - : { - get () { - Object.defineProperty(this, 'x5t', { value: thumbprint.x5t(this.x5c[0]), configurable: false }) - return this.x5t - }, - configurable: true - }) - } - } - : undefined), - ...(x5c - ? { - 'x5t#S256': { - enumerable: true, - ...(x5t256 - ? { value: x5t256 } - : { - get () { - Object.defineProperty(this, 'x5t#S256', { value: thumbprint['x5t#S256'](this.x5c[0]), configurable: false }) - return this['x5t#S256'] - }, - configurable: true - }) - } - } - : undefined), - thumbprint: { - get () { - Object.defineProperty(this, 'thumbprint', { value: thumbprint.kid(this[THUMBPRINT_MATERIAL]()), configurable: false }) - return this.thumbprint - }, - configurable: true - } - }) - } - - toPEM (priv = false, encoding = {}) { - if (this.secret) { - throw new TypeError('symmetric keys cannot be exported as PEM') + return success; } - - if (priv && this.public === true) { - throw new TypeError('public key cannot be exported as private') + /** + * Returns the global tracer provider. + */ + getTracerProvider() { + return (0, global_utils_1.getGlobal)(API_NAME) || this._proxyTracerProvider; } - - const { type = priv ? 'pkcs8' : 'spki', cipher, passphrase } = encoding - - let keyObject = this[KEYOBJECT] - - if (!priv) { - if (this.private) { - keyObject = createPublicKey(keyObject) - } - if (cipher || passphrase) { - throw new TypeError('cipher and passphrase can only be applied when exporting private keys') - } + /** + * Returns a tracer from the global tracer provider. + */ + getTracer(name, version) { + return this.getTracerProvider().getTracer(name, version); } - - if (priv) { - return keyObject.export({ format: 'pem', type, cipher, passphrase }) + /** Remove the global tracer provider */ + disable() { + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); } +} +exports.TraceAPI = TraceAPI; +//# sourceMappingURL=trace.js.map - return keyObject.export({ format: 'pem', type }) - } +/***/ }), - toJWK (priv = false) { - if (priv && this.public === true) { - throw new TypeError('public key cannot be exported as private') - } +/***/ 37682: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const components = [...this.constructor[priv ? PRIVATE_MEMBERS : PUBLIC_MEMBERS]] - .map(k => [k, this[k]]) +"use strict"; - const result = {} +/* + * Copyright The OpenTelemetry 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 + * + * https://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.deleteBaggage = exports.setBaggage = exports.getActiveBaggage = exports.getBaggage = void 0; +const context_1 = __nccwpck_require__(57171); +const context_2 = __nccwpck_require__(78242); +/** + * Baggage key + */ +const BAGGAGE_KEY = (0, context_2.createContextKey)('OpenTelemetry Baggage Key'); +/** + * Retrieve the current baggage from the given context + * + * @param {Context} Context that manage all context values + * @returns {Baggage} Extracted baggage from the context + */ +function getBaggage(context) { + return context.getValue(BAGGAGE_KEY) || undefined; +} +exports.getBaggage = getBaggage; +/** + * Retrieve the current baggage from the active/current context + * + * @returns {Baggage} Extracted baggage from the context + */ +function getActiveBaggage() { + return getBaggage(context_1.ContextAPI.getInstance().active()); +} +exports.getActiveBaggage = getActiveBaggage; +/** + * Store a baggage in the given context + * + * @param {Context} Context that manage all context values + * @param {Baggage} baggage that will be set in the actual context + */ +function setBaggage(context, baggage) { + return context.setValue(BAGGAGE_KEY, baggage); +} +exports.setBaggage = setBaggage; +/** + * Delete the baggage stored in the given context + * + * @param {Context} Context that manage all context values + */ +function deleteBaggage(context) { + return context.deleteValue(BAGGAGE_KEY); +} +exports.deleteBaggage = deleteBaggage; +//# sourceMappingURL=context-helpers.js.map - Object.keys(components).forEach((key) => { - const [k, v] = components[key] +/***/ }), - result[k] = v - }) +/***/ 84811: +/***/ ((__unused_webpack_module, exports) => { - result.kty = this.kty - result.kid = this.kid +"use strict"; - if (this.alg) { - result.alg = this.alg +/* + * Copyright The OpenTelemetry 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 + * + * https://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.BaggageImpl = void 0; +class BaggageImpl { + constructor(entries) { + this._entries = entries ? new Map(entries) : new Map(); } - - if (this.key_ops && this.key_ops.length) { - result.key_ops = this.key_ops + getEntry(key) { + const entry = this._entries.get(key); + if (!entry) { + return undefined; + } + return Object.assign({}, entry); } - - if (this.use) { - result.use = this.use + getAllEntries() { + return Array.from(this._entries.entries()).map(([k, v]) => [k, v]); } - - if (this.x5c) { - result.x5c = this.x5c + setEntry(key, entry) { + const newBaggage = new BaggageImpl(this._entries); + newBaggage._entries.set(key, entry); + return newBaggage; } - - if (this.x5t) { - result.x5t = this.x5t + removeEntry(key) { + const newBaggage = new BaggageImpl(this._entries); + newBaggage._entries.delete(key); + return newBaggage; } - - if (this['x5t#S256']) { - result['x5t#S256'] = this['x5t#S256'] + removeEntries(...keys) { + const newBaggage = new BaggageImpl(this._entries); + for (const key of keys) { + newBaggage._entries.delete(key); + } + return newBaggage; } + clear() { + return new BaggageImpl(); + } +} +exports.BaggageImpl = BaggageImpl; +//# sourceMappingURL=baggage-impl.js.map - return result - } - - [JWK_MEMBERS] () { - const props = this[KEYOBJECT].type === 'private' ? this.constructor[PRIVATE_MEMBERS] : this.constructor[PUBLIC_MEMBERS] - Object.defineProperties(this, [...props].reduce((acc, component) => { - acc[component] = { - get () { - const jwk = keyObjectToJWK(this[KEYOBJECT]) - Object.defineProperties( - this, - Object.entries(jwk) - .filter(([key]) => props.has(key)) - .reduce((acc, [key, value]) => { - acc[key] = { value, enumerable: this.constructor[PUBLIC_MEMBERS].has(key), configurable: false } - return acc - }, {}) - ) +/***/ }), - return this[component] - }, - enumerable: this.constructor[PUBLIC_MEMBERS].has(component), - configurable: true - } - return acc - }, {})) - } +/***/ 23542: +/***/ ((__unused_webpack_module, exports) => { - /* c8 ignore next 8 */ - [inspect.custom] () { - return `${this.constructor.name} ${inspect(this.toJWK(false), { - depth: Infinity, - colors: process.stdout.isTTY, - compact: false, - sorted: true - })}` - } +"use strict"; - /* c8 ignore next 3 */ - [THUMBPRINT_MATERIAL] () { - throw new Error(`"[THUMBPRINT_MATERIAL]()" is not implemented on ${this.constructor.name}`) - } +/* + * Copyright The OpenTelemetry 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 + * + * https://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.baggageEntryMetadataSymbol = void 0; +/** + * Symbol used to make BaggageEntryMetadata an opaque type + */ +exports.baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata'); +//# sourceMappingURL=symbol.js.map - algorithms (operation, /* the rest is private API */ int, opts) { - const { use = this.use, alg = this.alg, key_ops: ops = this.key_ops } = int === privateApi ? opts : {} - if (alg) { - return new Set(this.algorithms(operation, privateApi, { alg: null, use, key_ops: ops }).has(alg) ? [alg] : undefined) - } +/***/ }), - if (typeof operation === 'symbol') { - try { - return this[operation]() - } catch (err) { - return new Set() - } - } +/***/ 28136: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (operation && ops && !ops.includes(operation)) { - return new Set() - } +"use strict"; - switch (operation) { - case 'decrypt': - case 'deriveKey': - case 'encrypt': - case 'sign': - case 'unwrapKey': - case 'verify': - case 'wrapKey': - return new Set(Object.entries(JWK[this.kty][operation]).map(([alg, fn]) => fn(this) ? alg : undefined).filter(Boolean)) - case undefined: - return new Set([ - ...this.algorithms('sign'), - ...this.algorithms('verify'), - ...this.algorithms('decrypt'), - ...this.algorithms('encrypt'), - ...this.algorithms('unwrapKey'), - ...this.algorithms('wrapKey'), - ...this.algorithms('deriveKey') - ]) - default: - throw new TypeError('invalid key operation') +/* + * Copyright The OpenTelemetry 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 + * + * https://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.baggageEntryMetadataFromString = exports.createBaggage = void 0; +const diag_1 = __nccwpck_require__(11877); +const baggage_impl_1 = __nccwpck_require__(84811); +const symbol_1 = __nccwpck_require__(23542); +const diag = diag_1.DiagAPI.instance(); +/** + * Create a new Baggage with optional entries + * + * @param entries An array of baggage entries the new baggage should contain + */ +function createBaggage(entries = {}) { + return new baggage_impl_1.BaggageImpl(new Map(Object.entries(entries))); +} +exports.createBaggage = createBaggage; +/** + * Create a serializable BaggageEntryMetadata object from a string. + * + * @param str string metadata. Format is currently not defined by the spec and has no special meaning. + * + */ +function baggageEntryMetadataFromString(str) { + if (typeof str !== 'string') { + diag.error(`Cannot create baggage metadata from unknown type: ${typeof str}`); + str = ''; } - } - - /* c8 ignore next 3 */ - static async generate () { - throw new Error(`"static async generate()" is not implemented on ${this.name}`) - } - - /* c8 ignore next 3 */ - static generateSync () { - throw new Error(`"static generateSync()" is not implemented on ${this.name}`) - } - - /* c8 ignore next 3 */ - static get [PUBLIC_MEMBERS] () { - throw new Error(`"static get [PUBLIC_MEMBERS]()" is not implemented on ${this.name}`) - } - - /* c8 ignore next 3 */ - static get [PRIVATE_MEMBERS] () { - throw new Error(`"static get [PRIVATE_MEMBERS]()" is not implemented on ${this.name}`) - } + return { + __TYPE__: symbol_1.baggageEntryMetadataSymbol, + toString() { + return str; + }, + }; } - -module.exports = Key - +exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString; +//# sourceMappingURL=utils.js.map /***/ }), -/***/ 36582: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { generateKeyPairSync, generateKeyPair: async } = __nccwpck_require__(6113) -const { promisify } = __nccwpck_require__(73837) - -const { - THUMBPRINT_MATERIAL, JWK_MEMBERS, PUBLIC_MEMBERS, - PRIVATE_MEMBERS, KEY_MANAGEMENT_DECRYPT, KEY_MANAGEMENT_ENCRYPT -} = __nccwpck_require__(62928) -const { EC_CURVES } = __nccwpck_require__(47359) -const { keyObjectSupported } = __nccwpck_require__(57494) -const { createPublicKey, createPrivateKey } = __nccwpck_require__(31032) - -const errors = __nccwpck_require__(35132) - -const Key = __nccwpck_require__(99795) - -const generateKeyPair = promisify(async) - -const EC_PUBLIC = new Set(['crv', 'x', 'y']) -Object.freeze(EC_PUBLIC) -const EC_PRIVATE = new Set([...EC_PUBLIC, 'd']) -Object.freeze(EC_PRIVATE) +/***/ 7393: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// Elliptic Curve Key Type -class ECKey extends Key { - constructor (...args) { - super(...args) - this[JWK_MEMBERS]() - Object.defineProperty(this, 'kty', { value: 'EC', enumerable: true }) - if (!EC_CURVES.has(this.crv)) { - throw new errors.JOSENotSupported('unsupported EC key curve') - } - } +"use strict"; - static get [PUBLIC_MEMBERS] () { - return EC_PUBLIC - } +/* + * Copyright The OpenTelemetry 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 + * + * https://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.context = void 0; +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +const context_1 = __nccwpck_require__(57171); +/** Entrypoint for context API */ +exports.context = context_1.ContextAPI.getInstance(); +//# sourceMappingURL=context-api.js.map - static get [PRIVATE_MEMBERS] () { - return EC_PRIVATE - } +/***/ }), - // https://tc39.github.io/ecma262/#sec-ordinaryownpropertykeys no need for any special - // JSON.stringify handling in V8 - [THUMBPRINT_MATERIAL] () { - return { crv: this.crv, kty: 'EC', x: this.x, y: this.y } - } +/***/ 54118: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - [KEY_MANAGEMENT_ENCRYPT] () { - return this.algorithms('deriveKey') - } +"use strict"; - [KEY_MANAGEMENT_DECRYPT] () { - if (this.public) { - return new Set() +/* + * Copyright The OpenTelemetry 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 + * + * https://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.NoopContextManager = void 0; +const context_1 = __nccwpck_require__(78242); +class NoopContextManager { + active() { + return context_1.ROOT_CONTEXT; } - return this.algorithms('deriveKey') - } - - static async generate (crv = 'P-256', privat = true) { - if (!EC_CURVES.has(crv)) { - throw new errors.JOSENotSupported(`unsupported EC key curve: ${crv}`) + with(_context, fn, thisArg, ...args) { + return fn.call(thisArg, ...args); } - - let privateKey, publicKey - - if (keyObjectSupported) { - ({ privateKey, publicKey } = await generateKeyPair('ec', { namedCurve: crv })) - return privat ? privateKey : publicKey + bind(_context, target) { + return target; } - - ({ privateKey, publicKey } = await generateKeyPair('ec', { - namedCurve: crv, - publicKeyEncoding: { type: 'spki', format: 'pem' }, - privateKeyEncoding: { type: 'pkcs8', format: 'pem' } - })) - - if (privat) { - return createPrivateKey(privateKey) - } else { - return createPublicKey(publicKey) + enable() { + return this; } - } - - static generateSync (crv = 'P-256', privat = true) { - if (!EC_CURVES.has(crv)) { - throw new errors.JOSENotSupported(`unsupported EC key curve: ${crv}`) + disable() { + return this; } +} +exports.NoopContextManager = NoopContextManager; +//# sourceMappingURL=NoopContextManager.js.map - let privateKey, publicKey +/***/ }), - if (keyObjectSupported) { - ({ privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: crv })) - return privat ? privateKey : publicKey - } +/***/ 78242: +/***/ ((__unused_webpack_module, exports) => { - ({ privateKey, publicKey } = generateKeyPairSync('ec', { - namedCurve: crv, - publicKeyEncoding: { type: 'spki', format: 'pem' }, - privateKeyEncoding: { type: 'pkcs8', format: 'pem' } - })) +"use strict"; - if (privat) { - return createPrivateKey(privateKey) - } else { - return createPublicKey(publicKey) +/* + * Copyright The OpenTelemetry 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 + * + * https://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.ROOT_CONTEXT = exports.createContextKey = void 0; +/** Get a key to uniquely identify a context value */ +function createContextKey(description) { + // The specification states that for the same input, multiple calls should + // return different keys. Due to the nature of the JS dependency management + // system, this creates problems where multiple versions of some package + // could hold different keys for the same property. + // + // Therefore, we use Symbol.for which returns the same key for the same input. + return Symbol.for(description); +} +exports.createContextKey = createContextKey; +class BaseContext { + /** + * Construct a new context which inherits values from an optional parent context. + * + * @param parentContext a context from which to inherit values + */ + constructor(parentContext) { + // for minification + const self = this; + self._currentContext = parentContext ? new Map(parentContext) : new Map(); + self.getValue = (key) => self._currentContext.get(key); + self.setValue = (key, value) => { + const context = new BaseContext(self._currentContext); + context._currentContext.set(key, value); + return context; + }; + self.deleteValue = (key) => { + const context = new BaseContext(self._currentContext); + context._currentContext.delete(key); + return context; + }; } - } } - -module.exports = ECKey - +/** The root context is used as the default parent context when there is no active context */ +exports.ROOT_CONTEXT = new BaseContext(); +//# sourceMappingURL=context.js.map /***/ }), -/***/ 59116: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { inspect } = __nccwpck_require__(73837) +/***/ 39721: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const Key = __nccwpck_require__(99795) +"use strict"; -class EmbeddedJWK extends Key { - constructor () { - super({ type: 'embedded' }) - Object.defineProperties(this, { - kid: { value: undefined }, - kty: { value: undefined }, - thumbprint: { value: undefined }, - toJWK: { value: undefined }, - toPEM: { value: undefined } - }) - } +/* + * Copyright The OpenTelemetry 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 + * + * https://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.diag = void 0; +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +const diag_1 = __nccwpck_require__(11877); +/** + * Entrypoint for Diag API. + * Defines Diagnostic handler used for internal diagnostic logging operations. + * The default provides a Noop DiagLogger implementation which may be changed via the + * diag.setLogger(logger: DiagLogger) function. + */ +exports.diag = diag_1.DiagAPI.instance(); +//# sourceMappingURL=diag-api.js.map - /* c8 ignore next 3 */ - [inspect.custom] () { - return 'Embedded.JWK {}' - } +/***/ }), - algorithms () { - return new Set() - } -} +/***/ 17978: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -module.exports = new EmbeddedJWK() +"use strict"; +/* + * Copyright The OpenTelemetry 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 + * + * https://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.DiagComponentLogger = void 0; +const global_utils_1 = __nccwpck_require__(85135); +/** + * Component Logger which is meant to be used as part of any component which + * will add automatically additional namespace in front of the log message. + * It will then forward all message to global diag logger + * @example + * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' }); + * cLogger.debug('test'); + * // @opentelemetry/instrumentation-http test + */ +class DiagComponentLogger { + constructor(props) { + this._namespace = props.namespace || 'DiagComponentLogger'; + } + debug(...args) { + return logProxy('debug', this._namespace, args); + } + error(...args) { + return logProxy('error', this._namespace, args); + } + info(...args) { + return logProxy('info', this._namespace, args); + } + warn(...args) { + return logProxy('warn', this._namespace, args); + } + verbose(...args) { + return logProxy('verbose', this._namespace, args); + } +} +exports.DiagComponentLogger = DiagComponentLogger; +function logProxy(funcName, namespace, args) { + const logger = (0, global_utils_1.getGlobal)('diag'); + // shortcut if logger not set + if (!logger) { + return; + } + args.unshift(namespace); + return logger[funcName](...args); +} +//# sourceMappingURL=ComponentLogger.js.map /***/ }), -/***/ 79313: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { inspect } = __nccwpck_require__(73837) - -const Key = __nccwpck_require__(99795) - -class EmbeddedX5C extends Key { - constructor () { - super({ type: 'embedded' }) - Object.defineProperties(this, { - kid: { value: undefined }, - kty: { value: undefined }, - thumbprint: { value: undefined }, - toJWK: { value: undefined }, - toPEM: { value: undefined } - }) - } +/***/ 3041: +/***/ ((__unused_webpack_module, exports) => { - /* c8 ignore next 3 */ - [inspect.custom] () { - return 'Embedded.X5C {}' - } +"use strict"; - algorithms () { - return new Set() - } +/* + * Copyright The OpenTelemetry 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 + * + * https://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.DiagConsoleLogger = void 0; +const consoleMap = [ + { n: 'error', c: 'error' }, + { n: 'warn', c: 'warn' }, + { n: 'info', c: 'info' }, + { n: 'debug', c: 'debug' }, + { n: 'verbose', c: 'trace' }, +]; +/** + * A simple Immutable Console based diagnostic logger which will output any messages to the Console. + * If you want to limit the amount of logging to a specific level or lower use the + * {@link createLogLevelDiagLogger} + */ +class DiagConsoleLogger { + constructor() { + function _consoleFunc(funcName) { + return function (...args) { + if (console) { + // Some environments only expose the console when the F12 developer console is open + // eslint-disable-next-line no-console + let theFunc = console[funcName]; + if (typeof theFunc !== 'function') { + // Not all environments support all functions + // eslint-disable-next-line no-console + theFunc = console.log; + } + // One last final check + if (typeof theFunc === 'function') { + return theFunc.apply(console, args); + } + } + }; + } + for (let i = 0; i < consoleMap.length; i++) { + this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c); + } + } } - -module.exports = new EmbeddedX5C() - +exports.DiagConsoleLogger = DiagConsoleLogger; +//# sourceMappingURL=consoleLogger.js.map /***/ }), -/***/ 48114: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { inspect } = __nccwpck_require__(73837) - -const Key = __nccwpck_require__(99795) - -class NoneKey extends Key { - constructor () { - super({ type: 'unsecured' }, { alg: 'none' }) - Object.defineProperties(this, { - kid: { value: undefined }, - kty: { value: undefined }, - thumbprint: { value: undefined }, - toJWK: { value: undefined }, - toPEM: { value: undefined } - }) - } +/***/ 99639: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /* c8 ignore next 3 */ - [inspect.custom] () { - return 'None {}' - } +"use strict"; - algorithms (operation) { - switch (operation) { - case 'sign': - case 'verify': - case undefined: - return new Set(['none']) - default: - return new Set() +/* + * Copyright The OpenTelemetry 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 + * + * https://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.createLogLevelDiagLogger = void 0; +const types_1 = __nccwpck_require__(78077); +function createLogLevelDiagLogger(maxLevel, logger) { + if (maxLevel < types_1.DiagLogLevel.NONE) { + maxLevel = types_1.DiagLogLevel.NONE; } - } + else if (maxLevel > types_1.DiagLogLevel.ALL) { + maxLevel = types_1.DiagLogLevel.ALL; + } + // In case the logger is null or undefined + logger = logger || {}; + function _filterFunc(funcName, theLevel) { + const theFunc = logger[funcName]; + if (typeof theFunc === 'function' && maxLevel >= theLevel) { + return theFunc.bind(logger); + } + return function () { }; + } + return { + error: _filterFunc('error', types_1.DiagLogLevel.ERROR), + warn: _filterFunc('warn', types_1.DiagLogLevel.WARN), + info: _filterFunc('info', types_1.DiagLogLevel.INFO), + debug: _filterFunc('debug', types_1.DiagLogLevel.DEBUG), + verbose: _filterFunc('verbose', types_1.DiagLogLevel.VERBOSE), + }; } - -module.exports = new NoneKey() - +exports.createLogLevelDiagLogger = createLogLevelDiagLogger; +//# sourceMappingURL=logLevelLogger.js.map /***/ }), -/***/ 14591: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { randomBytes } = __nccwpck_require__(6113) - -const { createSecretKey } = __nccwpck_require__(31032) -const base64url = __nccwpck_require__(93312) -const { - THUMBPRINT_MATERIAL, PUBLIC_MEMBERS, PRIVATE_MEMBERS, - KEY_MANAGEMENT_DECRYPT, KEY_MANAGEMENT_ENCRYPT, KEYOBJECT -} = __nccwpck_require__(62928) - -const Key = __nccwpck_require__(99795) +/***/ 78077: +/***/ ((__unused_webpack_module, exports) => { -const OCT_PUBLIC = new Set() -Object.freeze(OCT_PUBLIC) -const OCT_PRIVATE = new Set(['k']) -Object.freeze(OCT_PRIVATE) +"use strict"; -// Octet sequence Key Type -class OctKey extends Key { - constructor (...args) { - super(...args) - Object.defineProperties(this, { - kty: { - value: 'oct', - enumerable: true - }, - length: { - value: this[KEYOBJECT] ? this[KEYOBJECT].symmetricKeySize * 8 : undefined - }, - k: { - enumerable: false, - get () { - if (this[KEYOBJECT]) { - Object.defineProperty(this, 'k', { - value: base64url.encodeBuffer(this[KEYOBJECT].export()), - configurable: false - }) - } else { - Object.defineProperty(this, 'k', { - value: undefined, - configurable: false - }) - } - - return this.k - }, - configurable: true - } - }) - } - - static get [PUBLIC_MEMBERS] () { - return OCT_PUBLIC - } +/* + * Copyright The OpenTelemetry 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 + * + * https://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.DiagLogLevel = void 0; +/** + * Defines the available internal logging levels for the diagnostic logger, the numeric values + * of the levels are defined to match the original values from the initial LogLevel to avoid + * compatibility/migration issues for any implementation that assume the numeric ordering. + */ +var DiagLogLevel; +(function (DiagLogLevel) { + /** Diagnostic Logging level setting to disable all logging (except and forced logs) */ + DiagLogLevel[DiagLogLevel["NONE"] = 0] = "NONE"; + /** Identifies an error scenario */ + DiagLogLevel[DiagLogLevel["ERROR"] = 30] = "ERROR"; + /** Identifies a warning scenario */ + DiagLogLevel[DiagLogLevel["WARN"] = 50] = "WARN"; + /** General informational log message */ + DiagLogLevel[DiagLogLevel["INFO"] = 60] = "INFO"; + /** General debug log message */ + DiagLogLevel[DiagLogLevel["DEBUG"] = 70] = "DEBUG"; + /** + * Detailed trace level logging should only be used for development, should only be set + * in a development environment. + */ + DiagLogLevel[DiagLogLevel["VERBOSE"] = 80] = "VERBOSE"; + /** Used to set the logging level to include all logging */ + DiagLogLevel[DiagLogLevel["ALL"] = 9999] = "ALL"; +})(DiagLogLevel = exports.DiagLogLevel || (exports.DiagLogLevel = {})); +//# sourceMappingURL=types.js.map - static get [PRIVATE_MEMBERS] () { - return OCT_PRIVATE - } +/***/ }), - // https://tc39.github.io/ecma262/#sec-ordinaryownpropertykeys no need for any special - // JSON.stringify handling in V8 - [THUMBPRINT_MATERIAL] () { - if (!this[KEYOBJECT]) { - throw new TypeError('reference "oct" keys without "k" cannot have their thumbprint calculated') - } - return { k: this.k, kty: 'oct' } - } +/***/ 65163: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - [KEY_MANAGEMENT_ENCRYPT] () { - return new Set([ - ...this.algorithms('wrapKey'), - ...this.algorithms('deriveKey') - ]) - } +"use strict"; - [KEY_MANAGEMENT_DECRYPT] () { - return this[KEY_MANAGEMENT_ENCRYPT]() - } +/* + * Copyright The OpenTelemetry 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 + * + * https://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.trace = exports.propagation = exports.metrics = exports.diag = exports.context = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.createTraceState = exports.TraceFlags = exports.SpanStatusCode = exports.SpanKind = exports.SamplingDecision = exports.ProxyTracerProvider = exports.ProxyTracer = exports.defaultTextMapSetter = exports.defaultTextMapGetter = exports.ValueType = exports.createNoopMeter = exports.DiagLogLevel = exports.DiagConsoleLogger = exports.ROOT_CONTEXT = exports.createContextKey = exports.baggageEntryMetadataFromString = void 0; +var utils_1 = __nccwpck_require__(28136); +Object.defineProperty(exports, "baggageEntryMetadataFromString", ({ enumerable: true, get: function () { return utils_1.baggageEntryMetadataFromString; } })); +// Context APIs +var context_1 = __nccwpck_require__(78242); +Object.defineProperty(exports, "createContextKey", ({ enumerable: true, get: function () { return context_1.createContextKey; } })); +Object.defineProperty(exports, "ROOT_CONTEXT", ({ enumerable: true, get: function () { return context_1.ROOT_CONTEXT; } })); +// Diag APIs +var consoleLogger_1 = __nccwpck_require__(3041); +Object.defineProperty(exports, "DiagConsoleLogger", ({ enumerable: true, get: function () { return consoleLogger_1.DiagConsoleLogger; } })); +var types_1 = __nccwpck_require__(78077); +Object.defineProperty(exports, "DiagLogLevel", ({ enumerable: true, get: function () { return types_1.DiagLogLevel; } })); +// Metrics APIs +var NoopMeter_1 = __nccwpck_require__(4837); +Object.defineProperty(exports, "createNoopMeter", ({ enumerable: true, get: function () { return NoopMeter_1.createNoopMeter; } })); +var Metric_1 = __nccwpck_require__(89999); +Object.defineProperty(exports, "ValueType", ({ enumerable: true, get: function () { return Metric_1.ValueType; } })); +// Propagation APIs +var TextMapPropagator_1 = __nccwpck_require__(80865); +Object.defineProperty(exports, "defaultTextMapGetter", ({ enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapGetter; } })); +Object.defineProperty(exports, "defaultTextMapSetter", ({ enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapSetter; } })); +var ProxyTracer_1 = __nccwpck_require__(43503); +Object.defineProperty(exports, "ProxyTracer", ({ enumerable: true, get: function () { return ProxyTracer_1.ProxyTracer; } })); +var ProxyTracerProvider_1 = __nccwpck_require__(2285); +Object.defineProperty(exports, "ProxyTracerProvider", ({ enumerable: true, get: function () { return ProxyTracerProvider_1.ProxyTracerProvider; } })); +var SamplingResult_1 = __nccwpck_require__(33209); +Object.defineProperty(exports, "SamplingDecision", ({ enumerable: true, get: function () { return SamplingResult_1.SamplingDecision; } })); +var span_kind_1 = __nccwpck_require__(31424); +Object.defineProperty(exports, "SpanKind", ({ enumerable: true, get: function () { return span_kind_1.SpanKind; } })); +var status_1 = __nccwpck_require__(48845); +Object.defineProperty(exports, "SpanStatusCode", ({ enumerable: true, get: function () { return status_1.SpanStatusCode; } })); +var trace_flags_1 = __nccwpck_require__(26905); +Object.defineProperty(exports, "TraceFlags", ({ enumerable: true, get: function () { return trace_flags_1.TraceFlags; } })); +var utils_2 = __nccwpck_require__(32615); +Object.defineProperty(exports, "createTraceState", ({ enumerable: true, get: function () { return utils_2.createTraceState; } })); +var spancontext_utils_1 = __nccwpck_require__(49745); +Object.defineProperty(exports, "isSpanContextValid", ({ enumerable: true, get: function () { return spancontext_utils_1.isSpanContextValid; } })); +Object.defineProperty(exports, "isValidTraceId", ({ enumerable: true, get: function () { return spancontext_utils_1.isValidTraceId; } })); +Object.defineProperty(exports, "isValidSpanId", ({ enumerable: true, get: function () { return spancontext_utils_1.isValidSpanId; } })); +var invalid_span_constants_1 = __nccwpck_require__(91760); +Object.defineProperty(exports, "INVALID_SPANID", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPANID; } })); +Object.defineProperty(exports, "INVALID_TRACEID", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_TRACEID; } })); +Object.defineProperty(exports, "INVALID_SPAN_CONTEXT", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPAN_CONTEXT; } })); +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +const context_api_1 = __nccwpck_require__(7393); +Object.defineProperty(exports, "context", ({ enumerable: true, get: function () { return context_api_1.context; } })); +const diag_api_1 = __nccwpck_require__(39721); +Object.defineProperty(exports, "diag", ({ enumerable: true, get: function () { return diag_api_1.diag; } })); +const metrics_api_1 = __nccwpck_require__(72601); +Object.defineProperty(exports, "metrics", ({ enumerable: true, get: function () { return metrics_api_1.metrics; } })); +const propagation_api_1 = __nccwpck_require__(17591); +Object.defineProperty(exports, "propagation", ({ enumerable: true, get: function () { return propagation_api_1.propagation; } })); +const trace_api_1 = __nccwpck_require__(98989); +Object.defineProperty(exports, "trace", ({ enumerable: true, get: function () { return trace_api_1.trace; } })); +// Default export. +exports["default"] = { + context: context_api_1.context, + diag: diag_api_1.diag, + metrics: metrics_api_1.metrics, + propagation: propagation_api_1.propagation, + trace: trace_api_1.trace, +}; +//# sourceMappingURL=index.js.map - algorithms (...args) { - if (!this[KEYOBJECT]) { - return new Set() - } +/***/ }), - return Key.prototype.algorithms.call(this, ...args) - } +/***/ 85135: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - static async generate (...args) { - return this.generateSync(...args) - } +"use strict"; - static generateSync (len = 256, privat = true) { - if (!privat) { - throw new TypeError('"oct" keys cannot be generated as public') +/* + * Copyright The OpenTelemetry 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 + * + * https://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.unregisterGlobal = exports.getGlobal = exports.registerGlobal = void 0; +const platform_1 = __nccwpck_require__(99957); +const version_1 = __nccwpck_require__(98996); +const semver_1 = __nccwpck_require__(81522); +const major = version_1.VERSION.split('.')[0]; +const GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`); +const _global = platform_1._globalThis; +function registerGlobal(type, instance, diag, allowOverride = false) { + var _a; + const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { + version: version_1.VERSION, + }); + if (!allowOverride && api[type]) { + // already registered an API of this type + const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`); + diag.error(err.stack || err.message); + return false; } - if (!Number.isSafeInteger(len) || !len || len % 8 !== 0) { - throw new TypeError('invalid bit length') + if (api.version !== version_1.VERSION) { + // All registered APIs must be of the same version exactly + const err = new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${version_1.VERSION}`); + diag.error(err.stack || err.message); + return false; } - - return createSecretKey(randomBytes(len / 8)) - } + api[type] = instance; + diag.debug(`@opentelemetry/api: Registered a global for ${type} v${version_1.VERSION}.`); + return true; } - -module.exports = OctKey - - -/***/ }), - -/***/ 27742: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { generateKeyPairSync, generateKeyPair: async } = __nccwpck_require__(6113) -const { promisify } = __nccwpck_require__(73837) - -const { - THUMBPRINT_MATERIAL, JWK_MEMBERS, PUBLIC_MEMBERS, - PRIVATE_MEMBERS, KEY_MANAGEMENT_DECRYPT, KEY_MANAGEMENT_ENCRYPT -} = __nccwpck_require__(62928) -const { OKP_CURVES } = __nccwpck_require__(47359) -const { edDSASupported } = __nccwpck_require__(57494) -const errors = __nccwpck_require__(35132) - -const Key = __nccwpck_require__(99795) - -const generateKeyPair = promisify(async) - -const OKP_PUBLIC = new Set(['crv', 'x']) -Object.freeze(OKP_PUBLIC) -const OKP_PRIVATE = new Set([...OKP_PUBLIC, 'd']) -Object.freeze(OKP_PRIVATE) - -// Octet string key pairs Key Type -class OKPKey extends Key { - constructor (...args) { - super(...args) - this[JWK_MEMBERS]() - Object.defineProperty(this, 'kty', { value: 'OKP', enumerable: true }) - if (!OKP_CURVES.has(this.crv)) { - throw new errors.JOSENotSupported('unsupported OKP key curve') +exports.registerGlobal = registerGlobal; +function getGlobal(type) { + var _a, _b; + const globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version; + if (!globalVersion || !(0, semver_1.isCompatible)(globalVersion)) { + return; } - } - - static get [PUBLIC_MEMBERS] () { - return OKP_PUBLIC - } - - static get [PRIVATE_MEMBERS] () { - return OKP_PRIVATE - } + return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type]; +} +exports.getGlobal = getGlobal; +function unregisterGlobal(type, diag) { + diag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${version_1.VERSION}.`); + const api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; + if (api) { + delete api[type]; + } +} +exports.unregisterGlobal = unregisterGlobal; +//# sourceMappingURL=global-utils.js.map - // https://tc39.github.io/ecma262/#sec-ordinaryownpropertykeys no need for any special - // JSON.stringify handling in V8 - [THUMBPRINT_MATERIAL] () { - return { crv: this.crv, kty: 'OKP', x: this.x } - } +/***/ }), - [KEY_MANAGEMENT_ENCRYPT] () { - return this.algorithms('deriveKey') - } +/***/ 81522: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - [KEY_MANAGEMENT_DECRYPT] () { - if (this.public) { - return new Set() - } - return this.algorithms('deriveKey') - } +"use strict"; - static async generate (crv = 'Ed25519', privat = true) { - if (!edDSASupported) { - throw new errors.JOSENotSupported('OKP keys are not supported in your Node.js runtime version') +/* + * Copyright The OpenTelemetry 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 + * + * https://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.isCompatible = exports._makeCompatibilityCheck = void 0; +const version_1 = __nccwpck_require__(98996); +const re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; +/** + * Create a function to test an API version to see if it is compatible with the provided ownVersion. + * + * The returned function has the following semantics: + * - Exact match is always compatible + * - Major versions must match exactly + * - 1.x package cannot use global 2.x package + * - 2.x package cannot use global 1.x package + * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API + * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects + * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3 + * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor + * - Patch and build tag differences are not considered at this time + * + * @param ownVersion version which should be checked against + */ +function _makeCompatibilityCheck(ownVersion) { + const acceptedVersions = new Set([ownVersion]); + const rejectedVersions = new Set(); + const myVersionMatch = ownVersion.match(re); + if (!myVersionMatch) { + // we cannot guarantee compatibility so we always return noop + return () => false; } - - if (!OKP_CURVES.has(crv)) { - throw new errors.JOSENotSupported(`unsupported OKP key curve: ${crv}`) + const ownVersionParsed = { + major: +myVersionMatch[1], + minor: +myVersionMatch[2], + patch: +myVersionMatch[3], + prerelease: myVersionMatch[4], + }; + // if ownVersion has a prerelease tag, versions must match exactly + if (ownVersionParsed.prerelease != null) { + return function isExactmatch(globalVersion) { + return globalVersion === ownVersion; + }; } - - const { privateKey, publicKey } = await generateKeyPair(crv.toLowerCase()) - - return privat ? privateKey : publicKey - } - - static generateSync (crv = 'Ed25519', privat = true) { - if (!edDSASupported) { - throw new errors.JOSENotSupported('OKP keys are not supported in your Node.js runtime version') + function _reject(v) { + rejectedVersions.add(v); + return false; } - - if (!OKP_CURVES.has(crv)) { - throw new errors.JOSENotSupported(`unsupported OKP key curve: ${crv}`) + function _accept(v) { + acceptedVersions.add(v); + return true; } - - const { privateKey, publicKey } = generateKeyPairSync(crv.toLowerCase()) - - return privat ? privateKey : publicKey - } + return function isCompatible(globalVersion) { + if (acceptedVersions.has(globalVersion)) { + return true; + } + if (rejectedVersions.has(globalVersion)) { + return false; + } + const globalVersionMatch = globalVersion.match(re); + if (!globalVersionMatch) { + // cannot parse other version + // we cannot guarantee compatibility so we always noop + return _reject(globalVersion); + } + const globalVersionParsed = { + major: +globalVersionMatch[1], + minor: +globalVersionMatch[2], + patch: +globalVersionMatch[3], + prerelease: globalVersionMatch[4], + }; + // if globalVersion has a prerelease tag, versions must match exactly + if (globalVersionParsed.prerelease != null) { + return _reject(globalVersion); + } + // major versions must match + if (ownVersionParsed.major !== globalVersionParsed.major) { + return _reject(globalVersion); + } + if (ownVersionParsed.major === 0) { + if (ownVersionParsed.minor === globalVersionParsed.minor && + ownVersionParsed.patch <= globalVersionParsed.patch) { + return _accept(globalVersion); + } + return _reject(globalVersion); + } + if (ownVersionParsed.minor <= globalVersionParsed.minor) { + return _accept(globalVersion); + } + return _reject(globalVersion); + }; } - -module.exports = OKPKey - +exports._makeCompatibilityCheck = _makeCompatibilityCheck; +/** + * Test an API version to see if it is compatible with this API. + * + * - Exact match is always compatible + * - Major versions must match exactly + * - 1.x package cannot use global 2.x package + * - 2.x package cannot use global 1.x package + * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API + * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects + * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3 + * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor + * - Patch and build tag differences are not considered at this time + * + * @param version version of the API requesting an instance of the global API + */ +exports.isCompatible = _makeCompatibilityCheck(version_1.VERSION); +//# sourceMappingURL=semver.js.map /***/ }), -/***/ 52679: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { generateKeyPairSync, generateKeyPair: async } = __nccwpck_require__(6113) -const { promisify } = __nccwpck_require__(73837) - -const { - THUMBPRINT_MATERIAL, JWK_MEMBERS, PUBLIC_MEMBERS, - PRIVATE_MEMBERS, KEY_MANAGEMENT_DECRYPT, KEY_MANAGEMENT_ENCRYPT -} = __nccwpck_require__(62928) -const { keyObjectSupported } = __nccwpck_require__(57494) -const { createPublicKey, createPrivateKey } = __nccwpck_require__(31032) - -const Key = __nccwpck_require__(99795) +/***/ 72601: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const generateKeyPair = promisify(async) +"use strict"; -const RSA_PUBLIC = new Set(['e', 'n']) -Object.freeze(RSA_PUBLIC) -const RSA_PRIVATE = new Set([...RSA_PUBLIC, 'd', 'p', 'q', 'dp', 'dq', 'qi']) -Object.freeze(RSA_PRIVATE) +/* + * Copyright The OpenTelemetry 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 + * + * https://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.metrics = void 0; +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +const metrics_1 = __nccwpck_require__(17696); +/** Entrypoint for metrics API */ +exports.metrics = metrics_1.MetricsAPI.getInstance(); +//# sourceMappingURL=metrics-api.js.map -// RSA Key Type -class RSAKey extends Key { - constructor (...args) { - super(...args) - this[JWK_MEMBERS]() - Object.defineProperties(this, { - kty: { - value: 'RSA', - enumerable: true - }, - length: { - get () { - Object.defineProperty(this, 'length', { - value: Buffer.byteLength(this.n, 'base64') * 8, - configurable: false - }) +/***/ }), - return this.length - }, - configurable: true - } - }) - } +/***/ 89999: +/***/ ((__unused_webpack_module, exports) => { - static get [PUBLIC_MEMBERS] () { - return RSA_PUBLIC - } +"use strict"; - static get [PRIVATE_MEMBERS] () { - return RSA_PRIVATE - } +/* + * Copyright The OpenTelemetry 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 + * + * https://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.ValueType = void 0; +/** The Type of value. It describes how the data is reported. */ +var ValueType; +(function (ValueType) { + ValueType[ValueType["INT"] = 0] = "INT"; + ValueType[ValueType["DOUBLE"] = 1] = "DOUBLE"; +})(ValueType = exports.ValueType || (exports.ValueType = {})); +//# sourceMappingURL=Metric.js.map - // https://tc39.github.io/ecma262/#sec-ordinaryownpropertykeys no need for any special - // JSON.stringify handling in V8 - [THUMBPRINT_MATERIAL] () { - return { e: this.e, kty: 'RSA', n: this.n } - } +/***/ }), - [KEY_MANAGEMENT_ENCRYPT] () { - return this.algorithms('wrapKey') - } +/***/ 4837: +/***/ ((__unused_webpack_module, exports) => { - [KEY_MANAGEMENT_DECRYPT] () { - return this.algorithms('unwrapKey') - } +"use strict"; - static async generate (len = 2048, privat = true) { - if (!Number.isSafeInteger(len) || len < 512 || len % 8 !== 0 || (('electron' in process.versions) && len % 128 !== 0)) { - throw new TypeError('invalid bit length') +/* + * Copyright The OpenTelemetry 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 + * + * https://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.createNoopMeter = exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = exports.NOOP_OBSERVABLE_GAUGE_METRIC = exports.NOOP_OBSERVABLE_COUNTER_METRIC = exports.NOOP_UP_DOWN_COUNTER_METRIC = exports.NOOP_HISTOGRAM_METRIC = exports.NOOP_COUNTER_METRIC = exports.NOOP_METER = exports.NoopObservableUpDownCounterMetric = exports.NoopObservableGaugeMetric = exports.NoopObservableCounterMetric = exports.NoopObservableMetric = exports.NoopHistogramMetric = exports.NoopUpDownCounterMetric = exports.NoopCounterMetric = exports.NoopMetric = exports.NoopMeter = void 0; +/** + * NoopMeter is a noop implementation of the {@link Meter} interface. It reuses + * constant NoopMetrics for all of its methods. + */ +class NoopMeter { + constructor() { } + /** + * @see {@link Meter.createHistogram} + */ + createHistogram(_name, _options) { + return exports.NOOP_HISTOGRAM_METRIC; } - - let privateKey, publicKey - - if (keyObjectSupported) { - ({ privateKey, publicKey } = await generateKeyPair('rsa', { modulusLength: len })) - return privat ? privateKey : publicKey + /** + * @see {@link Meter.createCounter} + */ + createCounter(_name, _options) { + return exports.NOOP_COUNTER_METRIC; } - - ({ privateKey, publicKey } = await generateKeyPair('rsa', { - modulusLength: len, - publicKeyEncoding: { type: 'spki', format: 'pem' }, - privateKeyEncoding: { type: 'pkcs8', format: 'pem' } - })) - - if (privat) { - return createPrivateKey(privateKey) - } else { - return createPublicKey(publicKey) + /** + * @see {@link Meter.createUpDownCounter} + */ + createUpDownCounter(_name, _options) { + return exports.NOOP_UP_DOWN_COUNTER_METRIC; } - } - - static generateSync (len = 2048, privat = true) { - if (!Number.isSafeInteger(len) || len < 512 || len % 8 !== 0 || (('electron' in process.versions) && len % 128 !== 0)) { - throw new TypeError('invalid bit length') + /** + * @see {@link Meter.createObservableGauge} + */ + createObservableGauge(_name, _options) { + return exports.NOOP_OBSERVABLE_GAUGE_METRIC; } - - let privateKey, publicKey - - if (keyObjectSupported) { - ({ privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: len })) - return privat ? privateKey : publicKey + /** + * @see {@link Meter.createObservableCounter} + */ + createObservableCounter(_name, _options) { + return exports.NOOP_OBSERVABLE_COUNTER_METRIC; } - - ({ privateKey, publicKey } = generateKeyPairSync('rsa', { - modulusLength: len, - publicKeyEncoding: { type: 'spki', format: 'pem' }, - privateKeyEncoding: { type: 'pkcs8', format: 'pem' } - })) - - if (privat) { - return createPrivateKey(privateKey) - } else { - return createPublicKey(publicKey) + /** + * @see {@link Meter.createObservableUpDownCounter} + */ + createObservableUpDownCounter(_name, _options) { + return exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC; } - } + /** + * @see {@link Meter.addBatchObservableCallback} + */ + addBatchObservableCallback(_callback, _observables) { } + /** + * @see {@link Meter.removeBatchObservableCallback} + */ + removeBatchObservableCallback(_callback) { } } - -module.exports = RSAKey - +exports.NoopMeter = NoopMeter; +class NoopMetric { +} +exports.NoopMetric = NoopMetric; +class NoopCounterMetric extends NoopMetric { + add(_value, _attributes) { } +} +exports.NoopCounterMetric = NoopCounterMetric; +class NoopUpDownCounterMetric extends NoopMetric { + add(_value, _attributes) { } +} +exports.NoopUpDownCounterMetric = NoopUpDownCounterMetric; +class NoopHistogramMetric extends NoopMetric { + record(_value, _attributes) { } +} +exports.NoopHistogramMetric = NoopHistogramMetric; +class NoopObservableMetric { + addCallback(_callback) { } + removeCallback(_callback) { } +} +exports.NoopObservableMetric = NoopObservableMetric; +class NoopObservableCounterMetric extends NoopObservableMetric { +} +exports.NoopObservableCounterMetric = NoopObservableCounterMetric; +class NoopObservableGaugeMetric extends NoopObservableMetric { +} +exports.NoopObservableGaugeMetric = NoopObservableGaugeMetric; +class NoopObservableUpDownCounterMetric extends NoopObservableMetric { +} +exports.NoopObservableUpDownCounterMetric = NoopObservableUpDownCounterMetric; +exports.NOOP_METER = new NoopMeter(); +// Synchronous instruments +exports.NOOP_COUNTER_METRIC = new NoopCounterMetric(); +exports.NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric(); +exports.NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric(); +// Asynchronous instruments +exports.NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric(); +exports.NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric(); +exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric(); +/** + * Create a no-op Meter + */ +function createNoopMeter() { + return exports.NOOP_METER; +} +exports.createNoopMeter = createNoopMeter; +//# sourceMappingURL=NoopMeter.js.map /***/ }), -/***/ 89020: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 72647: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const { createHash } = __nccwpck_require__(6113) +"use strict"; -const base64url = __nccwpck_require__(93312) +/* + * Copyright The OpenTelemetry 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 + * + * https://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.NOOP_METER_PROVIDER = exports.NoopMeterProvider = void 0; +const NoopMeter_1 = __nccwpck_require__(4837); +/** + * An implementation of the {@link MeterProvider} which returns an impotent Meter + * for all calls to `getMeter` + */ +class NoopMeterProvider { + getMeter(_name, _version, _options) { + return NoopMeter_1.NOOP_METER; + } +} +exports.NoopMeterProvider = NoopMeterProvider; +exports.NOOP_METER_PROVIDER = new NoopMeterProvider(); +//# sourceMappingURL=NoopMeterProvider.js.map -const x5t = (hash, cert) => base64url.encodeBuffer(createHash(hash).update(Buffer.from(cert, 'base64')).digest()) +/***/ }), -module.exports.kid = components => base64url.encodeBuffer(createHash('sha256').update(JSON.stringify(components)).digest()) -module.exports.x5t = x5t.bind(undefined, 'sha1') -module.exports["x5t#S256"] = x5t.bind(undefined, 'sha256') +/***/ 99957: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +"use strict"; -/***/ }), +/* + * Copyright The OpenTelemetry 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 + * + * https://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 __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (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 })); +__exportStar(__nccwpck_require__(87200), exports); +//# sourceMappingURL=index.js.map -/***/ 27397: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ }), -const KeyStore = __nccwpck_require__(44201) +/***/ 89406: +/***/ ((__unused_webpack_module, exports) => { -module.exports = KeyStore +"use strict"; +/* + * Copyright The OpenTelemetry 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 + * + * https://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._globalThis = void 0; +/** only globals that common to node and browsers are allowed */ +// eslint-disable-next-line node/no-unsupported-features/es-builtins +exports._globalThis = typeof globalThis === 'object' ? globalThis : global; +//# sourceMappingURL=globalThis.js.map /***/ }), -/***/ 44201: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 87200: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -const { inspect } = __nccwpck_require__(73837) +"use strict"; -const isObject = __nccwpck_require__(50243) -const { generate, generateSync } = __nccwpck_require__(87042) -const { USES_MAPPING } = __nccwpck_require__(62928) -const { isKey, asKey: importKey } = __nccwpck_require__(2297) +/* + * Copyright The OpenTelemetry 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 + * + * https://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 __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (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 })); +__exportStar(__nccwpck_require__(89406), exports); +//# sourceMappingURL=index.js.map -const keyscore = (key, { alg, use, ops }) => { - let score = 0 +/***/ }), - if (alg && key.alg) { - score++ - } +/***/ 17591: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (use && key.use) { - score++ - } +"use strict"; - if (ops && key.key_ops) { - score++ - } +/* + * Copyright The OpenTelemetry 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 + * + * https://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.propagation = void 0; +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +const propagation_1 = __nccwpck_require__(89909); +/** Entrypoint for propagation API */ +exports.propagation = propagation_1.PropagationAPI.getInstance(); +//# sourceMappingURL=propagation-api.js.map - return score -} +/***/ }), -class KeyStore { - constructor (...keys) { - while (keys.some(Array.isArray)) { - keys = keys.flat - ? keys.flat() - : keys.reduce((acc, val) => { - if (Array.isArray(val)) { - return [...acc, ...val] - } +/***/ 72368: +/***/ ((__unused_webpack_module, exports) => { - acc.push(val) - return acc - }, []) +"use strict"; + +/* + * Copyright The OpenTelemetry 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 + * + * https://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.NoopTextMapPropagator = void 0; +/** + * No-op implementations of {@link TextMapPropagator}. + */ +class NoopTextMapPropagator { + /** Noop inject function does nothing */ + inject(_context, _carrier) { } + /** Noop extract function does nothing and returns the input context */ + extract(context, _carrier) { + return context; } - if (keys.some(k => !isKey(k) || !k.kty)) { - throw new TypeError('all keys must be instances of a key instantiated by JWK.asKey') + fields() { + return []; } +} +exports.NoopTextMapPropagator = NoopTextMapPropagator; +//# sourceMappingURL=NoopTextMapPropagator.js.map - this._keys = new Set(keys) - } +/***/ }), - all ({ alg, kid, thumbprint, use, kty, key_ops: ops, x5t, 'x5t#S256': x5t256, crv } = {}) { - if (ops !== undefined && (!Array.isArray(ops) || !ops.length || ops.some(x => typeof x !== 'string'))) { - throw new TypeError('`key_ops` must be a non-empty array of strings') - } +/***/ 80865: +/***/ ((__unused_webpack_module, exports) => { - const search = { alg, use, ops } - return [...this._keys] - .filter((key) => { - let candidate = true +"use strict"; - if (candidate && kid !== undefined && key.kid !== kid) { - candidate = false +/* + * Copyright The OpenTelemetry 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 + * + * https://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.defaultTextMapSetter = exports.defaultTextMapGetter = void 0; +exports.defaultTextMapGetter = { + get(carrier, key) { + if (carrier == null) { + return undefined; } - - if (candidate && thumbprint !== undefined && key.thumbprint !== thumbprint) { - candidate = false + return carrier[key]; + }, + keys(carrier) { + if (carrier == null) { + return []; } - - if (candidate && x5t !== undefined && key.x5t !== x5t) { - candidate = false + return Object.keys(carrier); + }, +}; +exports.defaultTextMapSetter = { + set(carrier, key, value) { + if (carrier == null) { + return; } + carrier[key] = value; + }, +}; +//# sourceMappingURL=TextMapPropagator.js.map - if (candidate && x5t256 !== undefined && key['x5t#S256'] !== x5t256) { - candidate = false - } +/***/ }), - if (candidate && kty !== undefined && key.kty !== kty) { - candidate = false - } +/***/ 98989: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (candidate && crv !== undefined && (key.crv !== crv)) { - candidate = false - } +"use strict"; - if (alg !== undefined && !key.algorithms().has(alg)) { - candidate = false - } - - if (candidate && use !== undefined && (key.use !== undefined && key.use !== use)) { - candidate = false - } +/* + * Copyright The OpenTelemetry 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 + * + * https://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.trace = void 0; +// Split module-level variable definition into separate files to allow +// tree-shaking on each api instance. +const trace_1 = __nccwpck_require__(81539); +/** Entrypoint for trace API */ +exports.trace = trace_1.TraceAPI.getInstance(); +//# sourceMappingURL=trace-api.js.map - // TODO: - if (candidate && ops !== undefined && (key.key_ops !== undefined || key.use !== undefined)) { - let keyOps - if (key.key_ops) { - keyOps = new Set(key.key_ops) - } else { - keyOps = USES_MAPPING[key.use] - } - if (ops.some(x => !keyOps.has(x))) { - candidate = false - } - } +/***/ }), - return candidate - }) - .sort((first, second) => keyscore(second, search) - keyscore(first, search)) - } +/***/ 81462: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - get (...args) { - return this.all(...args)[0] - } +"use strict"; - add (key) { - if (!isKey(key) || !key.kty) { - throw new TypeError('key must be an instance of a key instantiated by JWK.asKey') +/* + * Copyright The OpenTelemetry 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 + * + * https://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.NonRecordingSpan = void 0; +const invalid_span_constants_1 = __nccwpck_require__(91760); +/** + * The NonRecordingSpan is the default {@link Span} that is used when no Span + * implementation is available. All operations are no-op including context + * propagation. + */ +class NonRecordingSpan { + constructor(_spanContext = invalid_span_constants_1.INVALID_SPAN_CONTEXT) { + this._spanContext = _spanContext; } - - this._keys.add(key) - } - - remove (key) { - if (!isKey(key)) { - throw new TypeError('key must be an instance of a key instantiated by JWK.asKey') + // Returns a SpanContext. + spanContext() { + return this._spanContext; } - - this._keys.delete(key) - } - - toJWKS (priv = false) { - return { - keys: [...this._keys.values()].map( - key => key.toJWK(priv && (key.private || (key.secret && key.k))) - ) + // By default does nothing + setAttribute(_key, _value) { + return this; } - } - - async generate (...args) { - this._keys.add(await generate(...args)) - } + // By default does nothing + setAttributes(_attributes) { + return this; + } + // By default does nothing + addEvent(_name, _attributes) { + return this; + } + // By default does nothing + setStatus(_status) { + return this; + } + // By default does nothing + updateName(_name) { + return this; + } + // By default does nothing + end(_endTime) { } + // isRecording always returns false for NonRecordingSpan. + isRecording() { + return false; + } + // By default does nothing + recordException(_exception, _time) { } +} +exports.NonRecordingSpan = NonRecordingSpan; +//# sourceMappingURL=NonRecordingSpan.js.map - generateSync (...args) { - this._keys.add(generateSync(...args)) - } +/***/ }), - get size () { - return this._keys.size - } +/***/ 17606: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /* c8 ignore next 8 */ - [inspect.custom] () { - return `${this.constructor.name} ${inspect(this.toJWKS(false), { - depth: Infinity, - colors: process.stdout.isTTY, - compact: false, - sorted: true - })}` - } +"use strict"; - * [Symbol.iterator] () { - for (const key of this._keys) { - yield key +/* + * Copyright The OpenTelemetry 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 + * + * https://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.NoopTracer = void 0; +const context_1 = __nccwpck_require__(57171); +const context_utils_1 = __nccwpck_require__(23326); +const NonRecordingSpan_1 = __nccwpck_require__(81462); +const spancontext_utils_1 = __nccwpck_require__(49745); +const contextApi = context_1.ContextAPI.getInstance(); +/** + * No-op implementations of {@link Tracer}. + */ +class NoopTracer { + // startSpan starts a noop span. + startSpan(name, options, context = contextApi.active()) { + const root = Boolean(options === null || options === void 0 ? void 0 : options.root); + if (root) { + return new NonRecordingSpan_1.NonRecordingSpan(); + } + const parentFromContext = context && (0, context_utils_1.getSpanContext)(context); + if (isSpanContext(parentFromContext) && + (0, spancontext_utils_1.isSpanContextValid)(parentFromContext)) { + return new NonRecordingSpan_1.NonRecordingSpan(parentFromContext); + } + else { + return new NonRecordingSpan_1.NonRecordingSpan(); + } } - } -} - -function asKeyStore (jwks, { ignoreErrors = false, calculateMissingRSAPrimes = false } = {}) { - if (!isObject(jwks) || !Array.isArray(jwks.keys) || jwks.keys.some(k => !isObject(k) || !('kty' in k))) { - throw new TypeError('jwks must be a JSON Web Key Set formatted object') - } - - const keys = jwks.keys.map((jwk) => { - try { - return importKey(jwk, { calculateMissingRSAPrimes }) - } catch (err) { - if (!ignoreErrors) { - throw err - } - return undefined + startActiveSpan(name, arg2, arg3, arg4) { + let opts; + let ctx; + let fn; + if (arguments.length < 2) { + return; + } + else if (arguments.length === 2) { + fn = arg2; + } + else if (arguments.length === 3) { + opts = arg2; + fn = arg3; + } + else { + opts = arg2; + ctx = arg3; + fn = arg4; + } + const parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active(); + const span = this.startSpan(name, opts, parentContext); + const contextWithSpanSet = (0, context_utils_1.setSpan)(parentContext, span); + return contextApi.with(contextWithSpanSet, fn, undefined, span); } - }).filter(Boolean) - - return new KeyStore(...keys) } - -module.exports = { KeyStore, asKeyStore } - +exports.NoopTracer = NoopTracer; +function isSpanContext(spanContext) { + return (typeof spanContext === 'object' && + typeof spanContext['spanId'] === 'string' && + typeof spanContext['traceId'] === 'string' && + typeof spanContext['traceFlags'] === 'number'); +} +//# sourceMappingURL=NoopTracer.js.map /***/ }), -/***/ 49830: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 23259: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const Sign = __nccwpck_require__(81194) -const { verify } = __nccwpck_require__(45057) +"use strict"; -const single = (serialization, payload, key, protectedHeader, unprotectedHeader) => { - return new Sign(payload) - .recipient(key, protectedHeader, unprotectedHeader) - .sign(serialization) +/* + * Copyright The OpenTelemetry 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 + * + * https://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.NoopTracerProvider = void 0; +const NoopTracer_1 = __nccwpck_require__(17606); +/** + * An implementation of the {@link TracerProvider} which returns an impotent + * Tracer for all calls to `getTracer`. + * + * All operations are no-op. + */ +class NoopTracerProvider { + getTracer(_name, _version, _options) { + return new NoopTracer_1.NoopTracer(); + } } - -module.exports.Sign = Sign -module.exports.sign = single.bind(undefined, 'compact') -module.exports.sign.flattened = single.bind(undefined, 'flattened') -module.exports.sign.general = single.bind(undefined, 'general') - -module.exports.verify = verify - +exports.NoopTracerProvider = NoopTracerProvider; +//# sourceMappingURL=NoopTracerProvider.js.map /***/ }), -/***/ 21708: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const isObject = __nccwpck_require__(50243) -let validateCrit = __nccwpck_require__(85822) -const { JWSInvalid } = __nccwpck_require__(35132) +/***/ 43503: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -validateCrit = validateCrit.bind(undefined, JWSInvalid) +"use strict"; -const compactSerializer = (payload, [recipient]) => { - return `${recipient.protected}.${payload}.${recipient.signature}` -} -compactSerializer.validate = (jws, { 0: { unprotectedHeader, protectedHeader }, length }) => { - if (length !== 1 || unprotectedHeader) { - throw new JWSInvalid('JWS Compact Serialization doesn\'t support multiple recipients or JWS unprotected headers') - } - validateCrit(protectedHeader, unprotectedHeader, protectedHeader ? protectedHeader.crit : undefined) +/* + * Copyright The OpenTelemetry 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 + * + * https://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.ProxyTracer = void 0; +const NoopTracer_1 = __nccwpck_require__(17606); +const NOOP_TRACER = new NoopTracer_1.NoopTracer(); +/** + * Proxy tracer provided by the proxy tracer provider + */ +class ProxyTracer { + constructor(_provider, name, version, options) { + this._provider = _provider; + this.name = name; + this.version = version; + this.options = options; + } + startSpan(name, options, context) { + return this._getTracer().startSpan(name, options, context); + } + startActiveSpan(_name, _options, _context, _fn) { + const tracer = this._getTracer(); + return Reflect.apply(tracer.startActiveSpan, tracer, arguments); + } + /** + * Try to get a tracer from the proxy tracer provider. + * If the proxy tracer provider has no delegate, return a noop tracer. + */ + _getTracer() { + if (this._delegate) { + return this._delegate; + } + const tracer = this._provider.getDelegateTracer(this.name, this.version, this.options); + if (!tracer) { + return NOOP_TRACER; + } + this._delegate = tracer; + return this._delegate; + } } +exports.ProxyTracer = ProxyTracer; +//# sourceMappingURL=ProxyTracer.js.map -const flattenedSerializer = (payload, [recipient]) => { - const { header, signature, protected: prot } = recipient +/***/ }), - return { - payload, - ...prot ? { protected: prot } : undefined, - ...header ? { header } : undefined, - signature - } -} -flattenedSerializer.validate = (jws, { 0: { unprotectedHeader, protectedHeader }, length }) => { - if (length !== 1) { - throw new JWSInvalid('Flattened JWS JSON Serialization doesn\'t support multiple recipients') - } - validateCrit(protectedHeader, unprotectedHeader, protectedHeader ? protectedHeader.crit : undefined) -} +/***/ 2285: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const generalSerializer = (payload, recipients) => { - return { - payload, - signatures: recipients.map(({ header, signature, protected: prot }) => { - return { - ...prot ? { protected: prot } : undefined, - ...header ? { header } : undefined, - signature - } - }) - } -} -generalSerializer.validate = (jws, recipients) => { - let validateB64 = false - recipients.forEach(({ protectedHeader, unprotectedHeader }) => { - if (protectedHeader && !validateB64 && 'b64' in protectedHeader) { - validateB64 = true - } - validateCrit(protectedHeader, unprotectedHeader, protectedHeader ? protectedHeader.crit : undefined) - }) +"use strict"; - if (validateB64) { - const values = recipients.map(({ protectedHeader }) => protectedHeader && protectedHeader.b64) - if (!values.every((actual, i, [expected]) => actual === expected)) { - throw new JWSInvalid('the "b64" Header Parameter value MUST be the same for all recipients') +/* + * Copyright The OpenTelemetry 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 + * + * https://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.ProxyTracerProvider = void 0; +const ProxyTracer_1 = __nccwpck_require__(43503); +const NoopTracerProvider_1 = __nccwpck_require__(23259); +const NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider(); +/** + * Tracer provider which provides {@link ProxyTracer}s. + * + * Before a delegate is set, tracers provided are NoOp. + * When a delegate is set, traces are provided from the delegate. + * When a delegate is set after tracers have already been provided, + * all tracers already provided will use the provided delegate implementation. + */ +class ProxyTracerProvider { + /** + * Get a {@link ProxyTracer} + */ + getTracer(name, version, options) { + var _a; + return ((_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer_1.ProxyTracer(this, name, version, options)); + } + getDelegate() { + var _a; + return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER; + } + /** + * Set the delegate tracer provider + */ + setDelegate(delegate) { + this._delegate = delegate; + } + getDelegateTracer(name, version, options) { + var _a; + return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options); } - } } +exports.ProxyTracerProvider = ProxyTracerProvider; +//# sourceMappingURL=ProxyTracerProvider.js.map -const isJSON = (input) => { - return isObject(input) && (typeof input.payload === 'string' || Buffer.isBuffer(input.payload)) -} +/***/ }), -const isValidRecipient = (recipient) => { - return isObject(recipient) && typeof recipient.signature === 'string' && - (recipient.header === undefined || isObject(recipient.header)) && - (recipient.protected === undefined || typeof recipient.protected === 'string') -} +/***/ 33209: +/***/ ((__unused_webpack_module, exports) => { -const isMultiRecipient = (input) => { - if (Array.isArray(input.signatures) && input.signatures.every(isValidRecipient)) { - return true - } +"use strict"; - return false -} +/* + * Copyright The OpenTelemetry 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 + * + * https://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.SamplingDecision = void 0; +/** + * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead. + * A sampling decision that determines how a {@link Span} will be recorded + * and collected. + */ +var SamplingDecision; +(function (SamplingDecision) { + /** + * `Span.isRecording() === false`, span will not be recorded and all events + * and attributes will be dropped. + */ + SamplingDecision[SamplingDecision["NOT_RECORD"] = 0] = "NOT_RECORD"; + /** + * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags} + * MUST NOT be set. + */ + SamplingDecision[SamplingDecision["RECORD"] = 1] = "RECORD"; + /** + * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags} + * MUST be set. + */ + SamplingDecision[SamplingDecision["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED"; +})(SamplingDecision = exports.SamplingDecision || (exports.SamplingDecision = {})); +//# sourceMappingURL=SamplingResult.js.map -const detect = (input) => { - if (typeof input === 'string' && input.split('.').length === 3) { - return 'compact' - } +/***/ }), - if (isJSON(input)) { - if (isMultiRecipient(input)) { - return 'general' - } +/***/ 23326: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (isValidRecipient(input)) { - return 'flattened' - } - } +"use strict"; - throw new JWSInvalid('JWS malformed or invalid serialization') +/* + * Copyright The OpenTelemetry 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 + * + * https://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.getSpanContext = exports.setSpanContext = exports.deleteSpan = exports.setSpan = exports.getActiveSpan = exports.getSpan = void 0; +const context_1 = __nccwpck_require__(78242); +const NonRecordingSpan_1 = __nccwpck_require__(81462); +const context_2 = __nccwpck_require__(57171); +/** + * span key + */ +const SPAN_KEY = (0, context_1.createContextKey)('OpenTelemetry Context Key SPAN'); +/** + * Return the span if one exists + * + * @param context context to get span from + */ +function getSpan(context) { + return context.getValue(SPAN_KEY) || undefined; } - -module.exports = { - compact: compactSerializer, - flattened: flattenedSerializer, - general: generalSerializer, - detect +exports.getSpan = getSpan; +/** + * Gets the span from the current context, if one exists. + */ +function getActiveSpan() { + return getSpan(context_2.ContextAPI.getInstance().active()); } - +exports.getActiveSpan = getActiveSpan; +/** + * Set the span on a context + * + * @param context context to use as parent + * @param span span to set active + */ +function setSpan(context, span) { + return context.setValue(SPAN_KEY, span); +} +exports.setSpan = setSpan; +/** + * Remove current span stored in the context + * + * @param context context to delete span from + */ +function deleteSpan(context) { + return context.deleteValue(SPAN_KEY); +} +exports.deleteSpan = deleteSpan; +/** + * Wrap span context in a NoopSpan and set as span in a new + * context + * + * @param context context to set active span on + * @param spanContext span context to be wrapped + */ +function setSpanContext(context, spanContext) { + return setSpan(context, new NonRecordingSpan_1.NonRecordingSpan(spanContext)); +} +exports.setSpanContext = setSpanContext; +/** + * Get the span context of the span if it exists. + * + * @param context context to get values from + */ +function getSpanContext(context) { + var _a; + return (_a = getSpan(context)) === null || _a === void 0 ? void 0 : _a.spanContext(); +} +exports.getSpanContext = getSpanContext; +//# sourceMappingURL=context-utils.js.map /***/ }), -/***/ 81194: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const base64url = __nccwpck_require__(93312) -const isDisjoint = __nccwpck_require__(48899) -const isObject = __nccwpck_require__(50243) -const deepClone = __nccwpck_require__(52083) -const { JWSInvalid } = __nccwpck_require__(35132) -const { sign } = __nccwpck_require__(40423) -const getKey = __nccwpck_require__(7090) - -const serializers = __nccwpck_require__(21708) +/***/ 62110: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const PROCESS_RECIPIENT = Symbol('PROCESS_RECIPIENT') +"use strict"; -class Sign { - constructor (payload) { - if (typeof payload === 'string') { - payload = base64url.encode(payload) - } else if (Buffer.isBuffer(payload)) { - payload = base64url.encodeBuffer(payload) - this._binary = true - } else if (isObject(payload)) { - payload = base64url.JSON.encode(payload) - } else { - throw new TypeError('payload argument must be a Buffer, string or an object') +/* + * Copyright The OpenTelemetry 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 + * + * https://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.TraceStateImpl = void 0; +const tracestate_validators_1 = __nccwpck_require__(54864); +const MAX_TRACE_STATE_ITEMS = 32; +const MAX_TRACE_STATE_LEN = 512; +const LIST_MEMBERS_SEPARATOR = ','; +const LIST_MEMBER_KEY_VALUE_SPLITTER = '='; +/** + * TraceState must be a class and not a simple object type because of the spec + * requirement (https://www.w3.org/TR/trace-context/#tracestate-field). + * + * Here is the list of allowed mutations: + * - New key-value pair should be added into the beginning of the list + * - The value of any key can be updated. Modified keys MUST be moved to the + * beginning of the list. + */ +class TraceStateImpl { + constructor(rawTraceState) { + this._internalState = new Map(); + if (rawTraceState) + this._parse(rawTraceState); } - - this._payload = payload - this._recipients = [] - } - - /* - * @public - */ - recipient (key, protectedHeader, unprotectedHeader) { - key = getKey(key) - - if (protectedHeader !== undefined && !isObject(protectedHeader)) { - throw new TypeError('protectedHeader argument must be a plain object when provided') + set(key, value) { + // TODO: Benchmark the different approaches(map vs list) and + // use the faster one. + const traceState = this._clone(); + if (traceState._internalState.has(key)) { + traceState._internalState.delete(key); + } + traceState._internalState.set(key, value); + return traceState; } - - if (unprotectedHeader !== undefined && !isObject(unprotectedHeader)) { - throw new TypeError('unprotectedHeader argument must be a plain object when provided') + unset(key) { + const traceState = this._clone(); + traceState._internalState.delete(key); + return traceState; } - - if (!isDisjoint(protectedHeader, unprotectedHeader)) { - throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint') + get(key) { + return this._internalState.get(key); } - - this._recipients.push({ - key, - protectedHeader: protectedHeader ? deepClone(protectedHeader) : undefined, - unprotectedHeader: unprotectedHeader ? deepClone(unprotectedHeader) : undefined - }) - - return this - } - - /* - * @private - */ - [PROCESS_RECIPIENT] (recipient, first) { - const { key, protectedHeader, unprotectedHeader } = recipient - - if (key.use === 'enc') { - throw new TypeError('a key with "use":"enc" is not usable for signing') + serialize() { + return this._keys() + .reduce((agg, key) => { + agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key)); + return agg; + }, []) + .join(LIST_MEMBERS_SEPARATOR); } - - const joseHeader = { - protected: protectedHeader || {}, - unprotected: unprotectedHeader || {} + _parse(rawTraceState) { + if (rawTraceState.length > MAX_TRACE_STATE_LEN) + return; + this._internalState = rawTraceState + .split(LIST_MEMBERS_SEPARATOR) + .reverse() // Store in reverse so new keys (.set(...)) will be placed at the beginning + .reduce((agg, part) => { + const listMember = part.trim(); // Optional Whitespace (OWS) handling + const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER); + if (i !== -1) { + const key = listMember.slice(0, i); + const value = listMember.slice(i + 1, part.length); + if ((0, tracestate_validators_1.validateKey)(key) && (0, tracestate_validators_1.validateValue)(value)) { + agg.set(key, value); + } + else { + // TODO: Consider to add warning log + } + } + return agg; + }, new Map()); + // Because of the reverse() requirement, trunc must be done after map is created + if (this._internalState.size > MAX_TRACE_STATE_ITEMS) { + this._internalState = new Map(Array.from(this._internalState.entries()) + .reverse() // Use reverse same as original tracestate parse chain + .slice(0, MAX_TRACE_STATE_ITEMS)); + } } - - let alg = joseHeader.protected.alg || joseHeader.unprotected.alg - - if (!alg) { - alg = key.alg || [...key.algorithms('sign')][0] - if (recipient.protectedHeader) { - joseHeader.protected.alg = recipient.protectedHeader.alg = alg - } else { - joseHeader.protected = recipient.protectedHeader = { alg } - } + _keys() { + return Array.from(this._internalState.keys()).reverse(); } - - if (!alg) { - throw new JWSInvalid('could not resolve a usable "alg" for a recipient') + _clone() { + const traceState = new TraceStateImpl(); + traceState._internalState = new Map(this._internalState); + return traceState; } +} +exports.TraceStateImpl = TraceStateImpl; +//# sourceMappingURL=tracestate-impl.js.map - recipient.header = unprotectedHeader - recipient.protected = Object.keys(joseHeader.protected).length ? base64url.JSON.encode(joseHeader.protected) : '' - - if (first && joseHeader.protected.crit && joseHeader.protected.crit.includes('b64') && joseHeader.protected.b64 === false) { - if (this._binary) { - this._payload = base64url.decodeToBuffer(this._payload) - } else { - this._payload = base64url.decode(this._payload) - } - } +/***/ }), - const data = Buffer.concat([ - Buffer.from(recipient.protected || ''), - Buffer.from('.'), - Buffer.from(this._payload) - ]) +/***/ 54864: +/***/ ((__unused_webpack_module, exports) => { - recipient.signature = base64url.encodeBuffer(sign(alg, key, data)) - } +"use strict"; - /* - * @public - */ - sign (serialization) { - const serializer = serializers[serialization] - if (!serializer) { - throw new TypeError('serialization must be one of "compact", "flattened", "general"') - } +/* + * Copyright The OpenTelemetry 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 + * + * https://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.validateValue = exports.validateKey = void 0; +const VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]'; +const VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`; +const VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`; +const VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`); +const VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/; +const INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/; +/** + * Key is opaque string up to 256 characters printable. It MUST begin with a + * lowercase letter, and can only contain lowercase letters a-z, digits 0-9, + * underscores _, dashes -, asterisks *, and forward slashes /. + * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the + * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key. + * see https://www.w3.org/TR/trace-context/#key + */ +function validateKey(key) { + return VALID_KEY_REGEX.test(key); +} +exports.validateKey = validateKey; +/** + * Value is opaque string up to 256 characters printable ASCII RFC0020 + * characters (i.e., the range 0x20 to 0x7E) except comma , and =. + */ +function validateValue(value) { + return (VALID_VALUE_BASE_REGEX.test(value) && + !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)); +} +exports.validateValue = validateValue; +//# sourceMappingURL=tracestate-validators.js.map - if (!this._recipients.length) { - throw new JWSInvalid('missing recipients') - } +/***/ }), - serializer.validate(this, this._recipients) +/***/ 32615: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - this._recipients.forEach((recipient, i) => { - this[PROCESS_RECIPIENT](recipient, i === 0) - }) +"use strict"; - return serializer(this._payload, this._recipients) - } +/* + * Copyright The OpenTelemetry 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 + * + * https://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.createTraceState = void 0; +const tracestate_impl_1 = __nccwpck_require__(62110); +function createTraceState(rawTraceState) { + return new tracestate_impl_1.TraceStateImpl(rawTraceState); } - -module.exports = Sign - +exports.createTraceState = createTraceState; +//# sourceMappingURL=utils.js.map /***/ }), -/***/ 45057: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { EOL } = __nccwpck_require__(22037) - -const base64url = __nccwpck_require__(93312) -const isDisjoint = __nccwpck_require__(48899) -const isObject = __nccwpck_require__(50243) -let validateCrit = __nccwpck_require__(85822) -const getKey = __nccwpck_require__(7090) -const { KeyStore } = __nccwpck_require__(27397) -const errors = __nccwpck_require__(35132) -const { check, verify } = __nccwpck_require__(40423) -const JWK = __nccwpck_require__(2297) - -const { detect: resolveSerialization } = __nccwpck_require__(21708) +/***/ 91760: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -validateCrit = validateCrit.bind(undefined, errors.JWSInvalid) -const SINGLE_RECIPIENT = new Set(['compact', 'flattened', 'preparsed']) +"use strict"; /* - * @public + * Copyright The OpenTelemetry 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 + * + * https://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 jwsVerify = (skipDisjointCheck, serialization, jws, key, { crit = [], complete = false, algorithms } = {}) => { - key = getKey(key, true) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = void 0; +const trace_flags_1 = __nccwpck_require__(26905); +exports.INVALID_SPANID = '0000000000000000'; +exports.INVALID_TRACEID = '00000000000000000000000000000000'; +exports.INVALID_SPAN_CONTEXT = { + traceId: exports.INVALID_TRACEID, + spanId: exports.INVALID_SPANID, + traceFlags: trace_flags_1.TraceFlags.NONE, +}; +//# sourceMappingURL=invalid-span-constants.js.map - if (algorithms !== undefined && (!Array.isArray(algorithms) || algorithms.some(s => typeof s !== 'string' || !s))) { - throw new TypeError('"algorithms" option must be an array of non-empty strings') - } else if (algorithms) { - algorithms = new Set(algorithms) - } +/***/ }), - if (!Array.isArray(crit) || crit.some(s => typeof s !== 'string' || !s)) { - throw new TypeError('"crit" option must be an array of non-empty strings') - } +/***/ 31424: +/***/ ((__unused_webpack_module, exports) => { - if (!serialization) { - serialization = resolveSerialization(jws) - } +"use strict"; - let prot // protected header - let header // unprotected header - let payload - let signature - let alg +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SpanKind = void 0; +/* + * Copyright The OpenTelemetry 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 + * + * https://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 SpanKind; +(function (SpanKind) { + /** Default value. Indicates that the span is used internally. */ + SpanKind[SpanKind["INTERNAL"] = 0] = "INTERNAL"; + /** + * Indicates that the span covers server-side handling of an RPC or other + * remote request. + */ + SpanKind[SpanKind["SERVER"] = 1] = "SERVER"; + /** + * Indicates that the span covers the client-side wrapper around an RPC or + * other remote request. + */ + SpanKind[SpanKind["CLIENT"] = 2] = "CLIENT"; + /** + * Indicates that the span describes producer sending a message to a + * broker. Unlike client and server, there is no direct critical path latency + * relationship between producer and consumer spans. + */ + SpanKind[SpanKind["PRODUCER"] = 3] = "PRODUCER"; + /** + * Indicates that the span describes consumer receiving a message from a + * broker. Unlike client and server, there is no direct critical path latency + * relationship between producer and consumer spans. + */ + SpanKind[SpanKind["CONSUMER"] = 4] = "CONSUMER"; +})(SpanKind = exports.SpanKind || (exports.SpanKind = {})); +//# sourceMappingURL=span_kind.js.map - // treat general format with one recipient as flattened - // skips iteration and avoids multi errors in this case - if (serialization === 'general' && jws.signatures.length === 1) { - serialization = 'flattened' - const { signatures, ...root } = jws - jws = { ...root, ...signatures[0] } - } +/***/ }), - let decoded +/***/ 49745: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (SINGLE_RECIPIENT.has(serialization)) { - let parsedProt = {} +"use strict"; - switch (serialization) { - case 'compact': // compact serialization format - ([prot, payload, signature] = jws.split('.')) - break - case 'flattened': // flattened serialization format - ({ protected: prot, payload, signature, header } = jws) - break - case 'preparsed': { // from the JWT module - ({ decoded } = jws); - ([prot, payload, signature] = jws.token.split('.')) - break - } - } - - if (!header) { - skipDisjointCheck = true - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.wrapSpanContext = exports.isSpanContextValid = exports.isValidSpanId = exports.isValidTraceId = void 0; +/* + * Copyright The OpenTelemetry 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 + * + * https://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 invalid_span_constants_1 = __nccwpck_require__(91760); +const NonRecordingSpan_1 = __nccwpck_require__(81462); +const VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i; +const VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; +function isValidTraceId(traceId) { + return VALID_TRACEID_REGEX.test(traceId) && traceId !== invalid_span_constants_1.INVALID_TRACEID; +} +exports.isValidTraceId = isValidTraceId; +function isValidSpanId(spanId) { + return VALID_SPANID_REGEX.test(spanId) && spanId !== invalid_span_constants_1.INVALID_SPANID; +} +exports.isValidSpanId = isValidSpanId; +/** + * Returns true if this {@link SpanContext} is valid. + * @return true if this {@link SpanContext} is valid. + */ +function isSpanContextValid(spanContext) { + return (isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId)); +} +exports.isSpanContextValid = isSpanContextValid; +/** + * Wrap the given {@link SpanContext} in a new non-recording {@link Span} + * + * @param spanContext span context to be wrapped + * @returns a new non-recording {@link Span} with the provided context + */ +function wrapSpanContext(spanContext) { + return new NonRecordingSpan_1.NonRecordingSpan(spanContext); +} +exports.wrapSpanContext = wrapSpanContext; +//# sourceMappingURL=spancontext-utils.js.map - if (decoded) { - parsedProt = decoded.header - } else if (prot) { - try { - parsedProt = base64url.JSON.decode(prot) - } catch (err) { - throw new errors.JWSInvalid('could not parse JWS protected header') - } - } else { - skipDisjointCheck = skipDisjointCheck || true - } +/***/ }), - if (!skipDisjointCheck && !isDisjoint(parsedProt, header)) { - throw new errors.JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint') - } +/***/ 48845: +/***/ ((__unused_webpack_module, exports) => { - const combinedHeader = { ...parsedProt, ...header } - validateCrit(parsedProt, header, crit) +"use strict"; - alg = parsedProt.alg || (header && header.alg) - if (!alg) { - throw new errors.JWSInvalid('missing JWS signature algorithm') - } else if (algorithms && !algorithms.has(alg)) { - throw new errors.JOSEAlgNotWhitelisted('alg not whitelisted') - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SpanStatusCode = void 0; +/** + * An enumeration of status codes. + */ +var SpanStatusCode; +(function (SpanStatusCode) { + /** + * The default status. + */ + SpanStatusCode[SpanStatusCode["UNSET"] = 0] = "UNSET"; + /** + * The operation has been validated by an Application developer or + * Operator to have completed successfully. + */ + SpanStatusCode[SpanStatusCode["OK"] = 1] = "OK"; + /** + * The operation contains an error. + */ + SpanStatusCode[SpanStatusCode["ERROR"] = 2] = "ERROR"; +})(SpanStatusCode = exports.SpanStatusCode || (exports.SpanStatusCode = {})); +//# sourceMappingURL=status.js.map - if (key instanceof KeyStore) { - const keystore = key - const keys = keystore.all({ kid: combinedHeader.kid, alg: combinedHeader.alg, key_ops: ['verify'] }) - switch (keys.length) { - case 0: - throw new errors.JWKSNoMatchingKey() - case 1: - // treat the call as if a Key instance was passed in - // skips iteration and avoids multi errors in this case - key = keys[0] - break - default: { - const errs = [] - for (const key of keys) { - try { - return jwsVerify(true, serialization, jws, key, { crit, complete, algorithms: algorithms ? [...algorithms] : undefined }) - } catch (err) { - errs.push(err) - continue - } - } +/***/ }), - const multi = new errors.JOSEMultiError(errs) - if ([...multi].some(e => e instanceof errors.JWSVerificationFailed)) { - throw new errors.JWSVerificationFailed() - } - throw multi - } - } - } +/***/ 26905: +/***/ ((__unused_webpack_module, exports) => { - if (key === JWK.EmbeddedJWK) { - if (!isObject(combinedHeader.jwk)) { - throw new errors.JWSInvalid('JWS Header Parameter "jwk" must be a JSON object') - } - key = JWK.asKey(combinedHeader.jwk) - if (key.type !== 'public') { - throw new errors.JWSInvalid('JWS Header Parameter "jwk" must be a public key') - } - } else if (key === JWK.EmbeddedX5C) { - if (!Array.isArray(combinedHeader.x5c) || !combinedHeader.x5c.length || combinedHeader.x5c.some(c => typeof c !== 'string' || !c)) { - throw new errors.JWSInvalid('JWS Header Parameter "x5c" must be a JSON array of certificate value strings') - } - key = JWK.asKey( - `-----BEGIN CERTIFICATE-----${EOL}${(combinedHeader.x5c[0].match(/.{1,64}/g) || []).join(EOL)}${EOL}-----END CERTIFICATE-----`, - { x5c: combinedHeader.x5c } - ) - } +"use strict"; - check(key, 'verify', alg) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TraceFlags = void 0; +/* + * Copyright The OpenTelemetry 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 + * + * https://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 TraceFlags; +(function (TraceFlags) { + /** Represents no flag set. */ + TraceFlags[TraceFlags["NONE"] = 0] = "NONE"; + /** Bit to represent whether trace is sampled in trace flags. */ + TraceFlags[TraceFlags["SAMPLED"] = 1] = "SAMPLED"; +})(TraceFlags = exports.TraceFlags || (exports.TraceFlags = {})); +//# sourceMappingURL=trace_flags.js.map - const toBeVerified = Buffer.concat([ - Buffer.from(prot || ''), - Buffer.from('.'), - Buffer.isBuffer(payload) ? payload : Buffer.from(payload) - ]) +/***/ }), - if (!verify(alg, key, toBeVerified, base64url.decodeToBuffer(signature))) { - throw new errors.JWSVerificationFailed() - } +/***/ 98996: +/***/ ((__unused_webpack_module, exports) => { - if (combinedHeader.b64 === false) { - payload = Buffer.from(payload) - } else { - payload = base64url.decodeToBuffer(payload) - } +"use strict"; - if (complete) { - const result = { payload, key } - if (prot) result.protected = parsedProt - if (header) result.header = header - return result - } +/* + * Copyright The OpenTelemetry 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 + * + * https://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.VERSION = void 0; +// this is autogenerated file, see scripts/version-update.js +exports.VERSION = '1.4.1'; +//# sourceMappingURL=version.js.map - return payload - } +/***/ }), - // general serialization format - const { signatures, ...root } = jws - const errs = [] - for (const recipient of signatures) { - try { - return jwsVerify(false, 'flattened', { ...root, ...recipient }, key, { crit, complete, algorithms: algorithms ? [...algorithms] : undefined }) - } catch (err) { - errs.push(err) - continue - } - } +/***/ 39436: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const multi = new errors.JOSEMultiError(errs) - if ([...multi].some(e => e instanceof errors.JWSVerificationFailed)) { - throw new errors.JWSVerificationFailed() - } else if ([...multi].every(e => e instanceof errors.JWKSNoMatchingKey)) { - throw new errors.JWKSNoMatchingKey() - } - throw multi -} +const { define } = __nccwpck_require__(93998) +const base = __nccwpck_require__(33318) +const constants = __nccwpck_require__(90998) +const decoders = __nccwpck_require__(5017) +const encoders = __nccwpck_require__(2246) module.exports = { - bare: jwsVerify, - verify: jwsVerify.bind(undefined, false, undefined) + base, + constants, + decoders, + define, + encoders } /***/ }), -/***/ 85955: +/***/ 93998: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const base64url = __nccwpck_require__(93312) -const errors = __nccwpck_require__(35132) - -module.exports = (token, { complete = false } = {}) => { - if (typeof token !== 'string' || !token) { - throw new TypeError('JWT must be a string') - } +const { inherits } = __nccwpck_require__(73837) +const encoders = __nccwpck_require__(2246) +const decoders = __nccwpck_require__(5017) - const { 0: header, 1: payload, 2: signature, length } = token.split('.') +module.exports.define = function define (name, body) { + return new Entity(name, body) +} - if (length === 5) { - throw new TypeError('encrypted JWTs cannot be decoded') - } +function Entity (name, body) { + this.name = name + this.body = body - if (length !== 3) { - throw new errors.JWTMalformed('JWTs must have three components') - } + this.decoders = {} + this.encoders = {} +} - try { - const result = { - header: base64url.JSON.decode(header), - payload: base64url.JSON.decode(payload), - signature - } +Entity.prototype._createNamed = function createNamed (Base) { + const name = this.name - return complete ? result : result.payload - } catch (err) { - throw new errors.JWTMalformed('JWT is malformed') + function Generated (entity) { + this._initNamed(entity, name) + } + inherits(Generated, Base) + Generated.prototype._initNamed = function _initNamed (entity, name) { + Base.call(this, entity, name) } -} - -/***/ }), + return new Generated(this) +} -/***/ 40449: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +Entity.prototype._getDecoder = function _getDecoder (enc) { + enc = enc || 'der' + // Lazily create decoder + if (!Object.prototype.hasOwnProperty.call(this.decoders, enc)) { this.decoders[enc] = this._createNamed(decoders[enc]) } + return this.decoders[enc] +} -const decode = __nccwpck_require__(85955) -const sign = __nccwpck_require__(82011) -const verify = __nccwpck_require__(88493) -const profiles = __nccwpck_require__(52651) +Entity.prototype.decode = function decode (data, enc, options) { + return this._getDecoder(enc).decode(data, options) +} -module.exports = { - sign, - verify, - ...profiles +Entity.prototype._getEncoder = function _getEncoder (enc) { + enc = enc || 'der' + // Lazily create encoder + if (!Object.prototype.hasOwnProperty.call(this.encoders, enc)) { this.encoders[enc] = this._createNamed(encoders[enc]) } + return this.encoders[enc] } -Object.defineProperty(module.exports, "decode", ({ - enumerable: false, - configurable: true, - value: decode -})) +Entity.prototype.encode = function encode (data, enc, /* internal */ reporter) { + return this._getEncoder(enc).encode(data, reporter) +} /***/ }), -/***/ 52651: +/***/ 28424: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const { JWTClaimInvalid } = __nccwpck_require__(35132) -const secs = __nccwpck_require__(84096) -const epoch = __nccwpck_require__(33773) -const isObject = __nccwpck_require__(50243) +const { inherits } = __nccwpck_require__(73837) -const verify = __nccwpck_require__(88493) -const { - isString, - isRequired, - isTimestamp, - isStringOrArrayOfStrings -} = __nccwpck_require__(29051) +const { Reporter } = __nccwpck_require__(93026) -const isPayloadRequired = isRequired.bind(undefined, JWTClaimInvalid) -const isPayloadString = isString.bind(undefined, JWTClaimInvalid) -const isOptionString = isString.bind(undefined, TypeError) +function DecoderBuffer (base, options) { + Reporter.call(this, options) + if (!Buffer.isBuffer(base)) { + this.error('Input not Buffer') + return + } -const defineLazyExportWithWarning = (obj, property, name, definition) => { - Object.defineProperty(obj, property, { - enumerable: true, - configurable: true, - value (...args) { - process.emitWarning( - `The ${name} API implements an IETF draft. Breaking draft implementations are included as minor versions of the jose library, therefore, the ~ semver operator should be used and close attention be payed to library changelog as well as the drafts themselves.`, - 'DraftWarning' - ) - Object.defineProperty(obj, property, { - enumerable: true, - configurable: true, - value: definition - }) - return obj[property](...args) - } - }) + this.base = base + this.offset = 0 + this.length = base.length } +inherits(DecoderBuffer, Reporter) -const validateCommonOptions = (options, profile) => { - if (!isObject(options)) { - throw new TypeError('options must be an object') +DecoderBuffer.isDecoderBuffer = function isDecoderBuffer (data) { + if (data instanceof DecoderBuffer) { + return true } - if (!options.issuer) { - throw new TypeError(`"issuer" option is required to validate ${profile}`) - } + // Or accept compatible API + const isCompatible = typeof data === 'object' && + Buffer.isBuffer(data.base) && + data.constructor.name === 'DecoderBuffer' && + typeof data.offset === 'number' && + typeof data.length === 'number' && + typeof data.save === 'function' && + typeof data.restore === 'function' && + typeof data.isEmpty === 'function' && + typeof data.readUInt8 === 'function' && + typeof data.skip === 'function' && + typeof data.raw === 'function' - if (!options.audience) { - throw new TypeError(`"audience" option is required to validate ${profile}`) - } + return isCompatible } -module.exports = { - IdToken: { - verify: (token, key, options = {}) => { - validateCommonOptions(options, 'an ID Token') - - if ('maxAuthAge' in options) { - isOptionString(options.maxAuthAge, 'options.maxAuthAge') - } - if ('nonce' in options) { - isOptionString(options.nonce, 'options.nonce') - } - - const unix = epoch(options.now || new Date()) - const result = verify(token, key, { ...options }) - const payload = options.complete ? result.payload : result - - if (Array.isArray(payload.aud) && payload.aud.length > 1) { - isPayloadRequired(payload.azp, '"azp" claim', 'azp') - } - isPayloadRequired(payload.iat, '"iat" claim', 'iat') - isPayloadRequired(payload.sub, '"sub" claim', 'sub') - isPayloadRequired(payload.exp, '"exp" claim', 'exp') - isTimestamp(payload.auth_time, 'auth_time', !!options.maxAuthAge) - isPayloadString(payload.nonce, '"nonce" claim', 'nonce', !!options.nonce) - isPayloadString(payload.acr, '"acr" claim', 'acr') - isStringOrArrayOfStrings(payload.amr, 'amr') - - if (options.nonce && payload.nonce !== options.nonce) { - throw new JWTClaimInvalid('unexpected "nonce" claim value', 'nonce', 'check_failed') - } - - const tolerance = options.clockTolerance ? secs(options.clockTolerance) : 0 +DecoderBuffer.prototype.save = function save () { + return { offset: this.offset, reporter: Reporter.prototype.save.call(this) } +} - if (options.maxAuthAge) { - const maxAuthAgeSeconds = secs(options.maxAuthAge) - if (payload.auth_time + maxAuthAgeSeconds < unix - tolerance) { - throw new JWTClaimInvalid('"auth_time" claim timestamp check failed (too much time has elapsed since the last End-User authentication)', 'auth_time', 'check_failed') - } - } +DecoderBuffer.prototype.restore = function restore (save) { + // Return skipped data + const res = new DecoderBuffer(this.base) + res.offset = save.offset + res.length = this.offset - if (Array.isArray(payload.aud) && payload.aud.length > 1 && payload.azp !== options.audience) { - throw new JWTClaimInvalid('unexpected "azp" claim value', 'azp', 'check_failed') - } + this.offset = save.offset + Reporter.prototype.restore.call(this, save.reporter) - return result - } - }, - LogoutToken: {}, - AccessToken: {} + return res } -defineLazyExportWithWarning(module.exports.LogoutToken, 'verify', 'jose.JWT.LogoutToken.verify', (token, key, options = {}) => { - validateCommonOptions(options, 'a Logout Token') +DecoderBuffer.prototype.isEmpty = function isEmpty () { + return this.offset === this.length +} - const result = verify(token, key, { ...options }) - const payload = options.complete ? result.payload : result +DecoderBuffer.prototype.readUInt8 = function readUInt8 (fail) { + if (this.offset + 1 <= this.length) { return this.base.readUInt8(this.offset++, true) } else { return this.error(fail || 'DecoderBuffer overrun') } +} - isPayloadRequired(payload.iat, '"iat" claim', 'iat') - isPayloadRequired(payload.jti, '"jti" claim', 'jti') - isPayloadString(payload.sid, '"sid" claim', 'sid') +DecoderBuffer.prototype.skip = function skip (bytes, fail) { + if (!(this.offset + bytes <= this.length)) { return this.error(fail || 'DecoderBuffer overrun') } - if (!('sid' in payload) && !('sub' in payload)) { - throw new JWTClaimInvalid('either "sid" or "sub" (or both) claims must be present') - } + const res = new DecoderBuffer(this.base) - if ('nonce' in payload) { - throw new JWTClaimInvalid('"nonce" claim is prohibited', 'nonce', 'prohibited') - } + // Share reporter state + res._reporterState = this._reporterState - if (!('events' in payload)) { - throw new JWTClaimInvalid('"events" claim is missing', 'events', 'missing') - } + res.offset = this.offset + res.length = this.offset + bytes + this.offset += bytes + return res +} - if (!isObject(payload.events)) { - throw new JWTClaimInvalid('"events" claim must be an object', 'events', 'invalid') - } +DecoderBuffer.prototype.raw = function raw (save) { + return this.base.slice(save ? save.offset : this.offset, this.length) +} - if (!('http://schemas.openid.net/event/backchannel-logout' in payload.events)) { - throw new JWTClaimInvalid('"http://schemas.openid.net/event/backchannel-logout" member is missing in the "events" claim', 'events', 'invalid') +function EncoderBuffer (value, reporter) { + if (Array.isArray(value)) { + this.length = 0 + this.value = value.map(function (item) { + if (!EncoderBuffer.isEncoderBuffer(item)) { item = new EncoderBuffer(item, reporter) } + this.length += item.length + return item + }, this) + } else if (typeof value === 'number') { + if (!(value >= 0 && value <= 0xff)) { return reporter.error('non-byte EncoderBuffer value') } + this.value = value + this.length = 1 + } else if (typeof value === 'string') { + this.value = value + this.length = Buffer.byteLength(value) + } else if (Buffer.isBuffer(value)) { + this.value = value + this.length = value.length + } else { + return reporter.error(`Unsupported type: ${typeof value}`) } +} - if (!isObject(payload.events['http://schemas.openid.net/event/backchannel-logout'])) { - throw new JWTClaimInvalid('"http://schemas.openid.net/event/backchannel-logout" member in the "events" claim must be an object', 'events', 'invalid') +EncoderBuffer.isEncoderBuffer = function isEncoderBuffer (data) { + if (data instanceof EncoderBuffer) { + return true } - return result -}) - -defineLazyExportWithWarning(module.exports.AccessToken, 'verify', 'jose.JWT.AccessToken.verify', (token, key, options = {}) => { - validateCommonOptions(options, 'a JWT Access Token') - - isOptionString(options.maxAuthAge, 'options.maxAuthAge') + // Or accept compatible API + const isCompatible = typeof data === 'object' && + data.constructor.name === 'EncoderBuffer' && + typeof data.length === 'number' && + typeof data.join === 'function' - const unix = epoch(options.now || new Date()) - const typ = 'at+JWT' - const result = verify(token, key, { ...options, typ }) - const payload = options.complete ? result.payload : result + return isCompatible +} - isPayloadRequired(payload.iat, '"iat" claim', 'iat') - isPayloadRequired(payload.exp, '"exp" claim', 'exp') - isPayloadRequired(payload.sub, '"sub" claim', 'sub') - isPayloadRequired(payload.jti, '"jti" claim', 'jti') - isPayloadString(payload.client_id, '"client_id" claim', 'client_id', true) - isTimestamp(payload.auth_time, 'auth_time', !!options.maxAuthAge) - isPayloadString(payload.acr, '"acr" claim', 'acr') - isStringOrArrayOfStrings(payload.amr, 'amr') +EncoderBuffer.prototype.join = function join (out, offset) { + if (!out) { out = Buffer.alloc(this.length) } + if (!offset) { offset = 0 } - const tolerance = options.clockTolerance ? secs(options.clockTolerance) : 0 + if (this.length === 0) { return out } - if (options.maxAuthAge) { - const maxAuthAgeSeconds = secs(options.maxAuthAge) - if (payload.auth_time + maxAuthAgeSeconds < unix - tolerance) { - throw new JWTClaimInvalid('"auth_time" claim timestamp check failed (too much time has elapsed since the last End-User authentication)', 'auth_time', 'check_failed') - } + if (Array.isArray(this.value)) { + this.value.forEach(function (item) { + item.join(out, offset) + offset += item.length + }) + } else { + if (typeof this.value === 'number') { out[offset] = this.value } else if (typeof this.value === 'string') { out.write(this.value, offset) } else if (Buffer.isBuffer(this.value)) { this.value.copy(out, offset) } + offset += this.length } - return result -}) + return out +} + +module.exports = { + DecoderBuffer, + EncoderBuffer +} /***/ }), -/***/ 29051: +/***/ 33318: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const { JWTClaimInvalid } = __nccwpck_require__(35132) - -const isNotString = val => typeof val !== 'string' || val.length === 0 -const isNotArrayOfStrings = val => !Array.isArray(val) || val.length === 0 || val.some(isNotString) -const isRequired = (Err, value, label, claim) => { - if (value === undefined) { - throw new Err(`${label} is missing`, claim, 'missing') - } -} -const isString = (Err, value, label, claim, required = false) => { - if (required) { - isRequired(Err, value, label, claim) - } - - if (value !== undefined && isNotString(value)) { - throw new Err(`${label} must be a string`, claim, 'invalid') - } -} -const isTimestamp = (value, label, required = false) => { - if (required && value === undefined) { - throw new JWTClaimInvalid(`"${label}" claim is missing`, label, 'missing') - } - - if (value !== undefined && (typeof value !== 'number')) { - throw new JWTClaimInvalid(`"${label}" claim must be a JSON numeric value`, label, 'invalid') - } -} -const isStringOrArrayOfStrings = (value, label, required = false) => { - if (required && value === undefined) { - throw new JWTClaimInvalid(`"${label}" claim is missing`, label, 'missing') - } - - if (value !== undefined && (isNotString(value) && isNotArrayOfStrings(value))) { - throw new JWTClaimInvalid(`"${label}" claim must be a string or array of strings`, label, 'invalid') - } -} +const { Reporter } = __nccwpck_require__(93026) +const { DecoderBuffer, EncoderBuffer } = __nccwpck_require__(28424) +const Node = __nccwpck_require__(48674) module.exports = { - isNotArrayOfStrings, - isRequired, - isNotString, - isString, - isTimestamp, - isStringOrArrayOfStrings + DecoderBuffer, + EncoderBuffer, + Node, + Reporter } /***/ }), -/***/ 82011: +/***/ 48674: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const isObject = __nccwpck_require__(50243) -const secs = __nccwpck_require__(84096) -const epoch = __nccwpck_require__(33773) -const getKey = __nccwpck_require__(7090) -const JWS = __nccwpck_require__(49830) - -const isString = (__nccwpck_require__(29051).isString.bind)(undefined, TypeError) - -const validateOptions = (options) => { - if (typeof options.iat !== 'boolean') { - throw new TypeError('options.iat must be a boolean') - } - - if (typeof options.kid !== 'boolean') { - throw new TypeError('options.kid must be a boolean') - } - - isString(options.subject, 'options.subject') - isString(options.issuer, 'options.issuer') +const { strict: assert } = __nccwpck_require__(39491) - if ( - options.audience !== undefined && - ( - (typeof options.audience !== 'string' || !options.audience) && - (!Array.isArray(options.audience) || options.audience.length === 0 || options.audience.some(a => !a || typeof a !== 'string')) - ) - ) { - throw new TypeError('options.audience must be a string or an array of strings') - } +const { Reporter } = __nccwpck_require__(93026) +const { DecoderBuffer, EncoderBuffer } = __nccwpck_require__(28424) - if (!isObject(options.header)) { - throw new TypeError('options.header must be an object') - } +// Supported tags +const tags = [ + 'seq', 'seqof', 'set', 'setof', 'objid', 'bool', + 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc', + 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str', + 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr' +] - isString(options.algorithm, 'options.algorithm') - isString(options.expiresIn, 'options.expiresIn') - isString(options.notBefore, 'options.notBefore') - isString(options.jti, 'options.jti') +// Public methods list +const methods = [ + 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', + 'any', 'contains' +].concat(tags) - if (options.now !== undefined && (!(options.now instanceof Date) || !options.now.getTime())) { - throw new TypeError('options.now must be a valid Date object') - } -} +// Overrided methods list +const overrided = [ + '_peekTag', '_decodeTag', '_use', + '_decodeStr', '_decodeObjid', '_decodeTime', + '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', -module.exports = (payload, key, options = {}) => { - if (!isObject(options)) { - throw new TypeError('options must be an object') - } + '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', + '_encodeNull', '_encodeInt', '_encodeBool' +] - const { - algorithm, audience, expiresIn, header = {}, iat = true, - issuer, jti, kid = true, notBefore, subject, now - } = options +function Node (enc, parent, name) { + const state = {} + this._baseState = state - validateOptions({ - algorithm, audience, expiresIn, header, iat, issuer, jti, kid, notBefore, now, subject - }) + state.name = name + state.enc = enc - if (!isObject(payload)) { - throw new TypeError('payload must be an object') - } + state.parent = parent || null + state.children = null - let unix - if (expiresIn || notBefore || iat) { - unix = epoch(now || new Date()) - } + // State + state.tag = null + state.args = null + state.reverseArgs = null + state.choice = null + state.optional = false + state.any = false + state.obj = false + state.use = null + state.useDecoder = null + state.key = null + state.default = null + state.explicit = null + state.implicit = null + state.contains = null - payload = { - ...payload, - sub: subject || payload.sub, - aud: audience || payload.aud, - iss: issuer || payload.iss, - jti: jti || payload.jti, - iat: iat ? unix : payload.iat, - exp: expiresIn ? unix + secs(expiresIn) : payload.exp, - nbf: notBefore ? unix + secs(notBefore) : payload.nbf + // Should create new instance on each method + if (!state.parent) { + state.children = [] + this._wrap() } +} - key = getKey(key) - - let includeKid - - if (typeof options.kid === 'boolean') { - includeKid = kid - } else { - includeKid = !key.secret - } +const stateProps = [ + 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', + 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', + 'implicit', 'contains' +] - return JWS.sign(JSON.stringify(payload), key, { - ...header, - alg: algorithm || header.alg, - kid: includeKid ? key.kid : header.kid +Node.prototype.clone = function clone () { + const state = this._baseState + const cstate = {} + stateProps.forEach(function (prop) { + cstate[prop] = state[prop] }) + const res = new this.constructor(cstate.parent) + res._baseState = cstate + return res } +Node.prototype._wrap = function wrap () { + const state = this._baseState + methods.forEach(function (method) { + this[method] = function _wrappedMethod () { + const clone = new this.constructor(this) + state.children.push(clone) + return clone[method].apply(clone, arguments) + } + }, this) +} -/***/ }), +Node.prototype._init = function init (body) { + const state = this._baseState -/***/ 88493: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + assert(state.parent === null) + body.call(this) -const isObject = __nccwpck_require__(50243) -const epoch = __nccwpck_require__(33773) -const secs = __nccwpck_require__(84096) -const getKey = __nccwpck_require__(7090) -const { bare: verify } = __nccwpck_require__(45057) -const { JWTClaimInvalid, JWTExpired } = __nccwpck_require__(35132) + // Filter children + state.children = state.children.filter(function (child) { + return child._baseState.parent === this + }, this) + assert.equal(state.children.length, 1, 'Root node can have only one child') +} -const { - isString, - isNotString, - isNotArrayOfStrings, - isTimestamp, - isStringOrArrayOfStrings -} = __nccwpck_require__(29051) -const decode = __nccwpck_require__(85955) +Node.prototype._useArgs = function useArgs (args) { + const state = this._baseState -const isPayloadString = isString.bind(undefined, JWTClaimInvalid) -const isOptionString = isString.bind(undefined, TypeError) + // Filter children and args + const children = args.filter(function (arg) { + return arg instanceof this.constructor + }, this) + args = args.filter(function (arg) { + return !(arg instanceof this.constructor) + }, this) -const normalizeTyp = (value) => value.toLowerCase().replace(/^application\//, '') + if (children.length !== 0) { + assert(state.children === null) + state.children = children -const validateOptions = ({ - algorithms, audience, clockTolerance, complete = false, crit, ignoreExp = false, - ignoreIat = false, ignoreNbf = false, issuer, jti, maxTokenAge, now = new Date(), - subject, typ -}) => { - if (typeof complete !== 'boolean') { - throw new TypeError('options.complete must be a boolean') + // Replace parent to maintain backward link + children.forEach(function (child) { + child._baseState.parent = this + }, this) } + if (args.length !== 0) { + assert(state.args === null) + state.args = args + state.reverseArgs = args.map(function (arg) { + if (typeof arg !== 'object' || arg.constructor !== Object) { return arg } - if (typeof ignoreExp !== 'boolean') { - throw new TypeError('options.ignoreExp must be a boolean') + const res = {} + Object.keys(arg).forEach(function (key) { + if (key == (key | 0)) { key |= 0 } // eslint-disable-line eqeqeq + const value = arg[key] + res[value] = key + }) + return res + }) } +} - if (typeof ignoreNbf !== 'boolean') { - throw new TypeError('options.ignoreNbf must be a boolean') - } +// +// Overrided methods +// - if (typeof ignoreIat !== 'boolean') { - throw new TypeError('options.ignoreIat must be a boolean') +overrided.forEach(function (method) { + Node.prototype[method] = function _overrided () { + const state = this._baseState + throw new Error(`${method} not implemented for encoding: ${state.enc}`) } +}) - isOptionString(maxTokenAge, 'options.maxTokenAge') - isOptionString(subject, 'options.subject') - isOptionString(jti, 'options.jti') - isOptionString(clockTolerance, 'options.clockTolerance') - isOptionString(typ, 'options.typ') +// +// Public methods +// - if (issuer !== undefined && (isNotString(issuer) && isNotArrayOfStrings(issuer))) { - throw new TypeError('options.issuer must be a string or an array of strings') - } +tags.forEach(function (tag) { + Node.prototype[tag] = function _tagMethod () { + const state = this._baseState + const args = Array.prototype.slice.call(arguments) - if (audience !== undefined && (isNotString(audience) && isNotArrayOfStrings(audience))) { - throw new TypeError('options.audience must be a string or an array of strings') - } + assert(state.tag === null) + state.tag = tag - if (algorithms !== undefined && isNotArrayOfStrings(algorithms)) { - throw new TypeError('options.algorithms must be an array of strings') - } + this._useArgs(args) - if (!(now instanceof Date) || !now.getTime()) { - throw new TypeError('options.now must be a valid Date object') + return this } +}) - if (ignoreIat && maxTokenAge !== undefined) { - throw new TypeError('options.ignoreIat and options.maxTokenAge cannot used together') - } +Node.prototype.use = function use (item) { + assert(item) + const state = this._baseState - if (crit !== undefined && isNotArrayOfStrings(crit)) { - throw new TypeError('options.crit must be an array of strings') - } + assert(state.use === null) + state.use = item - return { - algorithms, - audience, - clockTolerance, - complete, - crit, - ignoreExp, - ignoreIat, - ignoreNbf, - issuer, - jti, - maxTokenAge, - now, - subject, - typ - } + return this } -const validateTypes = ({ header, payload }, options) => { - isPayloadString(header.alg, '"alg" header parameter', 'alg', true) - - isTimestamp(payload.iat, 'iat', !!options.maxTokenAge) - isTimestamp(payload.exp, 'exp') - isTimestamp(payload.nbf, 'nbf') - isPayloadString(payload.jti, '"jti" claim', 'jti', !!options.jti) - isStringOrArrayOfStrings(payload.iss, 'iss', !!options.issuer) - isPayloadString(payload.sub, '"sub" claim', 'sub', !!options.subject) - isStringOrArrayOfStrings(payload.aud, 'aud', !!options.audience) - isPayloadString(header.typ, '"typ" header parameter', 'typ', !!options.typ) -} +Node.prototype.optional = function optional () { + const state = this._baseState -const checkAudiencePresence = (audPayload, audOption) => { - if (typeof audPayload === 'string') { - return audOption.includes(audPayload) - } + state.optional = true - // Each principal intended to process the JWT MUST - // identify itself with a value in the audience claim - audPayload = new Set(audPayload) - return audOption.some(Set.prototype.has.bind(audPayload)) + return this } -module.exports = (token, key, options = {}) => { - if (!isObject(options)) { - throw new TypeError('options must be an object') - } +Node.prototype.def = function def (val) { + const state = this._baseState - const { - algorithms, audience, clockTolerance, complete, crit, ignoreExp, ignoreIat, ignoreNbf, issuer, - jti, maxTokenAge, now, subject, typ - } = options = validateOptions(options) + assert(state.default === null) + state.default = val + state.optional = true - const decoded = decode(token, { complete: true }) - key = getKey(key, true) + return this +} - if (complete) { - ({ key } = verify(true, 'preparsed', { decoded, token }, key, { crit, algorithms, complete: true })) - decoded.key = key - } else { - verify(true, 'preparsed', { decoded, token }, key, { crit, algorithms }) - } +Node.prototype.explicit = function explicit (num) { + const state = this._baseState - const unix = epoch(now) - validateTypes(decoded, options) + assert(state.explicit === null && state.implicit === null) + state.explicit = num - if (issuer && (typeof decoded.payload.iss !== 'string' || !(typeof issuer === 'string' ? [issuer] : issuer).includes(decoded.payload.iss))) { - throw new JWTClaimInvalid('unexpected "iss" claim value', 'iss', 'check_failed') - } + return this +} - if (subject && decoded.payload.sub !== subject) { - throw new JWTClaimInvalid('unexpected "sub" claim value', 'sub', 'check_failed') - } +Node.prototype.implicit = function implicit (num) { + const state = this._baseState - if (jti && decoded.payload.jti !== jti) { - throw new JWTClaimInvalid('unexpected "jti" claim value', 'jti', 'check_failed') - } + assert(state.explicit === null && state.implicit === null) + state.implicit = num - if (audience && !checkAudiencePresence(decoded.payload.aud, typeof audience === 'string' ? [audience] : audience)) { - throw new JWTClaimInvalid('unexpected "aud" claim value', 'aud', 'check_failed') - } + return this +} - if (typ && normalizeTyp(decoded.header.typ) !== normalizeTyp(typ)) { - throw new JWTClaimInvalid('unexpected "typ" JWT header value', 'typ', 'check_failed') - } +Node.prototype.obj = function obj () { + const state = this._baseState + const args = Array.prototype.slice.call(arguments) - const tolerance = clockTolerance ? secs(clockTolerance) : 0 + state.obj = true - if (!ignoreIat && !('exp' in decoded.payload) && 'iat' in decoded.payload && decoded.payload.iat > unix + tolerance) { - throw new JWTClaimInvalid('"iat" claim timestamp check failed (it should be in the past)', 'iat', 'check_failed') - } + if (args.length !== 0) { this._useArgs(args) } - if (!ignoreNbf && 'nbf' in decoded.payload && decoded.payload.nbf > unix + tolerance) { - throw new JWTClaimInvalid('"nbf" claim timestamp check failed', 'nbf', 'check_failed') - } + return this +} - if (!ignoreExp && 'exp' in decoded.payload && decoded.payload.exp <= unix - tolerance) { - throw new JWTExpired('"exp" claim timestamp check failed', 'exp', 'check_failed') - } +Node.prototype.key = function key (newKey) { + const state = this._baseState - if (maxTokenAge) { - const age = unix - decoded.payload.iat - const max = secs(maxTokenAge) + assert(state.key === null) + state.key = newKey - if (age - tolerance > max) { - throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', 'iat', 'check_failed') - } + return this +} - if (age < 0 - tolerance) { - throw new JWTClaimInvalid('"iat" claim timestamp check failed (it should be in the past)', 'iat', 'check_failed') - } - } +Node.prototype.any = function any () { + const state = this._baseState - return complete ? decoded : decoded.payload + state.any = true + + return this } +Node.prototype.choice = function choice (obj) { + const state = this._baseState -/***/ }), + assert(state.choice === null) + state.choice = obj + this._useArgs(Object.keys(obj).map(function (key) { + return obj[key] + })) -/***/ 91071: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return this +} -const { getCurves } = __nccwpck_require__(6113) +Node.prototype.contains = function contains (item) { + const state = this._baseState -const curves = new Set() + assert(state.use === null) + state.contains = item -if (getCurves().includes('prime256v1')) { - curves.add('P-256') + return this } -if (getCurves().includes('secp256k1')) { - curves.add('secp256k1') -} +// +// Decoding +// -if (getCurves().includes('secp384r1')) { - curves.add('P-384') -} +Node.prototype._decode = function decode (input, options) { + const state = this._baseState -if (getCurves().includes('secp521r1')) { - curves.add('P-521') -} + // Decode root node + if (state.parent === null) { return input.wrapResult(state.children[0]._decode(input, options)) } -module.exports = curves + let result = state.default + let present = true + let prevKey = null + if (state.key !== null) { prevKey = input.enterKey(state.key) } -/***/ }), + // Check if tag is there + if (state.optional) { + let tag = null + if (state.explicit !== null) { tag = state.explicit } else if (state.implicit !== null) { tag = state.implicit } else if (state.tag !== null) { tag = state.tag } -/***/ 81645: -/***/ ((module) => { + if (tag === null && !state.any) { + // Trial and Error + const save = input.save() + try { + if (state.choice === null) { this._decodeGeneric(state.tag, input, options) } else { this._decodeChoice(input, options) } + present = true + } catch (e) { + present = false + } + input.restore(save) + } else { + present = this._peekTag(input, tag, state.any) -module.exports = new Map() + if (input.isError(present)) { return present } + } + } + // Push object on stack + let prevObj + if (state.obj && present) { prevObj = input.enterObject() } -/***/ }), + if (present) { + // Unwrap explicit values + if (state.explicit !== null) { + const explicit = this._decodeTag(input, state.explicit) + if (input.isError(explicit)) { return explicit } + input = explicit + } -/***/ 47359: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + const start = input.offset -const EC_CURVES = __nccwpck_require__(91071) -const IVLENGTHS = __nccwpck_require__(70589) -const JWA = __nccwpck_require__(22198) -const JWK = __nccwpck_require__(11648) -const KEYLENGTHS = __nccwpck_require__(90244) -const OKP_CURVES = __nccwpck_require__(52438) -const ECDH_DERIVE_LENGTHS = __nccwpck_require__(81645) + // Unwrap implicit and normal values + if (state.use === null && state.choice === null) { + let save + if (state.any) { save = input.save() } + const body = this._decodeTag( + input, + state.implicit !== null ? state.implicit : state.tag, + state.any + ) + if (input.isError(body)) { return body } -module.exports = { - EC_CURVES, - ECDH_DERIVE_LENGTHS, - IVLENGTHS, - JWA, - JWK, - KEYLENGTHS, - OKP_CURVES -} + if (state.any) { result = input.raw(save) } else { input = body } + } + if (options && options.track && state.tag !== null) { options.track(input.path(), start, input.length, 'tagged') } -/***/ }), + if (options && options.track && state.tag !== null) { options.track(input.path(), input.offset, input.length, 'content') } -/***/ 70589: -/***/ ((module) => { + // Select proper method for tag + if (state.any) { + // no-op + } else if (state.choice === null) { + result = this._decodeGeneric(state.tag, input, options) + } else { + result = this._decodeChoice(input, options) + } -module.exports = new Map([ - ['A128CBC-HS256', 128], - ['A128GCM', 96], - ['A128GCMKW', 96], - ['A192CBC-HS384', 128], - ['A192GCM', 96], - ['A192GCMKW', 96], - ['A256CBC-HS512', 128], - ['A256GCM', 96], - ['A256GCMKW', 96] -]) + if (input.isError(result)) { return result } + // Decode children + if (!state.any && state.choice === null && state.children !== null) { + state.children.forEach(function decodeChildren (child) { + // NOTE: We are ignoring errors here, to let parser continue with other + // parts of encoded data + child._decode(input, options) + }) + } -/***/ }), + // Decode contained/encoded by schema, only in bit or octet strings + if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) { + const data = new DecoderBuffer(result) + result = this._getUse(state.contains, input._reporterState.obj) + ._decode(data, options) + } + } -/***/ 22198: -/***/ ((module) => { + // Pop object + if (state.obj && present) { result = input.leaveObject(prevObj) } -module.exports = { - sign: new Map(), - verify: new Map(), - keyManagementEncrypt: new Map(), - keyManagementDecrypt: new Map(), - encrypt: new Map(), - decrypt: new Map() -} + // Set key + if (state.key !== null && (result !== null || present === true)) { input.leaveKey(prevKey, state.key, result) } else if (prevKey !== null) { input.exitKey(prevKey) } + return result +} -/***/ }), +Node.prototype._decodeGeneric = function decodeGeneric (tag, input, options) { + const state = this._baseState -/***/ 11648: -/***/ ((module) => { + if (tag === 'seq' || tag === 'set') { return null } + if (tag === 'seqof' || tag === 'setof') { return this._decodeList(input, tag, state.args[0], options) } else if (/str$/.test(tag)) { return this._decodeStr(input, tag, options) } else if (tag === 'objid' && state.args) { return this._decodeObjid(input, state.args[0], state.args[1], options) } else if (tag === 'objid') { return this._decodeObjid(input, null, null, options) } else if (tag === 'gentime' || tag === 'utctime') { return this._decodeTime(input, tag, options) } else if (tag === 'null_') { return this._decodeNull(input, options) } else if (tag === 'bool') { return this._decodeBool(input, options) } else if (tag === 'objDesc') { return this._decodeStr(input, tag, options) } else if (tag === 'int' || tag === 'enum') { return this._decodeInt(input, state.args && state.args[0], options) } -module.exports = { - oct: { - decrypt: {}, - deriveKey: {}, - encrypt: {}, - sign: {}, - unwrapKey: {}, - verify: {}, - wrapKey: {} - }, - EC: { - decrypt: {}, - deriveKey: {}, - encrypt: {}, - sign: {}, - unwrapKey: {}, - verify: {}, - wrapKey: {} - }, - RSA: { - decrypt: {}, - deriveKey: {}, - encrypt: {}, - sign: {}, - unwrapKey: {}, - verify: {}, - wrapKey: {} - }, - OKP: { - decrypt: {}, - deriveKey: {}, - encrypt: {}, - sign: {}, - unwrapKey: {}, - verify: {}, - wrapKey: {} + if (state.use !== null) { + return this._getUse(state.use, input._reporterState.obj) + ._decode(input, options) + } else { + return input.error(`unknown tag: ${tag}`) } } +Node.prototype._getUse = function _getUse (entity, obj) { + const state = this._baseState + // Create altered use decoder if implicit is set + state.useDecoder = this._use(entity, obj) + assert(state.useDecoder._baseState.parent === null) + state.useDecoder = state.useDecoder._baseState.children[0] + if (state.implicit !== state.useDecoder._baseState.implicit) { + state.useDecoder = state.useDecoder.clone() + state.useDecoder._baseState.implicit = state.implicit + } + return state.useDecoder +} -/***/ }), - -/***/ 90244: -/***/ ((module) => { - -module.exports = new Map([ - ['A128CBC-HS256', 256], - ['A128GCM', 128], - ['A192CBC-HS384', 384], - ['A192GCM', 192], - ['A256CBC-HS512', 512], - ['A256GCM', 256] -]) - +Node.prototype._decodeChoice = function decodeChoice (input, options) { + const state = this._baseState + let result = null + let match = false -/***/ }), + Object.keys(state.choice).some(function (key) { + const save = input.save() + const node = state.choice[key] + try { + const value = node._decode(input, options) + if (input.isError(value)) { return false } -/***/ 52438: -/***/ ((module) => { + result = { type: key, value: value } + match = true + } catch (e) { + input.restore(save) + return false + } + return true + }, this) -const curves = new Set(['Ed25519']) + if (!match) { return input.error('Choice not matched') } -if (!('electron' in process.versions)) { - curves.add('Ed448') - curves.add('X25519') - curves.add('X448') + return result } -module.exports = curves +// +// Encoding +// +Node.prototype._createEncoderBuffer = function createEncoderBuffer (data) { + return new EncoderBuffer(data, this.reporter) +} -/***/ }), +Node.prototype._encode = function encode (data, reporter, parent) { + const state = this._baseState + if (state.default !== null && state.default === data) { return } -/***/ 49609: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + const result = this._encodeValue(data, reporter, parent) + if (result === undefined) { return } -/* eslint-disable max-classes-per-file */ + if (this._skipDefault(result, reporter, parent)) { return } -const { inspect } = __nccwpck_require__(73837); -const stdhttp = __nccwpck_require__(13685); -const crypto = __nccwpck_require__(6113); -const { strict: assert } = __nccwpck_require__(39491); -const querystring = __nccwpck_require__(63477); -const url = __nccwpck_require__(57310); + return result +} -const { ParseError } = __nccwpck_require__(93061); -const jose = __nccwpck_require__(87115); -const tokenHash = __nccwpck_require__(1270); +Node.prototype._encodeValue = function encode (data, reporter, parent) { + const state = this._baseState -const base64url = __nccwpck_require__(23570); -const defaults = __nccwpck_require__(44129); -const { assertSigningAlgValuesSupport, assertIssuerConfiguration } = __nccwpck_require__(68973); -const pick = __nccwpck_require__(70260); -const isPlainObject = __nccwpck_require__(89717); -const processResponse = __nccwpck_require__(59980); -const TokenSet = __nccwpck_require__(14974); -const { OPError, RPError } = __nccwpck_require__(31151); -const now = __nccwpck_require__(24393); -const { random } = __nccwpck_require__(65894); -const request = __nccwpck_require__(8048); -const { - CALLBACK_PROPERTIES, CLIENT_DEFAULTS, JWT_CONTENT, CLOCK_TOLERANCE, -} = __nccwpck_require__(6144); -const issuerRegistry = __nccwpck_require__(70011); -const instance = __nccwpck_require__(69020); -const { authenticatedPost, resolveResponseType, resolveRedirectUri } = __nccwpck_require__(26633); -const DeviceFlowHandle = __nccwpck_require__(60679); + // Decode root node + if (state.parent === null) { return state.children[0]._encode(data, reporter || new Reporter()) } -function pickCb(input) { - return pick(input, ...CALLBACK_PROPERTIES); -} + let result = null -function authorizationHeaderValue(token, tokenType = 'Bearer') { - return `${tokenType} ${token}`; -} + // Set reporter to share it with a child class + this.reporter = reporter -function cleanUpClaims(claims) { - if (Object.keys(claims._claim_names).length === 0) { - delete claims._claim_names; - } - if (Object.keys(claims._claim_sources).length === 0) { - delete claims._claim_sources; + // Check if data is there + if (state.optional && data === undefined) { + if (state.default !== null) { data = state.default } else { return } } -} -function assignClaim(target, source, sourceName, throwOnMissing = true) { - return ([claim, inSource]) => { - if (inSource === sourceName) { - if (throwOnMissing && source[claim] === undefined) { - throw new RPError(`expected claim "${claim}" in "${sourceName}"`); - } else if (source[claim] !== undefined) { - target[claim] = source[claim]; - } - delete target._claim_names[claim]; - } - }; -} + // Encode children first + let content = null + let primitive = false + if (state.any) { + // Anything that was given is translated to buffer + result = this._createEncoderBuffer(data) + } else if (state.choice) { + result = this._encodeChoice(data, reporter) + } else if (state.contains) { + content = this._getUse(state.contains, parent)._encode(data, reporter) + primitive = true + } else if (state.children) { + content = state.children.map(function (child) { + if (child._baseState.tag === 'null_') { return child._encode(null, reporter, data) } -function verifyPresence(payload, jwt, prop) { - if (payload[prop] === undefined) { - throw new RPError({ - message: `missing required JWT property ${prop}`, - jwt, - }); - } -} + if (child._baseState.key === null) { return reporter.error('Child should have a key') } + const prevKey = reporter.enterKey(child._baseState.key) -function authorizationParams(params) { - const authParams = { - client_id: this.client_id, - scope: 'openid', - response_type: resolveResponseType.call(this), - redirect_uri: resolveRedirectUri.call(this), - ...params, - }; + if (typeof data !== 'object') { return reporter.error('Child expected, but input is not object') } - Object.entries(authParams).forEach(([key, value]) => { - if (value === null || value === undefined) { - delete authParams[key]; - } else if (key === 'claims' && typeof value === 'object') { - authParams[key] = JSON.stringify(value); - } else if (key === 'resource' && Array.isArray(value)) { - authParams[key] = value; - } else if (typeof value !== 'string') { - authParams[key] = String(value); - } - }); + const res = child._encode(data[child._baseState.key], reporter, data) + reporter.leaveKey(prevKey) - return authParams; -} + return res + }, this).filter(function (child) { + return child + }) + content = this._createEncoderBuffer(content) + } else { + if (state.tag === 'seqof' || state.tag === 'setof') { + if (!(state.args && state.args.length === 1)) { return reporter.error(`Too many args for: ${state.tag}`) } -async function claimJWT(label, jwt) { - try { - const { header, payload } = jose.JWT.decode(jwt, { complete: true }); - const { iss } = payload; + if (!Array.isArray(data)) { return reporter.error('seqof/setof, but data is not Array') } - if (header.alg === 'none') { - return payload; - } + const child = this.clone() + child._baseState.implicit = null + content = this._createEncoderBuffer(data.map(function (item) { + const state = this._baseState - let key; - if (!iss || iss === this.issuer.issuer) { - key = await this.issuer.queryKeyStore(header); - } else if (issuerRegistry.has(iss)) { - key = await issuerRegistry.get(iss).queryKeyStore(header); - } else { - const discovered = await this.issuer.constructor.discover(iss); - key = await discovered.queryKeyStore(header); - } - return jose.JWT.verify(jwt, key); - } catch (err) { - if (err instanceof RPError || err instanceof OPError || err.name === 'AggregateError') { - throw err; + return this._getUse(state.args[0], data)._encode(item, reporter) + }, child)) + } else if (state.use !== null) { + result = this._getUse(state.use, parent)._encode(data, reporter) } else { - throw new RPError({ - printf: ['failed to validate the %s JWT (%s: %s)', label, err.name, err.message], - jwt, - }); + content = this._encodePrimitive(state.tag, data) + primitive = true } } -} -function getKeystore(jwks) { - if (!isPlainObject(jwks) || !Array.isArray(jwks.keys) || jwks.keys.some((k) => !isPlainObject(k) || !('kty' in k))) { - throw new TypeError('jwks must be a JSON Web Key Set formatted object'); - } + // Encode data itself + if (!state.any && state.choice === null) { + const tag = state.implicit !== null ? state.implicit : state.tag + const cls = state.implicit === null ? 'universal' : 'context' - // eslint-disable-next-line no-restricted-syntax - for (const jwk of jwks.keys) { - if (jwk.kid === undefined) { - jwk.kid = `DONOTUSE.${random()}`; + if (tag === null) { + if (state.use === null) { reporter.error('Tag could be omitted only for .use()') } + } else { + if (state.use === null) { result = this._encodeComposite(tag, primitive, cls, content) } } } - const keystore = jose.JWKS.asKeyStore(jwks); - if (keystore.all().some((key) => key.type !== 'private')) { - throw new TypeError('jwks must only contain private keys'); - } - return keystore; -} + // Wrap in explicit + if (state.explicit !== null) { result = this._encodeComposite(state.explicit, false, 'context', result) } -// if an OP doesnt support client_secret_basic but supports client_secret_post, use it instead -// this is in place to take care of most common pitfalls when first using discovered Issuers without -// the support for default values defined by Discovery 1.0 -function checkBasicSupport(client, metadata, properties) { - try { - const supported = client.issuer.token_endpoint_auth_methods_supported; - if (!supported.includes(properties.token_endpoint_auth_method)) { - if (supported.includes('client_secret_post')) { - properties.token_endpoint_auth_method = 'client_secret_post'; - } - } - } catch (err) {} + return result } -function handleCommonMistakes(client, metadata, properties) { - if (!metadata.token_endpoint_auth_method) { // if no explicit value was provided - checkBasicSupport(client, metadata, properties); - } - - // :fp: c'mon people... RTFM - if (metadata.redirect_uri) { - if (metadata.redirect_uris) { - throw new TypeError('provide a redirect_uri or redirect_uris, not both'); - } - properties.redirect_uris = [metadata.redirect_uri]; - delete properties.redirect_uri; - } +Node.prototype._encodeChoice = function encodeChoice (data, reporter) { + const state = this._baseState - if (metadata.response_type) { - if (metadata.response_types) { - throw new TypeError('provide a response_type or response_types, not both'); - } - properties.response_types = [metadata.response_type]; - delete properties.response_type; + const node = state.choice[data.type] + if (!node) { + assert( + false, + `${data.type} not found in ${JSON.stringify(Object.keys(state.choice))}` + ) } + return node._encode(data.value, reporter) } -function getDefaultsForEndpoint(endpoint, issuer, properties) { - if (!issuer[`${endpoint}_endpoint`]) return; +Node.prototype._encodePrimitive = function encodePrimitive (tag, data) { + const state = this._baseState - const tokenEndpointAuthMethod = properties.token_endpoint_auth_method; - const tokenEndpointAuthSigningAlg = properties.token_endpoint_auth_signing_alg; + if (/str$/.test(tag)) { return this._encodeStr(data, tag) } else if (tag === 'objid' && state.args) { return this._encodeObjid(data, state.reverseArgs[0], state.args[1]) } else if (tag === 'objid') { return this._encodeObjid(data, null, null) } else if (tag === 'gentime' || tag === 'utctime') { return this._encodeTime(data, tag) } else if (tag === 'null_') { return this._encodeNull() } else if (tag === 'int' || tag === 'enum') { return this._encodeInt(data, state.args && state.reverseArgs[0]) } else if (tag === 'bool') { return this._encodeBool(data) } else if (tag === 'objDesc') { return this._encodeStr(data, tag) } else { throw new Error(`Unsupported tag: ${tag}`) } +} - const eam = `${endpoint}_endpoint_auth_method`; - const easa = `${endpoint}_endpoint_auth_signing_alg`; +Node.prototype._isNumstr = function isNumstr (str) { + return /^[0-9 ]*$/.test(str) +} - if (properties[eam] === undefined && properties[easa] === undefined) { - if (tokenEndpointAuthMethod !== undefined) { - properties[eam] = tokenEndpointAuthMethod; - } - if (tokenEndpointAuthSigningAlg !== undefined) { - properties[easa] = tokenEndpointAuthSigningAlg; - } - } +Node.prototype._isPrintstr = function isPrintstr (str) { + return /^[A-Za-z0-9 '()+,-./:=?]*$/.test(str) } -class BaseClient {} +module.exports = Node -module.exports = (issuer, aadIssValidation = false) => class Client extends BaseClient { - /** - * @name constructor - * @api public - */ - constructor(metadata = {}, jwks, options) { - super(); - if (typeof metadata.client_id !== 'string' || !metadata.client_id) { - throw new TypeError('client_id is required'); - } +/***/ }), - const properties = { ...CLIENT_DEFAULTS, ...metadata }; +/***/ 93026: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - handleCommonMistakes(this, metadata, properties); +const { inherits } = __nccwpck_require__(73837) - assertSigningAlgValuesSupport('token', this.issuer, properties); +function Reporter (options) { + this._reporterState = { + obj: null, + path: [], + options: options || {}, + errors: [] + } +} - ['introspection', 'revocation'].forEach((endpoint) => { - getDefaultsForEndpoint(endpoint, this.issuer, properties); - assertSigningAlgValuesSupport(endpoint, this.issuer, properties); - }); +Reporter.prototype.isError = function isError (obj) { + return obj instanceof ReporterError +} - Object.entries(properties).forEach(([key, value]) => { - instance(this).get('metadata').set(key, value); - if (!this[key]) { - Object.defineProperty(this, key, { - get() { return instance(this).get('metadata').get(key); }, - enumerable: true, - }); - } - }); +Reporter.prototype.save = function save () { + const state = this._reporterState - if (jwks !== undefined) { - const keystore = getKeystore.call(this, jwks); - instance(this).set('keystore', keystore); - } + return { obj: state.obj, pathLen: state.path.length } +} - if (options !== undefined) { - instance(this).set('options', options); - } +Reporter.prototype.restore = function restore (data) { + const state = this._reporterState - this[CLOCK_TOLERANCE] = 0; - } + state.obj = data.obj + state.path = state.path.slice(0, data.pathLen) +} - /** - * @name authorizationUrl - * @api public - */ - authorizationUrl(params = {}) { - if (!isPlainObject(params)) { - throw new TypeError('params must be a plain object'); - } - assertIssuerConfiguration(this.issuer, 'authorization_endpoint'); - const target = url.parse(this.issuer.authorization_endpoint, true); - target.search = null; - target.query = { - ...target.query, - ...authorizationParams.call(this, params), - }; - return url.format(target); - } +Reporter.prototype.enterKey = function enterKey (key) { + return this._reporterState.path.push(key) +} - /** - * @name authorizationPost - * @api public - */ - authorizationPost(params = {}) { - if (!isPlainObject(params)) { - throw new TypeError('params must be a plain object'); - } - const inputs = authorizationParams.call(this, params); - const formInputs = Object.keys(inputs) - .map((name) => ``).join('\n'); +Reporter.prototype.exitKey = function exitKey (index) { + const state = this._reporterState - return ` - - Requesting Authorization - - -
- ${formInputs} -
- -`; - } + state.path = state.path.slice(0, index - 1) +} - /** - * @name endSessionUrl - * @api public - */ - endSessionUrl(params = {}) { - assertIssuerConfiguration(this.issuer, 'end_session_endpoint'); +Reporter.prototype.leaveKey = function leaveKey (index, key, value) { + const state = this._reporterState - const { - 0: postLogout, - length, - } = this.post_logout_redirect_uris || []; + this.exitKey(index) + if (state.obj !== null) { state.obj[key] = value } +} - const { - post_logout_redirect_uri = length === 1 ? postLogout : undefined, - } = params; +Reporter.prototype.path = function path () { + return this._reporterState.path.join('/') +} - let hint = params.id_token_hint; +Reporter.prototype.enterObject = function enterObject () { + const state = this._reporterState - if (hint instanceof TokenSet) { - if (!hint.id_token) { - throw new TypeError('id_token not present in TokenSet'); - } - hint = hint.id_token; - } + const prev = state.obj + state.obj = {} + return prev +} - const target = url.parse(this.issuer.end_session_endpoint, true); - target.search = null; - target.query = { - ...params, - ...target.query, - ...{ - post_logout_redirect_uri, - id_token_hint: hint, - }, - }; +Reporter.prototype.leaveObject = function leaveObject (prev) { + const state = this._reporterState - Object.entries(target.query).forEach(([key, value]) => { - if (value === null || value === undefined) { - delete target.query[key]; - } - }); + const now = state.obj + state.obj = prev + return now +} - return url.format(target); +Reporter.prototype.error = function error (msg) { + let err + const state = this._reporterState + + const inherited = msg instanceof ReporterError + if (inherited) { + err = msg + } else { + err = new ReporterError(state.path.map(function (elem) { + return `[${JSON.stringify(elem)}]` + }).join(''), msg.message || msg, msg.stack) } - /** - * @name callbackParams - * @api public - */ - callbackParams(input) { // eslint-disable-line class-methods-use-this - const isIncomingMessage = input instanceof stdhttp.IncomingMessage - || (input && input.method && input.url); - const isString = typeof input === 'string'; + if (!state.options.partial) { throw err } - if (!isString && !isIncomingMessage) { - throw new TypeError('#callbackParams only accepts string urls, http.IncomingMessage or a lookalike'); - } + if (!inherited) { state.errors.push(err) } - if (isIncomingMessage) { - switch (input.method) { - case 'GET': - return pickCb(url.parse(input.url, true).query); - case 'POST': - if (input.body === undefined) { - throw new TypeError('incoming message body missing, include a body parser prior to this method call'); - } - switch (typeof input.body) { - case 'object': - case 'string': - if (Buffer.isBuffer(input.body)) { - return pickCb(querystring.parse(input.body.toString('utf-8'))); - } - if (typeof input.body === 'string') { - return pickCb(querystring.parse(input.body)); - } + return err +} - return pickCb(input.body); - default: - throw new TypeError('invalid IncomingMessage body object'); - } - default: - throw new TypeError('invalid IncomingMessage method'); - } - } else { - return pickCb(url.parse(input, true).query); - } - } +Reporter.prototype.wrapResult = function wrapResult (result) { + const state = this._reporterState + if (!state.options.partial) { return result } - /** - * @name callback - * @api public - */ - async callback( - redirectUri, - parameters, - checks = {}, - { exchangeBody, clientAssertionPayload, DPoP } = {}, - ) { - let params = pickCb(parameters); + return { + result: this.isError(result) ? null : result, + errors: state.errors + } +} - if (checks.jarm && !('response' in parameters)) { - throw new RPError({ - message: 'expected a JARM response', - checks, - params, - }); - } else if ('response' in parameters) { - const decrypted = await this.decryptJARM(params.response); - params = await this.validateJARM(decrypted); - } +function ReporterError (path, msg) { + this.path = path + this.rethrow(msg) +} +inherits(ReporterError, Error) - if (this.default_max_age && !checks.max_age) { - checks.max_age = this.default_max_age; - } +ReporterError.prototype.rethrow = function rethrow (msg) { + this.message = `${msg} at: ${this.path || '(shallow)'}` + if (Error.captureStackTrace) { Error.captureStackTrace(this, ReporterError) } - if (params.state && !checks.state) { - throw new TypeError('checks.state argument is missing'); + if (!this.stack) { + try { + // IE only adds stack when thrown + throw new Error(this.message) + } catch (e) { + this.stack = e.stack } + } + return this +} - if (!params.state && checks.state) { - throw new RPError({ - message: 'state missing from the response', - checks, - params, - }); - } +exports.Reporter = Reporter - if (checks.state !== params.state) { - throw new RPError({ - printf: ['state mismatch, expected %s, got: %s', checks.state, params.state], - checks, - params, - }); - } - if (params.error) { - throw new OPError(params); - } +/***/ }), - const RESPONSE_TYPE_REQUIRED_PARAMS = { - code: ['code'], - id_token: ['id_token'], - token: ['access_token', 'token_type'], - }; +/***/ 96018: +/***/ ((__unused_webpack_module, exports) => { - if (checks.response_type) { - for (const type of checks.response_type.split(' ')) { // eslint-disable-line no-restricted-syntax - if (type === 'none') { - if (params.code || params.id_token || params.access_token) { - throw new RPError({ - message: 'unexpected params encountered for "none" response', - checks, - params, - }); - } - } else { - for (const param of RESPONSE_TYPE_REQUIRED_PARAMS[type]) { // eslint-disable-line no-restricted-syntax, max-len - if (!params[param]) { - throw new RPError({ - message: `${param} missing from response`, - checks, - params, - }); - } - } - } - } - } +// Helper +function reverse (map) { + const res = {} - if (params.id_token) { - const tokenset = new TokenSet(params); - await this.decryptIdToken(tokenset); - await this.validateIdToken(tokenset, checks.nonce, 'authorization', checks.max_age, checks.state); + Object.keys(map).forEach(function (key) { + // Convert key to integer if it is stringified + if ((key | 0) == key) { key = key | 0 } // eslint-disable-line eqeqeq - if (!params.code) { - return tokenset; - } - } + const value = map[key] + res[value] = key + }) - if (params.code) { - const tokenset = await this.grant({ - ...exchangeBody, - grant_type: 'authorization_code', - code: params.code, - redirect_uri: redirectUri, - code_verifier: checks.code_verifier, - }, { clientAssertionPayload, DPoP }); + return res +} - await this.decryptIdToken(tokenset); - await this.validateIdToken(tokenset, checks.nonce, 'token', checks.max_age); +exports.tagClass = { + 0: 'universal', + 1: 'application', + 2: 'context', + 3: 'private' +} +exports.tagClassByName = reverse(exports.tagClass) - if (params.session_state) { - tokenset.session_state = params.session_state; - } +exports.tag = { + 0x00: 'end', + 0x01: 'bool', + 0x02: 'int', + 0x03: 'bitstr', + 0x04: 'octstr', + 0x05: 'null_', + 0x06: 'objid', + 0x07: 'objDesc', + 0x08: 'external', + 0x09: 'real', + 0x0a: 'enum', + 0x0b: 'embed', + 0x0c: 'utf8str', + 0x0d: 'relativeOid', + 0x10: 'seq', + 0x11: 'set', + 0x12: 'numstr', + 0x13: 'printstr', + 0x14: 't61str', + 0x15: 'videostr', + 0x16: 'ia5str', + 0x17: 'utctime', + 0x18: 'gentime', + 0x19: 'graphstr', + 0x1a: 'iso646str', + 0x1b: 'genstr', + 0x1c: 'unistr', + 0x1d: 'charstr', + 0x1e: 'bmpstr' +} +exports.tagByName = reverse(exports.tag) - return tokenset; - } - return new TokenSet(params); - } +/***/ }), - /** - * @name oauthCallback - * @api public - */ - async oauthCallback( - redirectUri, - parameters, - checks = {}, - { exchangeBody, clientAssertionPayload, DPoP } = {}, - ) { - let params = pickCb(parameters); +/***/ 90998: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (checks.jarm && !('response' in parameters)) { - throw new RPError({ - message: 'expected a JARM response', - checks, - params, - }); - } else if ('response' in parameters) { - const decrypted = await this.decryptJARM(params.response); - params = await this.validateJARM(decrypted); - } +module.exports = { + der: __nccwpck_require__(96018) +} - if (params.state && !checks.state) { - throw new TypeError('checks.state argument is missing'); - } - if (!params.state && checks.state) { - throw new RPError({ - message: 'state missing from the response', - checks, - params, - }); - } +/***/ }), - if (checks.state !== params.state) { - throw new RPError({ - printf: ['state mismatch, expected %s, got: %s', checks.state, params.state], - checks, - params, - }); - } +/***/ 44798: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (params.error) { - throw new OPError(params); - } +/* global BigInt */ +const { inherits } = __nccwpck_require__(73837) - const RESPONSE_TYPE_REQUIRED_PARAMS = { - code: ['code'], - token: ['access_token', 'token_type'], - }; +const { DecoderBuffer } = __nccwpck_require__(28424) +const Node = __nccwpck_require__(48674) - if (checks.response_type) { - for (const type of checks.response_type.split(' ')) { // eslint-disable-line no-restricted-syntax - if (type === 'none') { - if (params.code || params.id_token || params.access_token) { - throw new RPError({ - message: 'unexpected params encountered for "none" response', - checks, - params, - }); - } - } +// Import DER constants +const der = __nccwpck_require__(96018) - if (RESPONSE_TYPE_REQUIRED_PARAMS[type]) { - for (const param of RESPONSE_TYPE_REQUIRED_PARAMS[type]) { // eslint-disable-line no-restricted-syntax, max-len - if (!params[param]) { - throw new RPError({ - message: `${param} missing from response`, - checks, - params, - }); - } - } - } - } - } +function DERDecoder (entity) { + this.enc = 'der' + this.name = entity.name + this.entity = entity - if (params.code) { - return this.grant({ - ...exchangeBody, - grant_type: 'authorization_code', - code: params.code, - redirect_uri: redirectUri, - code_verifier: checks.code_verifier, - }, { clientAssertionPayload, DPoP }); - } + // Construct base tree + this.tree = new DERNode() + this.tree._init(entity.body) +} - return new TokenSet(params); +DERDecoder.prototype.decode = function decode (data, options) { + if (!DecoderBuffer.isDecoderBuffer(data)) { + data = new DecoderBuffer(data, options) } - /** - * @name decryptIdToken - * @api private - */ - async decryptIdToken(token) { - if (!this.id_token_encrypted_response_alg) { - return token; - } + return this.tree._decode(data, options) +} - let idToken = token; +// Tree methods - if (idToken instanceof TokenSet) { - if (!idToken.id_token) { - throw new TypeError('id_token not present in TokenSet'); - } - idToken = idToken.id_token; - } +function DERNode (parent) { + Node.call(this, 'der', parent) +} +inherits(DERNode, Node) - const expectedAlg = this.id_token_encrypted_response_alg; - const expectedEnc = this.id_token_encrypted_response_enc; +DERNode.prototype._peekTag = function peekTag (buffer, tag, any) { + if (buffer.isEmpty()) { return false } - const result = await this.decryptJWE(idToken, expectedAlg, expectedEnc); + const state = buffer.save() + const decodedTag = derDecodeTag(buffer, `Failed to peek tag: "${tag}"`) + if (buffer.isError(decodedTag)) { return decodedTag } - if (token instanceof TokenSet) { - token.id_token = result; - return token; - } + buffer.restore(state) - return result; - } + return decodedTag.tag === tag || decodedTag.tagStr === tag || (decodedTag.tagStr + 'of') === tag || any +} - async validateJWTUserinfo(body) { - const expectedAlg = this.userinfo_signed_response_alg; +DERNode.prototype._decodeTag = function decodeTag (buffer, tag, any) { + const decodedTag = derDecodeTag(buffer, + `Failed to decode tag of "${tag}"`) + if (buffer.isError(decodedTag)) { return decodedTag } - return this.validateJWT(body, expectedAlg, []); - } - - /** - * @name decryptJARM - * @api private - */ - async decryptJARM(response) { - if (!this.authorization_encrypted_response_alg) { - return response; - } + let len = derDecodeLen(buffer, + decodedTag.primitive, + `Failed to get length of "${tag}"`) - const expectedAlg = this.authorization_encrypted_response_alg; - const expectedEnc = this.authorization_encrypted_response_enc; + // Failure + if (buffer.isError(len)) { return len } - return this.decryptJWE(response, expectedAlg, expectedEnc); + if (!any && + decodedTag.tag !== tag && + decodedTag.tagStr !== tag && + decodedTag.tagStr + 'of' !== tag) { + return buffer.error(`Failed to match tag: "${tag}"`) } - /** - * @name decryptJWTUserinfo - * @api private - */ - async decryptJWTUserinfo(body) { - if (!this.userinfo_encrypted_response_alg) { - return body; - } - - const expectedAlg = this.userinfo_encrypted_response_alg; - const expectedEnc = this.userinfo_encrypted_response_enc; - - return this.decryptJWE(body, expectedAlg, expectedEnc); - } + if (decodedTag.primitive || len !== null) { return buffer.skip(len, `Failed to match body of: "${tag}"`) } - /** - * @name decryptJWE - * @api private - */ - async decryptJWE(jwe, expectedAlg, expectedEnc = 'A128CBC-HS256') { - const header = JSON.parse(base64url.decode(jwe.split('.')[0])); + // Indefinite length... find END tag + const state = buffer.save() + const res = this._skipUntilEnd( + buffer, + `Failed to skip indefinite length body: "${this.tag}"`) + if (buffer.isError(res)) { return res } - if (header.alg !== expectedAlg) { - throw new RPError({ - printf: ['unexpected JWE alg received, expected %s, got: %s', expectedAlg, header.alg], - jwt: jwe, - }); - } + len = buffer.offset - state.offset + buffer.restore(state) + return buffer.skip(len, `Failed to match body of: "${tag}"`) +} - if (header.enc !== expectedEnc) { - throw new RPError({ - printf: ['unexpected JWE enc received, expected %s, got: %s', expectedEnc, header.enc], - jwt: jwe, - }); - } +DERNode.prototype._skipUntilEnd = function skipUntilEnd (buffer, fail) { + for (;;) { + const tag = derDecodeTag(buffer, fail) + if (buffer.isError(tag)) { return tag } + const len = derDecodeLen(buffer, tag.primitive, fail) + if (buffer.isError(len)) { return len } - let keyOrStore; + let res + if (tag.primitive || len !== null) { res = buffer.skip(len) } else { res = this._skipUntilEnd(buffer, fail) } - if (expectedAlg.match(/^(?:RSA|ECDH)/)) { - keyOrStore = instance(this).get('keystore'); - } else { - keyOrStore = await this.joseSecret(expectedAlg === 'dir' ? expectedEnc : expectedAlg); - } + // Failure + if (buffer.isError(res)) { return res } - const payload = jose.JWE.decrypt(jwe, keyOrStore); - return payload.toString('utf8'); + if (tag.tagStr === 'end') { break } } +} - /** - * @name validateIdToken - * @api private - */ - async validateIdToken(tokenSet, nonce, returnedBy, maxAge, state) { - let idToken = tokenSet; +DERNode.prototype._decodeList = function decodeList (buffer, tag, decoder, + options) { + const result = [] + while (!buffer.isEmpty()) { + const possibleEnd = this._peekTag(buffer, 'end') + if (buffer.isError(possibleEnd)) { return possibleEnd } - const expectedAlg = this.id_token_signed_response_alg; + const res = decoder.decode(buffer, 'der', options) + if (buffer.isError(res) && possibleEnd) { break } + result.push(res) + } + return result +} - const isTokenSet = idToken instanceof TokenSet; +DERNode.prototype._decodeStr = function decodeStr (buffer, tag) { + if (tag === 'bitstr') { + const unused = buffer.readUInt8() + if (buffer.isError(unused)) { return unused } + return { unused: unused, data: buffer.raw() } + } else if (tag === 'bmpstr') { + const raw = buffer.raw() + if (raw.length % 2 === 1) { return buffer.error('Decoding of string type: bmpstr length mismatch') } - if (isTokenSet) { - if (!idToken.id_token) { - throw new TypeError('id_token not present in TokenSet'); - } - idToken = idToken.id_token; + let str = '' + for (let i = 0; i < raw.length / 2; i++) { + str += String.fromCharCode(raw.readUInt16BE(i * 2)) } - - idToken = String(idToken); - - const timestamp = now(); - const { protected: header, payload, key } = await this.validateJWT(idToken, expectedAlg); - - if (maxAge || (maxAge !== null && this.require_auth_time)) { - if (!payload.auth_time) { - throw new RPError({ - message: 'missing required JWT property auth_time', - jwt: idToken, - }); - } - if (typeof payload.auth_time !== 'number') { - throw new RPError({ - message: 'JWT auth_time claim must be a JSON numeric value', - jwt: idToken, - }); - } + return str + } else if (tag === 'numstr') { + const numstr = buffer.raw().toString('ascii') + if (!this._isNumstr(numstr)) { + return buffer.error('Decoding of string type: numstr unsupported characters') } - - if (maxAge && (payload.auth_time + maxAge < timestamp - this[CLOCK_TOLERANCE])) { - throw new RPError({ - printf: ['too much time has elapsed since the last End-User authentication, max_age %i, auth_time: %i, now %i', maxAge, payload.auth_time, timestamp - this[CLOCK_TOLERANCE]], - now: timestamp, - tolerance: this[CLOCK_TOLERANCE], - auth_time: payload.auth_time, - jwt: idToken, - }); + return numstr + } else if (tag === 'octstr') { + return buffer.raw() + } else if (tag === 'objDesc') { + return buffer.raw() + } else if (tag === 'printstr') { + const printstr = buffer.raw().toString('ascii') + if (!this._isPrintstr(printstr)) { + return buffer.error('Decoding of string type: printstr unsupported characters') } + return printstr + } else if (/str$/.test(tag)) { + return buffer.raw().toString() + } else { + return buffer.error(`Decoding of string type: ${tag} unsupported`) + } +} - if (nonce !== null && (payload.nonce || nonce !== undefined) && payload.nonce !== nonce) { - throw new RPError({ - printf: ['nonce mismatch, expected %s, got: %s', nonce, payload.nonce], - jwt: idToken, - }); +DERNode.prototype._decodeObjid = function decodeObjid (buffer, values, relative) { + let result + const identifiers = [] + let ident = 0 + let subident = 0 + while (!buffer.isEmpty()) { + subident = buffer.readUInt8() + ident <<= 7 + ident |= subident & 0x7f + if ((subident & 0x80) === 0) { + identifiers.push(ident) + ident = 0 } + } + if (subident & 0x80) { identifiers.push(ident) } - const fapi = this.constructor.name === 'FAPIClient'; + const first = (identifiers[0] / 40) | 0 + const second = identifiers[0] % 40 - if (returnedBy === 'authorization') { - if (!payload.at_hash && tokenSet.access_token) { - throw new RPError({ - message: 'missing required property at_hash', - jwt: idToken, - }); - } + if (relative) { result = identifiers } else { result = [first, second].concat(identifiers.slice(1)) } - if (!payload.c_hash && tokenSet.code) { - throw new RPError({ - message: 'missing required property c_hash', - jwt: idToken, - }); - } + if (values) { + let tmp = values[result.join(' ')] + if (tmp === undefined) { tmp = values[result.join('.')] } + if (tmp !== undefined) { result = tmp } + } - if (fapi) { - if (!payload.s_hash && (tokenSet.state || state)) { - throw new RPError({ - message: 'missing required property s_hash', - jwt: idToken, - }); - } - } + return result +} - if (payload.s_hash) { - if (!state) { - throw new TypeError('cannot verify s_hash, "checks.state" property not provided'); - } +DERNode.prototype._decodeTime = function decodeTime (buffer, tag) { + const str = buffer.raw().toString() - try { - tokenHash.validate({ claim: 's_hash', source: 'state' }, payload.s_hash, state, header.alg, key && key.crv); - } catch (err) { - throw new RPError({ message: err.message, jwt: idToken }); - } - } - } + let year + let mon + let day + let hour + let min + let sec + if (tag === 'gentime') { + year = str.slice(0, 4) | 0 + mon = str.slice(4, 6) | 0 + day = str.slice(6, 8) | 0 + hour = str.slice(8, 10) | 0 + min = str.slice(10, 12) | 0 + sec = str.slice(12, 14) | 0 + } else if (tag === 'utctime') { + year = str.slice(0, 2) | 0 + mon = str.slice(2, 4) | 0 + day = str.slice(4, 6) | 0 + hour = str.slice(6, 8) | 0 + min = str.slice(8, 10) | 0 + sec = str.slice(10, 12) | 0 + if (year < 70) { year = 2000 + year } else { year = 1900 + year } + } else { + return buffer.error(`Decoding ${tag} time is not supported yet`) + } - if (fapi && payload.iat < timestamp - 3600) { - throw new RPError({ - printf: ['JWT issued too far in the past, now %i, iat %i', timestamp, payload.iat], - now: timestamp, - tolerance: this[CLOCK_TOLERANCE], - iat: payload.iat, - jwt: idToken, - }); - } + return Date.UTC(year, mon - 1, day, hour, min, sec, 0) +} - if (tokenSet.access_token && payload.at_hash !== undefined) { - try { - tokenHash.validate({ claim: 'at_hash', source: 'access_token' }, payload.at_hash, tokenSet.access_token, header.alg, key && key.crv); - } catch (err) { - throw new RPError({ message: err.message, jwt: idToken }); - } - } +DERNode.prototype._decodeNull = function decodeNull () { + return null +} - if (tokenSet.code && payload.c_hash !== undefined) { - try { - tokenHash.validate({ claim: 'c_hash', source: 'code' }, payload.c_hash, tokenSet.code, header.alg, key && key.crv); - } catch (err) { - throw new RPError({ message: err.message, jwt: idToken }); - } - } +DERNode.prototype._decodeBool = function decodeBool (buffer) { + const res = buffer.readUInt8() + if (buffer.isError(res)) { return res } else { return res !== 0 } +} - return tokenSet; - } +DERNode.prototype._decodeInt = function decodeInt (buffer, values) { + // Bigint, return as it is (assume big endian) + const raw = buffer.raw() + let res = BigInt(`0x${raw.toString('hex')}`) - /** - * @name validateJWT - * @api private - */ - async validateJWT(jwt, expectedAlg, required = ['iss', 'sub', 'aud', 'exp', 'iat']) { - const isSelfIssued = this.issuer.issuer === 'https://self-issued.me'; - const timestamp = now(); - let header; - let payload; - try { - ({ header, payload } = jose.JWT.decode(jwt, { complete: true })); - } catch (err) { - throw new RPError({ - printf: ['failed to decode JWT (%s: %s)', err.name, err.message], - jwt, - }); - } + if (values) { + res = values[res.toString(10)] || res + } - if (header.alg !== expectedAlg) { - throw new RPError({ - printf: ['unexpected JWT alg received, expected %s, got: %s', expectedAlg, header.alg], - jwt, - }); - } + return res +} - if (isSelfIssued) { - required = [...required, 'sub_jwk']; // eslint-disable-line no-param-reassign - } +DERNode.prototype._use = function use (entity, obj) { + if (typeof entity === 'function') { entity = entity(obj) } + return entity._getDecoder('der').tree +} - required.forEach(verifyPresence.bind(undefined, payload, jwt)); +// Utility methods - if (payload.iss !== undefined) { - let expectedIss = this.issuer.issuer; +function derDecodeTag (buf, fail) { + let tag = buf.readUInt8(fail) + if (buf.isError(tag)) { return tag } - if (aadIssValidation) { - expectedIss = this.issuer.issuer.replace('{tenantid}', payload.tid); - } + const cls = der.tagClass[tag >> 6] + const primitive = (tag & 0x20) === 0 - if (payload.iss !== expectedIss) { - throw new RPError({ - printf: ['unexpected iss value, expected %s, got: %s', expectedIss, payload.iss], - jwt, - }); - } - } + // Multi-octet tag - load + if ((tag & 0x1f) === 0x1f) { + let oct = tag + tag = 0 + while ((oct & 0x80) === 0x80) { + oct = buf.readUInt8(fail) + if (buf.isError(oct)) { return oct } - if (payload.iat !== undefined) { - if (typeof payload.iat !== 'number') { - throw new RPError({ - message: 'JWT iat claim must be a JSON numeric value', - jwt, - }); - } + tag <<= 7 + tag |= oct & 0x7f } + } else { + tag &= 0x1f + } + const tagStr = der.tag[tag] - if (payload.nbf !== undefined) { - if (typeof payload.nbf !== 'number') { - throw new RPError({ - message: 'JWT nbf claim must be a JSON numeric value', - jwt, - }); - } - if (payload.nbf > timestamp + this[CLOCK_TOLERANCE]) { - throw new RPError({ - printf: ['JWT not active yet, now %i, nbf %i', timestamp + this[CLOCK_TOLERANCE], payload.nbf], - now: timestamp, - tolerance: this[CLOCK_TOLERANCE], - nbf: payload.nbf, - jwt, - }); - } - } + return { + cls: cls, + primitive: primitive, + tag: tag, + tagStr: tagStr + } +} - if (payload.exp !== undefined) { - if (typeof payload.exp !== 'number') { - throw new RPError({ - message: 'JWT exp claim must be a JSON numeric value', - jwt, - }); - } - if (timestamp - this[CLOCK_TOLERANCE] >= payload.exp) { - throw new RPError({ - printf: ['JWT expired, now %i, exp %i', timestamp - this[CLOCK_TOLERANCE], payload.exp], - now: timestamp, - tolerance: this[CLOCK_TOLERANCE], - exp: payload.exp, - jwt, - }); - } - } +function derDecodeLen (buf, primitive, fail) { + let len = buf.readUInt8(fail) + if (buf.isError(len)) { return len } - if (payload.aud !== undefined) { - if (Array.isArray(payload.aud)) { - if (payload.aud.length > 1 && !payload.azp) { - throw new RPError({ - message: 'missing required JWT property azp', - jwt, - }); - } + // Indefinite form + if (!primitive && len === 0x80) { return null } - if (!payload.aud.includes(this.client_id)) { - throw new RPError({ - printf: ['aud is missing the client_id, expected %s to be included in %j', this.client_id, payload.aud], - jwt, - }); - } - } else if (payload.aud !== this.client_id) { - throw new RPError({ - printf: ['aud mismatch, expected %s, got: %s', this.client_id, payload.aud], - jwt, - }); - } - } + // Definite form + if ((len & 0x80) === 0) { + // Short form + return len + } - if (payload.azp !== undefined) { - let { additionalAuthorizedParties } = instance(this).get('options') || {}; + // Long form + const num = len & 0x7f + if (num > 4) { return buf.error('length octect is too long') } - if (typeof additionalAuthorizedParties === 'string') { - additionalAuthorizedParties = [this.client_id, additionalAuthorizedParties]; - } else if (Array.isArray(additionalAuthorizedParties)) { - additionalAuthorizedParties = [this.client_id, ...additionalAuthorizedParties]; - } else { - additionalAuthorizedParties = [this.client_id]; - } + len = 0 + for (let i = 0; i < num; i++) { + len <<= 8 + const j = buf.readUInt8(fail) + if (buf.isError(j)) { return j } + len |= j + } - if (!additionalAuthorizedParties.includes(payload.azp)) { - throw new RPError({ - printf: ['azp mismatch, got: %s', payload.azp], - jwt, - }); - } - } + return len +} - let key; +module.exports = DERDecoder - if (isSelfIssued) { - try { - assert(isPlainObject(payload.sub_jwk)); - key = jose.JWK.asKey(payload.sub_jwk); - assert.equal(key.type, 'public'); - } catch (err) { - throw new RPError({ - message: 'failed to use sub_jwk claim as an asymmetric JSON Web Key', - jwt, - }); - } - if (key.thumbprint !== payload.sub) { - throw new RPError({ - message: 'failed to match the subject with sub_jwk', - jwt, - }); - } - } else if (header.alg.startsWith('HS')) { - key = await this.joseSecret(); - } else if (header.alg !== 'none') { - key = await this.issuer.queryKeyStore(header); - } - if (!key && header.alg === 'none') { - return { protected: header, payload }; - } +/***/ }), - try { - return { - ...jose.JWS.verify(jwt, key, { complete: true }), - payload, - }; - } catch (err) { - throw new RPError({ - message: 'failed to validate JWT signature', - jwt, - }); - } - } +/***/ 5017: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * @name refresh - * @api public - */ - async refresh(refreshToken, { exchangeBody, clientAssertionPayload, DPoP } = {}) { - let token = refreshToken; +module.exports = { + der: __nccwpck_require__(44798), + pem: __nccwpck_require__(33956) +} - if (token instanceof TokenSet) { - if (!token.refresh_token) { - throw new TypeError('refresh_token not present in TokenSet'); - } - token = token.refresh_token; - } - const tokenset = await this.grant({ - ...exchangeBody, - grant_type: 'refresh_token', - refresh_token: String(token), - }, { clientAssertionPayload, DPoP }); +/***/ }), - if (tokenset.id_token) { - await this.decryptIdToken(tokenset); - await this.validateIdToken(tokenset, null, 'token', null); +/***/ 33956: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (refreshToken instanceof TokenSet && refreshToken.id_token) { - const expectedSub = refreshToken.claims().sub; - const actualSub = tokenset.claims().sub; - if (actualSub !== expectedSub) { - throw new RPError({ - printf: ['sub mismatch, expected %s, got: %s', expectedSub, actualSub], - jwt: tokenset.id_token, - }); - } - } - } +const { inherits } = __nccwpck_require__(73837) - return tokenset; - } +const DERDecoder = __nccwpck_require__(44798) - async requestResource( - resourceUrl, - accessToken, - { - method, - headers, - body, - DPoP, - // eslint-disable-next-line no-nested-ternary - tokenType = DPoP ? 'DPoP' : accessToken instanceof TokenSet ? accessToken.token_type : 'Bearer', - } = {}, - ) { - if (accessToken instanceof TokenSet) { - if (!accessToken.access_token) { - throw new TypeError('access_token not present in TokenSet'); - } - accessToken = accessToken.access_token; // eslint-disable-line no-param-reassign - } +function PEMDecoder (entity) { + DERDecoder.call(this, entity) + this.enc = 'pem' +} +inherits(PEMDecoder, DERDecoder) - const requestOpts = { - headers: { - Authorization: authorizationHeaderValue(accessToken, tokenType), - ...headers, - }, - body, - }; +PEMDecoder.prototype.decode = function decode (data, options) { + const lines = data.toString().split(/[\r\n]+/g) - const mTLS = !!this.tls_client_certificate_bound_access_tokens; + const label = options.label.toUpperCase() - return request.call(this, { - ...requestOpts, - responseType: 'buffer', - method, - url: resourceUrl, - }, { accessToken, mTLS, DPoP }); - } + const re = /^-----(BEGIN|END) ([^-]+)-----$/ + let start = -1 + let end = -1 + for (let i = 0; i < lines.length; i++) { + const match = lines[i].match(re) + if (match === null) { continue } - /** - * @name userinfo - * @api public - */ - async userinfo(accessToken, { - method = 'GET', via = 'header', tokenType, params, DPoP, - } = {}) { - assertIssuerConfiguration(this.issuer, 'userinfo_endpoint'); - const options = { - tokenType, - method: String(method).toUpperCase(), - DPoP, - }; + if (match[2] !== label) { continue } - if (options.method !== 'GET' && options.method !== 'POST') { - throw new TypeError('#userinfo() method can only be POST or a GET'); + if (start === -1) { + if (match[1] !== 'BEGIN') { break } + start = i + } else { + if (match[1] !== 'END') { break } + end = i + break } + } + if (start === -1 || end === -1) { throw new Error(`PEM section not found for: ${label}`) } - if (via === 'query' && options.method !== 'GET') { - throw new TypeError('userinfo endpoints will only parse query strings for GET requests'); - } else if (via === 'body' && options.method !== 'POST') { - throw new TypeError('can only send body on POST'); - } + const base64 = lines.slice(start + 1, end).join('') + // Remove excessive symbols + base64.replace(/[^a-z0-9+/=]+/gi, '') - const jwt = !!(this.userinfo_signed_response_alg || this.userinfo_encrypted_response_alg); + const input = Buffer.from(base64, 'base64') + return DERDecoder.prototype.decode.call(this, input, options) +} - if (jwt) { - options.headers = { Accept: 'application/jwt' }; - } else { - options.headers = { Accept: 'application/json' }; - } +module.exports = PEMDecoder - const mTLS = !!this.tls_client_certificate_bound_access_tokens; - let targetUrl; - if (mTLS && this.issuer.mtls_endpoint_aliases) { - targetUrl = this.issuer.mtls_endpoint_aliases.userinfo_endpoint; - } +/***/ }), - targetUrl = new url.URL(targetUrl || this.issuer.userinfo_endpoint); +/***/ 20846: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // when via is not header we clear the Authorization header and add either - // query string parameters or urlencoded body access_token parameter - if (via === 'query') { - options.headers.Authorization = undefined; - targetUrl.searchParams.append('access_token', accessToken instanceof TokenSet ? accessToken.access_token : accessToken); - } else if (via === 'body') { - options.headers.Authorization = undefined; - options.headers['Content-Type'] = 'application/x-www-form-urlencoded'; - options.body = new url.URLSearchParams(); - options.body.append('access_token', accessToken instanceof TokenSet ? accessToken.access_token : accessToken); - } +/* global BigInt */ +const { inherits } = __nccwpck_require__(73837) - // handle additional parameters, GET via querystring, POST via urlencoded body - if (params) { - if (options.method === 'GET') { - Object.entries(params).forEach(([key, value]) => { - targetUrl.searchParams.append(key, value); - }); - } else if (options.body) { // POST && via body - Object.entries(params).forEach(([key, value]) => { - options.body.append(key, value); - }); - } else { // POST && via header - options.body = new url.URLSearchParams(); - options.headers['Content-Type'] = 'application/x-www-form-urlencoded'; - Object.entries(params).forEach(([key, value]) => { - options.body.append(key, value); - }); - } - } +const Node = __nccwpck_require__(48674) +const der = __nccwpck_require__(96018) - if (options.body) { - options.body = options.body.toString(); - } +function DEREncoder (entity) { + this.enc = 'der' + this.name = entity.name + this.entity = entity - const response = await this.requestResource(targetUrl, accessToken, options); + // Construct base tree + this.tree = new DERNode() + this.tree._init(entity.body) +} - let parsed = processResponse(response, { bearer: true }); +DEREncoder.prototype.encode = function encode (data, reporter) { + return this.tree._encode(data, reporter).join() +} - if (jwt) { - if (!JWT_CONTENT.test(response.headers['content-type'])) { - throw new RPError({ - message: 'expected application/jwt response from the userinfo_endpoint', - response, - }); - } +// Tree methods - const body = response.body.toString(); - const userinfo = await this.decryptJWTUserinfo(body); - if (!this.userinfo_signed_response_alg) { - try { - parsed = JSON.parse(userinfo); - assert(isPlainObject(parsed)); - } catch (err) { - throw new RPError({ - message: 'failed to parse userinfo JWE payload as JSON', - jwt: userinfo, - }); - } - } else { - ({ payload: parsed } = await this.validateJWTUserinfo(userinfo)); - } - } else { - try { - parsed = JSON.parse(response.body); - } catch (error) { - throw new ParseError(error, response); - } - } +function DERNode (parent) { + Node.call(this, 'der', parent) +} +inherits(DERNode, Node) - if (accessToken instanceof TokenSet && accessToken.id_token) { - const expectedSub = accessToken.claims().sub; - if (parsed.sub !== expectedSub) { - throw new RPError({ - printf: ['userinfo sub mismatch, expected %s, got: %s', expectedSub, parsed.sub], - body: parsed, - jwt: accessToken.id_token, - }); - } - } +DERNode.prototype._encodeComposite = function encodeComposite (tag, + primitive, + cls, + content) { + const encodedTag = encodeTag(tag, primitive, cls, this.reporter) - return parsed; + // Short form + if (content.length < 0x80) { + const header = Buffer.alloc(2) + header[0] = encodedTag + header[1] = content.length + return this._createEncoderBuffer([header, content]) } - /** - * @name derivedKey - * @api private - */ - async derivedKey(len) { - const cacheKey = `${len}_key`; - if (instance(this).has(cacheKey)) { - return instance(this).get(cacheKey); - } - - const hash = len <= 256 ? 'sha256' : len <= 384 ? 'sha384' : len <= 512 ? 'sha512' : false; // eslint-disable-line no-nested-ternary - if (!hash) { - throw new Error('unsupported symmetric encryption key derivation'); - } + // Long form + // Count octets required to store length + let lenOctets = 1 + for (let i = content.length; i >= 0x100; i >>= 8) { lenOctets++ } - const derivedBuffer = crypto.createHash(hash) - .update(this.client_secret) - .digest() - .slice(0, len / 8); + const header = Buffer.alloc(1 + 1 + lenOctets) + header[0] = encodedTag + header[1] = 0x80 | lenOctets - const key = jose.JWK.asKey({ k: base64url.encode(derivedBuffer), kty: 'oct' }); - instance(this).set(cacheKey, key); + for (let i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) { header[i] = j & 0xff } - return key; - } + return this._createEncoderBuffer([header, content]) +} - /** - * @name joseSecret - * @api private - */ - async joseSecret(alg) { - if (!this.client_secret) { - throw new TypeError('client_secret is required'); +DERNode.prototype._encodeStr = function encodeStr (str, tag) { + if (tag === 'bitstr') { + return this._createEncoderBuffer([str.unused | 0, str.data]) + } else if (tag === 'bmpstr') { + const buf = Buffer.alloc(str.length * 2) + for (let i = 0; i < str.length; i++) { + buf.writeUInt16BE(str.charCodeAt(i), i * 2) } - if (/^A(\d{3})(?:GCM)?KW$/.test(alg)) { - return this.derivedKey(parseInt(RegExp.$1, 10)); + return this._createEncoderBuffer(buf) + } else if (tag === 'numstr') { + if (!this._isNumstr(str)) { + return this.reporter.error('Encoding of string type: numstr supports only digits and space') } - - if (/^A(\d{3})(?:GCM|CBC-HS(\d{3}))$/.test(alg)) { - return this.derivedKey(parseInt(RegExp.$2 || RegExp.$1, 10)); + return this._createEncoderBuffer(str) + } else if (tag === 'printstr') { + if (!this._isPrintstr(str)) { + return this.reporter.error('Encoding of string type: printstr supports only latin upper and lower case letters, digits, space, apostrophe, left and rigth parenthesis, plus sign, comma, hyphen, dot, slash, colon, equal sign, question mark') } + return this._createEncoderBuffer(str) + } else if (/str$/.test(tag)) { + return this._createEncoderBuffer(str) + } else if (tag === 'objDesc') { + return this._createEncoderBuffer(str) + } else { + return this.reporter.error(`Encoding of string type: ${tag} unsupported`) + } +} - if (instance(this).has('jose_secret')) { - return instance(this).get('jose_secret'); - } +DERNode.prototype._encodeObjid = function encodeObjid (id, values, relative) { + if (typeof id === 'string') { + if (!values) { return this.reporter.error('string objid given, but no values map found') } + if (!Object.prototype.hasOwnProperty.call(values, id)) { return this.reporter.error('objid not found in values map') } + id = values[id].split(/[\s.]+/g) + for (let i = 0; i < id.length; i++) { id[i] |= 0 } + } else if (Array.isArray(id)) { + id = id.slice() + for (let i = 0; i < id.length; i++) { id[i] |= 0 } + } - const key = jose.JWK.asKey({ k: base64url.encode(this.client_secret), kty: 'oct' }); - instance(this).set('jose_secret', key); + if (!Array.isArray(id)) { + return this.reporter.error(`objid() should be either array or string, got: ${JSON.stringify(id)}`) + } - return key; + if (!relative) { + if (id[1] >= 40) { return this.reporter.error('Second objid identifier OOB') } + id.splice(0, 2, id[0] * 40 + id[1]) } - /** - * @name grant - * @api public - */ - async grant(body, { clientAssertionPayload, DPoP } = {}) { - assertIssuerConfiguration(this.issuer, 'token_endpoint'); - const response = await authenticatedPost.call( - this, - 'token', - { - form: body, - responseType: 'json', - }, - { clientAssertionPayload, DPoP }, - ); - const responseBody = processResponse(response); + // Count number of octets + let size = 0 + for (let i = 0; i < id.length; i++) { + let ident = id[i] + for (size++; ident >= 0x80; ident >>= 7) { size++ } + } - return new TokenSet(responseBody); + const objid = Buffer.alloc(size) + let offset = objid.length - 1 + for (let i = id.length - 1; i >= 0; i--) { + let ident = id[i] + objid[offset--] = ident & 0x7f + while ((ident >>= 7) > 0) { objid[offset--] = 0x80 | (ident & 0x7f) } } - /** - * @name deviceAuthorization - * @api public - */ - async deviceAuthorization(params = {}, { exchangeBody, clientAssertionPayload, DPoP } = {}) { - assertIssuerConfiguration(this.issuer, 'device_authorization_endpoint'); - assertIssuerConfiguration(this.issuer, 'token_endpoint'); + return this._createEncoderBuffer(objid) +} - const body = authorizationParams.call(this, { - client_id: this.client_id, - redirect_uri: null, - response_type: null, - ...params, - }); +function two (num) { + if (num < 10) { return `0${num}` } else { return num } +} - const response = await authenticatedPost.call( - this, - 'device_authorization', - { - responseType: 'json', - form: body, - }, - { clientAssertionPayload, endpointAuthMethod: 'token' }, - ); - const responseBody = processResponse(response); +DERNode.prototype._encodeTime = function encodeTime (time, tag) { + let str + const date = new Date(time) - return new DeviceFlowHandle({ - client: this, - exchangeBody, - clientAssertionPayload, - response: responseBody, - maxAge: params.max_age, - DPoP, - }); + if (tag === 'gentime') { + str = [ + two(date.getUTCFullYear()), + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + 'Z' + ].join('') + } else if (tag === 'utctime') { + str = [ + two(date.getUTCFullYear() % 100), + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + 'Z' + ].join('') + } else { + this.reporter.error(`Encoding ${tag} time is not supported yet`) } - /** - * @name revoke - * @api public - */ - async revoke(token, hint, { revokeBody, clientAssertionPayload } = {}) { - assertIssuerConfiguration(this.issuer, 'revocation_endpoint'); - if (hint !== undefined && typeof hint !== 'string') { - throw new TypeError('hint must be a string'); - } + return this._encodeStr(str, 'octstr') +} - const form = { ...revokeBody, token }; +DERNode.prototype._encodeNull = function encodeNull () { + return this._createEncoderBuffer('') +} - if (hint) { - form.token_type_hint = hint; - } +function bnToBuf (bn) { + var hex = BigInt(bn).toString(16) + if (hex.length % 2) { hex = '0' + hex } - const response = await authenticatedPost.call( - this, - 'revocation', { - form, - }, { clientAssertionPayload }, - ); - processResponse(response, { body: false }); + var len = hex.length / 2 + var u8 = new Uint8Array(len) + + var i = 0 + var j = 0 + while (i < len) { + u8[i] = parseInt(hex.slice(j, j + 2), 16) + i += 1 + j += 2 } - /** - * @name introspect - * @api public - */ - async introspect(token, hint, { introspectBody, clientAssertionPayload } = {}) { - assertIssuerConfiguration(this.issuer, 'introspection_endpoint'); - if (hint !== undefined && typeof hint !== 'string') { - throw new TypeError('hint must be a string'); - } + return u8 +} - const form = { ...introspectBody, token }; - if (hint) { - form.token_type_hint = hint; +DERNode.prototype._encodeInt = function encodeInt (num, values) { + if (typeof num === 'string') { + if (!values) { return this.reporter.error('String int or enum given, but no values map') } + if (!Object.prototype.hasOwnProperty.call(values, num)) { + return this.reporter.error(`Values map doesn't contain: ${JSON.stringify(num)}`) } + num = values[num] + } - const response = await authenticatedPost.call( - this, - 'introspection', - { form, responseType: 'json' }, - { clientAssertionPayload }, - ); + if (typeof num === 'bigint') { + const numArray = [...bnToBuf(num)] + if (numArray[0] & 0x80) { + numArray.unshift(0) + } + num = Buffer.from(numArray) + } - const responseBody = processResponse(response); + if (Buffer.isBuffer(num)) { + let size = num.length + if (num.length === 0) { size++ } - return responseBody; + const out = Buffer.alloc(size) + num.copy(out) + if (num.length === 0) { out[0] = 0 } + return this._createEncoderBuffer(out) } - /** - * @name fetchDistributedClaims - * @api public - */ - async fetchDistributedClaims(claims, tokens = {}) { - if (!isPlainObject(claims)) { - throw new TypeError('claims argument must be a plain object'); - } - - if (!isPlainObject(claims._claim_sources)) { - return claims; - } - - if (!isPlainObject(claims._claim_names)) { - return claims; - } - - const distributedSources = Object.entries(claims._claim_sources) - .filter(([, value]) => value && value.endpoint); - - await Promise.all(distributedSources.map(async ([sourceName, def]) => { - try { - const requestOpts = { - headers: { - Accept: 'application/jwt', - Authorization: authorizationHeaderValue(def.access_token || tokens[sourceName]), - }, - }; + if (num < 0x80) { return this._createEncoderBuffer(num) } - const response = await request.call(this, { - ...requestOpts, - method: 'GET', - url: def.endpoint, - }); - const body = processResponse(response, { bearer: true }); + if (num < 0x100) { return this._createEncoderBuffer([0, num]) } - const decoded = await claimJWT.call(this, 'distributed', body); - delete claims._claim_sources[sourceName]; - Object.entries(claims._claim_names).forEach( - assignClaim(claims, decoded, sourceName, false), - ); - } catch (err) { - err.src = sourceName; - throw err; - } - })); + let size = 1 + for (let i = num; i >= 0x100; i >>= 8) { size++ } - cleanUpClaims(claims); - return claims; + const out = new Array(size) + for (let i = out.length - 1; i >= 0; i--) { + out[i] = num & 0xff + num >>= 8 + } + if (out[0] & 0x80) { + out.unshift(0) } - /** - * @name unpackAggregatedClaims - * @api public - */ - async unpackAggregatedClaims(claims) { - if (!isPlainObject(claims)) { - throw new TypeError('claims argument must be a plain object'); - } + return this._createEncoderBuffer(Buffer.from(out)) +} - if (!isPlainObject(claims._claim_sources)) { - return claims; - } +DERNode.prototype._encodeBool = function encodeBool (value) { + return this._createEncoderBuffer(value ? 0xff : 0) +} - if (!isPlainObject(claims._claim_names)) { - return claims; - } +DERNode.prototype._use = function use (entity, obj) { + if (typeof entity === 'function') { entity = entity(obj) } + return entity._getEncoder('der').tree +} - const aggregatedSources = Object.entries(claims._claim_sources) - .filter(([, value]) => value && value.JWT); +DERNode.prototype._skipDefault = function skipDefault (dataBuffer, reporter, parent) { + const state = this._baseState + let i + if (state.default === null) { return false } - await Promise.all(aggregatedSources.map(async ([sourceName, def]) => { - try { - const decoded = await claimJWT.call(this, 'aggregated', def.JWT); - delete claims._claim_sources[sourceName]; - Object.entries(claims._claim_names).forEach(assignClaim(claims, decoded, sourceName)); - } catch (err) { - err.src = sourceName; - throw err; - } - })); + const data = dataBuffer.join() + if (state.defaultBuffer === undefined) { state.defaultBuffer = this._encodeValue(state.default, reporter, parent).join() } - cleanUpClaims(claims); - return claims; + if (data.length !== state.defaultBuffer.length) { return false } + + for (i = 0; i < data.length; i++) { + if (data[i] !== state.defaultBuffer[i]) { return false } } - /** - * @name register - * @api public - */ - static async register(metadata, options = {}) { - const { initialAccessToken, jwks, ...clientOptions } = options; + return true +} - assertIssuerConfiguration(this.issuer, 'registration_endpoint'); +// Utility methods - if (jwks !== undefined && !(metadata.jwks || metadata.jwks_uri)) { - const keystore = getKeystore.call(this, jwks); - metadata.jwks = keystore.toJWKS(false); - // eslint-disable-next-line no-restricted-syntax - for (const jwk of metadata.jwks.keys) { - if (jwk.kid.startsWith('DONOTUSE.')) { - delete jwk.kid; - } - } - } +function encodeTag (tag, primitive, cls, reporter) { + let res - const response = await request.call(this, { - headers: initialAccessToken ? { - Authorization: authorizationHeaderValue(initialAccessToken), - } : undefined, - responseType: 'json', - json: metadata, - url: this.issuer.registration_endpoint, - method: 'POST', - }); - const responseBody = processResponse(response, { statusCode: 201, bearer: true }); + if (tag === 'seqof') { tag = 'seq' } else if (tag === 'setof') { tag = 'set' } - return new this(responseBody, jwks, clientOptions); - } + if (Object.prototype.hasOwnProperty.call(der.tagByName, tag)) { res = der.tagByName[tag] } else if (typeof tag === 'number' && (tag | 0) === tag) { res = tag } else { return reporter.error(`Unknown tag: ${tag}`) } - /** - * @name metadata - * @api public - */ - get metadata() { - const copy = {}; - instance(this).get('metadata').forEach((value, key) => { - copy[key] = value; - }); - return copy; - } + if (res >= 0x1f) { return reporter.error('Multi-octet tag encoding unsupported') } - /** - * @name fromUri - * @api public - */ - static async fromUri(registrationClientUri, registrationAccessToken, jwks, clientOptions) { - const response = await request.call(this, { - method: 'GET', - url: registrationClientUri, - responseType: 'json', - headers: { Authorization: authorizationHeaderValue(registrationAccessToken) }, - }); - const responseBody = processResponse(response, { bearer: true }); + if (!primitive) { res |= 0x20 } - return new this(responseBody, jwks, clientOptions); - } + res |= (der.tagClassByName[cls || 'universal'] << 6) - /** - * @name requestObject - * @api public - */ - async requestObject(requestObject = {}, { - sign: signingAlgorithm = this.request_object_signing_alg || 'none', - encrypt: { - alg: eKeyManagement = this.request_object_encryption_alg, - enc: eContentEncryption = this.request_object_encryption_enc || 'A128CBC-HS256', - } = {}, - } = {}) { - if (!isPlainObject(requestObject)) { - throw new TypeError('requestObject must be a plain object'); - } + return res +} - let signed; - let key; +module.exports = DEREncoder - const fapi = this.constructor.name === 'FAPIClient'; - const unix = now(); - const header = { alg: signingAlgorithm, typ: 'oauth-authz-req+jwt' }; - const payload = JSON.stringify(defaults({}, requestObject, { - iss: this.client_id, - aud: this.issuer.issuer, - client_id: this.client_id, - jti: random(), - iat: unix, - exp: unix + 300, - ...(fapi ? { nbf: unix } : undefined), - })); - if (signingAlgorithm === 'none') { - signed = [ - base64url.encode(JSON.stringify(header)), - base64url.encode(payload), - '', - ].join('.'); - } else { - const symmetric = signingAlgorithm.startsWith('HS'); - if (symmetric) { - key = await this.joseSecret(); - } else { - const keystore = instance(this).get('keystore'); +/***/ }), - if (!keystore) { - throw new TypeError(`no keystore present for client, cannot sign using alg ${signingAlgorithm}`); - } - key = keystore.get({ alg: signingAlgorithm, use: 'sig' }); - if (!key) { - throw new TypeError(`no key to sign with found for alg ${signingAlgorithm}`); - } - } +/***/ 2246: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - signed = jose.JWS.sign(payload, key, { - ...header, - kid: symmetric || key.kid.startsWith('DONOTUSE.') ? undefined : key.kid, - }); - } +module.exports = { + der: __nccwpck_require__(20846), + pem: __nccwpck_require__(26217) +} - if (!eKeyManagement) { - return signed; - } - const fields = { alg: eKeyManagement, enc: eContentEncryption, cty: 'oauth-authz-req+jwt' }; +/***/ }), - if (fields.alg.match(/^(RSA|ECDH)/)) { - [key] = await this.issuer.queryKeyStore({ - alg: fields.alg, - enc: fields.enc, - use: 'enc', - }, { allowMulti: true }); - } else { - key = await this.joseSecret(fields.alg === 'dir' ? fields.enc : fields.alg); - } +/***/ 26217: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return jose.JWE.encrypt(signed, key, { - ...fields, - kid: key.kty === 'oct' ? undefined : key.kid, - }); - } +const { inherits } = __nccwpck_require__(73837) - /** - * @name pushedAuthorizationRequest - * @api public - */ - async pushedAuthorizationRequest(params = {}, { clientAssertionPayload } = {}) { - assertIssuerConfiguration(this.issuer, 'pushed_authorization_request_endpoint'); +const DEREncoder = __nccwpck_require__(20846) - const body = { - ...('request' in params ? params : authorizationParams.call(this, params)), - client_id: this.client_id, - }; +function PEMEncoder (entity) { + DEREncoder.call(this, entity) + this.enc = 'pem' +} +inherits(PEMEncoder, DEREncoder) - const response = await authenticatedPost.call( - this, - 'pushed_authorization_request', - { - responseType: 'json', - form: body, - }, - { clientAssertionPayload, endpointAuthMethod: 'token' }, - ); - const responseBody = processResponse(response, { statusCode: 201 }); +PEMEncoder.prototype.encode = function encode (data, options) { + const buf = DEREncoder.prototype.encode.call(this, data) - if (!('expires_in' in responseBody)) { - throw new RPError({ - message: 'expected expires_in in Pushed Authorization Successful Response', - response, - }); - } - if (typeof responseBody.expires_in !== 'number') { - throw new RPError({ - message: 'invalid expires_in value in Pushed Authorization Successful Response', - response, - }); - } - if (!('request_uri' in responseBody)) { - throw new RPError({ - message: 'expected request_uri in Pushed Authorization Successful Response', - response, - }); - } - if (typeof responseBody.request_uri !== 'string') { - throw new RPError({ - message: 'invalid request_uri value in Pushed Authorization Successful Response', - response, - }); - } + const p = buf.toString('base64') + const out = [`-----BEGIN ${options.label}-----`] + for (let i = 0; i < p.length; i += 64) { out.push(p.slice(i, i + 64)) } + out.push(`-----END ${options.label}-----`) + return out.join('\n') +} - return responseBody; - } +module.exports = PEMEncoder - /** - * @name issuer - * @api public - */ - static get issuer() { - return issuer; - } - /** - * @name issuer - * @api public - */ - get issuer() { // eslint-disable-line class-methods-use-this - return issuer; - } +/***/ }), - /* istanbul ignore next */ - [inspect.custom]() { - return `${this.constructor.name} ${inspect(this.metadata, { - depth: Infinity, - colors: process.stdout.isTTY, - compact: false, - sorted: true, - })}`; - } -}; +/***/ 29912: +/***/ (function(__unused_webpack_module, exports) { -/** - * @name validateJARM - * @api private - */ -async function validateJARM(response) { - const expectedAlg = this.authorization_signed_response_alg; - const { payload } = await this.validateJWT(response, expectedAlg, ['iss', 'exp', 'aud']); - return pickCb(payload); -} +"use strict"; -Object.defineProperty(BaseClient.prototype, 'validateJARM', { - enumerable: true, - configurable: true, - value(...args) { - process.emitWarning( - "The JARM API implements an OIDF implementer's draft. Breaking draft implementations are included as minor versions of the openid-client library, therefore, the ~ semver operator should be used and close attention be payed to library changelog as well as the drafts themselves.", - 'DraftWarning', - ); - Object.defineProperty(BaseClient.prototype, 'validateJARM', { - enumerable: true, - configurable: true, - value: validateJARM, +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); - return this.validateJARM(...args); - }, -}); - +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ClientStreamingCall = void 0; /** - * @name dpopProof - * @api private + * A client streaming RPC call. This means that the clients sends 0, 1, or + * more messages to the server, and the server replies with exactly one + * message. */ -function dpopProof(payload, jwk, accessToken) { - if (!isPlainObject(payload)) { - throw new TypeError('payload must be a plain object'); - } - - let key; - try { - key = jose.JWK.asKey(jwk); - assert(key.type === 'private'); - } catch (err) { - throw new TypeError('"DPoP" option must be an asymmetric private key to sign the DPoP Proof JWT with'); - } - - let { alg } = key; - - if (!alg && this.issuer.dpop_signing_alg_values_supported) { - const algs = key.algorithms('sign'); - alg = this.issuer.dpop_signing_alg_values_supported.find((a) => algs.has(a)); - } - - if (!alg) { - [alg] = key.algorithms('sign'); - } - - return jose.JWS.sign({ - iat: now(), - jti: random(), - ath: accessToken ? base64url.encode(crypto.createHash('sha256').update(accessToken).digest()) : undefined, - ...payload, - }, jwk, { - alg, - typ: 'dpop+jwt', - jwk: pick(key, 'kty', 'crv', 'x', 'y', 'e', 'n'), - }); +class ClientStreamingCall { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.requests = request; + this.headers = headers; + this.response = response; + this.status = status; + this.trailers = trailers; + } + /** + * Instead of awaiting the response status and trailers, you can + * just as well await this call itself to receive the server outcome. + * Note that it may still be valid to send more request messages. + */ + then(onfulfilled, onrejected) { + return this.promiseFinished().then(value => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, reason => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter(this, void 0, void 0, function* () { + let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + headers, + response, + status, + trailers + }; + }); + } } - -Object.defineProperty(BaseClient.prototype, 'dpopProof', { - enumerable: true, - configurable: true, - value(...args) { - process.emitWarning( - 'The DPoP APIs implements an IETF draft (https://www.ietf.org/archive/id/draft-ietf-oauth-dpop-03.html). Breaking draft implementations are included as minor versions of the openid-client library, therefore, the ~ semver operator should be used and close attention be payed to library changelog as well as the drafts themselves.', - 'DraftWarning', - ); - Object.defineProperty(BaseClient.prototype, 'dpopProof', { - enumerable: true, - configurable: true, - value: dpopProof, - }); - return this.dpopProof(...args); - }, -}); - -module.exports.BaseClient = BaseClient; +exports.ClientStreamingCall = ClientStreamingCall; /***/ }), -/***/ 60679: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/* eslint-disable camelcase */ -const { inspect } = __nccwpck_require__(73837); - -const { RPError, OPError } = __nccwpck_require__(31151); -const instance = __nccwpck_require__(69020); -const now = __nccwpck_require__(24393); -const { authenticatedPost } = __nccwpck_require__(26633); -const processResponse = __nccwpck_require__(59980); -const TokenSet = __nccwpck_require__(14974); +/***/ 85702: +/***/ ((__unused_webpack_module, exports) => { -class DeviceFlowHandle { - constructor({ - client, exchangeBody, clientAssertionPayload, response, maxAge, DPoP, - }) { - ['verification_uri', 'user_code', 'device_code'].forEach((prop) => { - if (typeof response[prop] !== 'string' || !response[prop]) { - throw new RPError(`expected ${prop} string to be returned by Device Authorization Response, got %j`, response[prop]); - } - }); +"use strict"; - if (!Number.isSafeInteger(response.expires_in)) { - throw new RPError('expected expires_in number to be returned by Device Authorization Response, got %j', response.expires_in); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Deferred = exports.DeferredState = void 0; +var DeferredState; +(function (DeferredState) { + DeferredState[DeferredState["PENDING"] = 0] = "PENDING"; + DeferredState[DeferredState["REJECTED"] = 1] = "REJECTED"; + DeferredState[DeferredState["RESOLVED"] = 2] = "RESOLVED"; +})(DeferredState = exports.DeferredState || (exports.DeferredState = {})); +/** + * A deferred promise. This is a "controller" for a promise, which lets you + * pass a promise around and reject or resolve it from the outside. + * + * Warning: This class is to be used with care. Using it can make code very + * difficult to read. It is intended for use in library code that exposes + * promises, not for regular business logic. + */ +class Deferred { + /** + * @param preventUnhandledRejectionWarning - prevents the warning + * "Unhandled Promise rejection" by adding a noop rejection handler. + * Working with calls returned from the runtime-rpc package in an + * async function usually means awaiting one call property after + * the other. This means that the "status" is not being awaited when + * an earlier await for the "headers" is rejected. This causes the + * "unhandled promise reject" warning. A more correct behaviour for + * calls might be to become aware whether at least one of the + * promises is handled and swallow the rejection warning for the + * others. + */ + constructor(preventUnhandledRejectionWarning = true) { + this._state = DeferredState.PENDING; + this._promise = new Promise((resolve, reject) => { + this._resolve = resolve; + this._reject = reject; + }); + if (preventUnhandledRejectionWarning) { + this._promise.catch(_ => { }); + } } - - instance(this).expires_at = now() + response.expires_in; - instance(this).client = client; - instance(this).DPoP = DPoP; - instance(this).maxAge = maxAge; - instance(this).exchangeBody = exchangeBody; - instance(this).clientAssertionPayload = clientAssertionPayload; - instance(this).response = response; - instance(this).interval = response.interval * 1000 || 5000; - } - - abort() { - instance(this).aborted = true; - } - - async poll({ signal } = {}) { - if ((signal && signal.aborted) || instance(this).aborted) { - throw new RPError('polling aborted'); + /** + * Get the current state of the promise. + */ + get state() { + return this._state; } - - if (this.expired()) { - throw new RPError('the device code %j has expired and the device authorization session has concluded', this.device_code); + /** + * Get the deferred promise. + */ + get promise() { + return this._promise; } - - await new Promise((resolve) => setTimeout(resolve, instance(this).interval)); - - const response = await authenticatedPost.call( - instance(this).client, - 'token', - { - form: { - ...instance(this).exchangeBody, - grant_type: 'urn:ietf:params:oauth:grant-type:device_code', - device_code: this.device_code, - }, - responseType: 'json', - }, - { clientAssertionPayload: instance(this).clientAssertionPayload, DPoP: instance(this).DPoP }, - ); - - let responseBody; - try { - responseBody = processResponse(response); - } catch (err) { - switch (err instanceof OPError && err.error) { - case 'slow_down': - instance(this).interval += 5000; - case 'authorization_pending': // eslint-disable-line no-fallthrough - return this.poll({ signal }); - default: - throw err; - } + /** + * Resolve the promise. Throws if the promise is already resolved or rejected. + */ + resolve(value) { + if (this.state !== DeferredState.PENDING) + throw new Error(`cannot resolve ${DeferredState[this.state].toLowerCase()}`); + this._resolve(value); + this._state = DeferredState.RESOLVED; } - - const tokenset = new TokenSet(responseBody); - - if ('id_token' in tokenset) { - await instance(this).client.decryptIdToken(tokenset); - await instance(this).client.validateIdToken(tokenset, undefined, 'token', instance(this).maxAge); + /** + * Reject the promise. Throws if the promise is already resolved or rejected. + */ + reject(reason) { + if (this.state !== DeferredState.PENDING) + throw new Error(`cannot reject ${DeferredState[this.state].toLowerCase()}`); + this._reject(reason); + this._state = DeferredState.REJECTED; } + /** + * Resolve the promise. Ignore if not pending. + */ + resolvePending(val) { + if (this._state === DeferredState.PENDING) + this.resolve(val); + } + /** + * Reject the promise. Ignore if not pending. + */ + rejectPending(reason) { + if (this._state === DeferredState.PENDING) + this.reject(reason); + } +} +exports.Deferred = Deferred; - return tokenset; - } - - get device_code() { - return instance(this).response.device_code; - } - - get user_code() { - return instance(this).response.user_code; - } - - get verification_uri() { - return instance(this).response.verification_uri; - } - get verification_uri_complete() { - return instance(this).response.verification_uri_complete; - } +/***/ }), - get expires_in() { - return Math.max.apply(null, [instance(this).expires_at - now(), 0]); - } +/***/ 17042: +/***/ (function(__unused_webpack_module, exports) { - expired() { - return this.expires_in === 0; - } +"use strict"; - /* istanbul ignore next */ - [inspect.custom]() { - return `${this.constructor.name} ${inspect(instance(this).response, { - depth: Infinity, - colors: process.stdout.isTTY, - compact: false, - sorted: true, - })}`; - } +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DuplexStreamingCall = void 0; +/** + * A duplex streaming RPC call. This means that the clients sends an + * arbitrary amount of messages to the server, while at the same time, + * the server sends an arbitrary amount of messages to the client. + */ +class DuplexStreamingCall { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.requests = request; + this.headers = headers; + this.responses = response; + this.status = status; + this.trailers = trailers; + } + /** + * Instead of awaiting the response status and trailers, you can + * just as well await this call itself to receive the server outcome. + * Note that it may still be valid to send more request messages. + */ + then(onfulfilled, onrejected) { + return this.promiseFinished().then(value => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, reason => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter(this, void 0, void 0, function* () { + let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + headers, + status, + trailers, + }; + }); + } } - -module.exports = DeviceFlowHandle; +exports.DuplexStreamingCall = DuplexStreamingCall; /***/ }), -/***/ 31151: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 60012: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/* eslint-disable camelcase */ -const { format } = __nccwpck_require__(73837); +"use strict"; -const makeError = __nccwpck_require__(21381); +// Public API of the rpc runtime. +// Note: we do not use `export * from ...` to help tree shakers, +// webpack verbose output hints that this should be useful +Object.defineProperty(exports, "__esModule", ({ value: true })); +var service_type_1 = __nccwpck_require__(14107); +Object.defineProperty(exports, "ServiceType", ({ enumerable: true, get: function () { return service_type_1.ServiceType; } })); +var reflection_info_1 = __nccwpck_require__(44331); +Object.defineProperty(exports, "readMethodOptions", ({ enumerable: true, get: function () { return reflection_info_1.readMethodOptions; } })); +Object.defineProperty(exports, "readMethodOption", ({ enumerable: true, get: function () { return reflection_info_1.readMethodOption; } })); +Object.defineProperty(exports, "readServiceOption", ({ enumerable: true, get: function () { return reflection_info_1.readServiceOption; } })); +var rpc_error_1 = __nccwpck_require__(63159); +Object.defineProperty(exports, "RpcError", ({ enumerable: true, get: function () { return rpc_error_1.RpcError; } })); +var rpc_options_1 = __nccwpck_require__(67386); +Object.defineProperty(exports, "mergeRpcOptions", ({ enumerable: true, get: function () { return rpc_options_1.mergeRpcOptions; } })); +var rpc_output_stream_1 = __nccwpck_require__(76637); +Object.defineProperty(exports, "RpcOutputStreamController", ({ enumerable: true, get: function () { return rpc_output_stream_1.RpcOutputStreamController; } })); +var test_transport_1 = __nccwpck_require__(87008); +Object.defineProperty(exports, "TestTransport", ({ enumerable: true, get: function () { return test_transport_1.TestTransport; } })); +var deferred_1 = __nccwpck_require__(85702); +Object.defineProperty(exports, "Deferred", ({ enumerable: true, get: function () { return deferred_1.Deferred; } })); +Object.defineProperty(exports, "DeferredState", ({ enumerable: true, get: function () { return deferred_1.DeferredState; } })); +var duplex_streaming_call_1 = __nccwpck_require__(17042); +Object.defineProperty(exports, "DuplexStreamingCall", ({ enumerable: true, get: function () { return duplex_streaming_call_1.DuplexStreamingCall; } })); +var client_streaming_call_1 = __nccwpck_require__(29912); +Object.defineProperty(exports, "ClientStreamingCall", ({ enumerable: true, get: function () { return client_streaming_call_1.ClientStreamingCall; } })); +var server_streaming_call_1 = __nccwpck_require__(30066); +Object.defineProperty(exports, "ServerStreamingCall", ({ enumerable: true, get: function () { return server_streaming_call_1.ServerStreamingCall; } })); +var unary_call_1 = __nccwpck_require__(84175); +Object.defineProperty(exports, "UnaryCall", ({ enumerable: true, get: function () { return unary_call_1.UnaryCall; } })); +var rpc_interceptor_1 = __nccwpck_require__(51680); +Object.defineProperty(exports, "stackIntercept", ({ enumerable: true, get: function () { return rpc_interceptor_1.stackIntercept; } })); +Object.defineProperty(exports, "stackDuplexStreamingInterceptors", ({ enumerable: true, get: function () { return rpc_interceptor_1.stackDuplexStreamingInterceptors; } })); +Object.defineProperty(exports, "stackClientStreamingInterceptors", ({ enumerable: true, get: function () { return rpc_interceptor_1.stackClientStreamingInterceptors; } })); +Object.defineProperty(exports, "stackServerStreamingInterceptors", ({ enumerable: true, get: function () { return rpc_interceptor_1.stackServerStreamingInterceptors; } })); +Object.defineProperty(exports, "stackUnaryInterceptors", ({ enumerable: true, get: function () { return rpc_interceptor_1.stackUnaryInterceptors; } })); +var server_call_context_1 = __nccwpck_require__(25320); +Object.defineProperty(exports, "ServerCallContextController", ({ enumerable: true, get: function () { return server_call_context_1.ServerCallContextController; } })); -function OPError({ - error_description, - error, - error_uri, - session_state, - state, - scope, -}, response) { - OPError.super.call(this, !error_description ? error : `${error} (${error_description})`); - Object.assign( - this, - { error }, - (error_description && { error_description }), - (error_uri && { error_uri }), - (state && { state }), - (scope && { scope }), - (session_state && { session_state }), - ); +/***/ }), - if (response) { - Object.defineProperty(this, 'response', { - value: response, - }); - } -} +/***/ 44331: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -makeError(OPError); +"use strict"; -function RPError(...args) { - if (typeof args[0] === 'string') { - RPError.super.call(this, format(...args)); - } else { - const { - message, printf, response, ...rest - } = args[0]; - if (printf) { - RPError.super.call(this, format(...printf)); - } else { - RPError.super.call(this, message); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.readServiceOption = exports.readMethodOption = exports.readMethodOptions = exports.normalizeMethodInfo = void 0; +const runtime_1 = __nccwpck_require__(4061); +/** + * Turns PartialMethodInfo into MethodInfo. + */ +function normalizeMethodInfo(method, service) { + var _a, _b, _c; + let m = method; + m.service = service; + m.localName = (_a = m.localName) !== null && _a !== void 0 ? _a : runtime_1.lowerCamelCase(m.name); + // noinspection PointlessBooleanExpressionJS + m.serverStreaming = !!m.serverStreaming; + // noinspection PointlessBooleanExpressionJS + m.clientStreaming = !!m.clientStreaming; + m.options = (_b = m.options) !== null && _b !== void 0 ? _b : {}; + m.idempotency = (_c = m.idempotency) !== null && _c !== void 0 ? _c : undefined; + return m; +} +exports.normalizeMethodInfo = normalizeMethodInfo; +/** + * Read custom method options from a generated service client. + * + * @deprecated use readMethodOption() + */ +function readMethodOptions(service, methodName, extensionName, extensionType) { + var _a; + const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; + return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : undefined; +} +exports.readMethodOptions = readMethodOptions; +function readMethodOption(service, methodName, extensionName, extensionType) { + var _a; + const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; + if (!options) { + return undefined; } - Object.assign(this, rest); - if (response) { - Object.defineProperty(this, 'response', { - value: response, - }); + const optionVal = options[extensionName]; + if (optionVal === undefined) { + return optionVal; } - } + return extensionType ? extensionType.fromJson(optionVal) : optionVal; } - -makeError(RPError); - -module.exports = { - OPError, - RPError, -}; +exports.readMethodOption = readMethodOption; +function readServiceOption(service, extensionName, extensionType) { + const options = service.options; + if (!options) { + return undefined; + } + const optionVal = options[extensionName]; + if (optionVal === undefined) { + return optionVal; + } + return extensionType ? extensionType.fromJson(optionVal) : optionVal; +} +exports.readServiceOption = readServiceOption; /***/ }), -/***/ 68973: -/***/ ((module) => { - -function assertSigningAlgValuesSupport(endpoint, issuer, properties) { - if (!issuer[`${endpoint}_endpoint`]) return; - - const eam = `${endpoint}_endpoint_auth_method`; - const easa = `${endpoint}_endpoint_auth_signing_alg`; - const easavs = `${endpoint}_endpoint_auth_signing_alg_values_supported`; +/***/ 63159: +/***/ ((__unused_webpack_module, exports) => { - if (properties[eam] && properties[eam].endsWith('_jwt') && !properties[easa] && !issuer[easavs]) { - throw new TypeError(`${easavs} must be configured on the issuer if ${easa} is not defined on a client`); - } -} +"use strict"; -function assertIssuerConfiguration(issuer, endpoint) { - if (!issuer[endpoint]) { - throw new TypeError(`${endpoint} must be configured on the issuer`); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.RpcError = void 0; +/** + * An error that occurred while calling a RPC method. + */ +class RpcError extends Error { + constructor(message, code = 'UNKNOWN', meta) { + super(message); + this.name = 'RpcError'; + // see https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#example + Object.setPrototypeOf(this, new.target.prototype); + this.code = code; + this.meta = meta !== null && meta !== void 0 ? meta : {}; + } + toString() { + const l = [this.name + ': ' + this.message]; + if (this.code) { + l.push(''); + l.push('Code: ' + this.code); + } + if (this.serviceName && this.methodName) { + l.push('Method: ' + this.serviceName + '/' + this.methodName); + } + let m = Object.entries(this.meta); + if (m.length) { + l.push(''); + l.push('Meta:'); + for (let [k, v] of m) { + l.push(` ${k}: ${v}`); + } + } + return l.join('\n'); + } } - -module.exports = { - assertSigningAlgValuesSupport, - assertIssuerConfiguration, -}; +exports.RpcError = RpcError; /***/ }), -/***/ 23570: -/***/ ((module) => { - -let encode; -if (Buffer.isEncoding('base64url')) { - encode = (input, encoding = 'utf8') => Buffer.from(input, encoding).toString('base64url'); -} else { - const fromBase64 = (base64) => base64.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); - encode = (input, encoding = 'utf8') => fromBase64(Buffer.from(input, encoding).toString('base64')); -} +/***/ 51680: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const decode = (input) => Buffer.from(input, 'base64'); +"use strict"; -module.exports.decode = decode; -module.exports.encode = encode; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.stackDuplexStreamingInterceptors = exports.stackClientStreamingInterceptors = exports.stackServerStreamingInterceptors = exports.stackUnaryInterceptors = exports.stackIntercept = void 0; +const runtime_1 = __nccwpck_require__(4061); +/** + * Creates a "stack" of of all interceptors specified in the given `RpcOptions`. + * Used by generated client implementations. + * @internal + */ +function stackIntercept(kind, transport, method, options, input) { + var _a, _b, _c, _d; + if (kind == "unary") { + let tail = (mtd, inp, opt) => transport.unary(mtd, inp, opt); + for (const curr of ((_a = options.interceptors) !== null && _a !== void 0 ? _a : []).filter(i => i.interceptUnary).reverse()) { + const next = tail; + tail = (mtd, inp, opt) => curr.interceptUnary(next, mtd, inp, opt); + } + return tail(method, input, options); + } + if (kind == "serverStreaming") { + let tail = (mtd, inp, opt) => transport.serverStreaming(mtd, inp, opt); + for (const curr of ((_b = options.interceptors) !== null && _b !== void 0 ? _b : []).filter(i => i.interceptServerStreaming).reverse()) { + const next = tail; + tail = (mtd, inp, opt) => curr.interceptServerStreaming(next, mtd, inp, opt); + } + return tail(method, input, options); + } + if (kind == "clientStreaming") { + let tail = (mtd, opt) => transport.clientStreaming(mtd, opt); + for (const curr of ((_c = options.interceptors) !== null && _c !== void 0 ? _c : []).filter(i => i.interceptClientStreaming).reverse()) { + const next = tail; + tail = (mtd, opt) => curr.interceptClientStreaming(next, mtd, opt); + } + return tail(method, options); + } + if (kind == "duplex") { + let tail = (mtd, opt) => transport.duplex(mtd, opt); + for (const curr of ((_d = options.interceptors) !== null && _d !== void 0 ? _d : []).filter(i => i.interceptDuplex).reverse()) { + const next = tail; + tail = (mtd, opt) => curr.interceptDuplex(next, mtd, opt); + } + return tail(method, options); + } + runtime_1.assertNever(kind); +} +exports.stackIntercept = stackIntercept; +/** + * @deprecated replaced by `stackIntercept()`, still here to support older generated code + */ +function stackUnaryInterceptors(transport, method, input, options) { + return stackIntercept("unary", transport, method, options, input); +} +exports.stackUnaryInterceptors = stackUnaryInterceptors; +/** + * @deprecated replaced by `stackIntercept()`, still here to support older generated code + */ +function stackServerStreamingInterceptors(transport, method, input, options) { + return stackIntercept("serverStreaming", transport, method, options, input); +} +exports.stackServerStreamingInterceptors = stackServerStreamingInterceptors; +/** + * @deprecated replaced by `stackIntercept()`, still here to support older generated code + */ +function stackClientStreamingInterceptors(transport, method, options) { + return stackIntercept("clientStreaming", transport, method, options); +} +exports.stackClientStreamingInterceptors = stackClientStreamingInterceptors; +/** + * @deprecated replaced by `stackIntercept()`, still here to support older generated code + */ +function stackDuplexStreamingInterceptors(transport, method, options) { + return stackIntercept("duplex", transport, method, options); +} +exports.stackDuplexStreamingInterceptors = stackDuplexStreamingInterceptors; /***/ }), -/***/ 26633: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const jose = __nccwpck_require__(87115); - -const { assertIssuerConfiguration } = __nccwpck_require__(68973); -const { random } = __nccwpck_require__(65894); -const now = __nccwpck_require__(24393); -const request = __nccwpck_require__(8048); -const instance = __nccwpck_require__(69020); -const merge = __nccwpck_require__(71839); - -const formUrlEncode = (value) => encodeURIComponent(value).replace(/%20/g, '+'); - -async function clientAssertion(endpoint, payload) { - let alg = this[`${endpoint}_endpoint_auth_signing_alg`]; - if (!alg) { - assertIssuerConfiguration(this.issuer, `${endpoint}_endpoint_auth_signing_alg_values_supported`); - } - - if (this[`${endpoint}_endpoint_auth_method`] === 'client_secret_jwt') { - const key = await this.joseSecret(); - - if (!alg) { - const supported = this.issuer[`${endpoint}_endpoint_auth_signing_alg_values_supported`]; - alg = Array.isArray(supported) && supported.find((signAlg) => key.algorithms('sign').has(signAlg)); - } - - return jose.JWS.sign(payload, key, { alg, typ: 'JWT' }); - } +/***/ 67386: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const keystore = instance(this).get('keystore'); +"use strict"; - if (!keystore) { - throw new TypeError('no client jwks provided for signing a client assertion with'); - } - - if (!alg) { - const algs = new Set(); - - keystore.all().forEach((key) => { - key.algorithms('sign').forEach(Set.prototype.add.bind(algs)); - }); - - const supported = this.issuer[`${endpoint}_endpoint_auth_signing_alg_values_supported`]; - alg = Array.isArray(supported) && supported.find((signAlg) => algs.has(signAlg)); - } - - const key = keystore.get({ alg, use: 'sig' }); - if (!key) { - throw new TypeError(`no key found in client jwks to sign a client assertion with using alg ${alg}`); - } - return jose.JWS.sign(payload, key, { alg, typ: 'JWT', kid: key.kid.startsWith('DONOTUSE.') ? undefined : key.kid }); -} - -async function authFor(endpoint, { clientAssertionPayload } = {}) { - const authMethod = this[`${endpoint}_endpoint_auth_method`]; - switch (authMethod) { - case 'self_signed_tls_client_auth': - case 'tls_client_auth': - case 'none': - return { form: { client_id: this.client_id } }; - case 'client_secret_post': - if (!this.client_secret) { - throw new TypeError('client_secret_post client authentication method requires a client_secret'); - } - return { form: { client_id: this.client_id, client_secret: this.client_secret } }; - case 'private_key_jwt': - case 'client_secret_jwt': { - const timestamp = now(); - - const mTLS = endpoint === 'token' && this.tls_client_certificate_bound_access_tokens; - const audience = [...new Set([ - this.issuer.issuer, - this.issuer.token_endpoint, - this.issuer[`${endpoint}_endpoint`], - mTLS && this.issuer.mtls_endpoint_aliases - ? this.issuer.mtls_endpoint_aliases.token_endpoint : undefined, - ].filter(Boolean))]; - - const assertion = await clientAssertion.call(this, endpoint, { - iat: timestamp, - exp: timestamp + 60, - jti: random(), - iss: this.client_id, - sub: this.client_id, - aud: audience, - ...clientAssertionPayload, - }); - - return { - form: { - client_id: this.client_id, - client_assertion: assertion, - client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer', - }, - }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.mergeRpcOptions = void 0; +const runtime_1 = __nccwpck_require__(4061); +/** + * Merges custom RPC options with defaults. Returns a new instance and keeps + * the "defaults" and the "options" unmodified. + * + * Merges `RpcMetadata` "meta", overwriting values from "defaults" with + * values from "options". Does not append values to existing entries. + * + * Merges "jsonOptions", including "jsonOptions.typeRegistry", by creating + * a new array that contains types from "options.jsonOptions.typeRegistry" + * first, then types from "defaults.jsonOptions.typeRegistry". + * + * Merges "binaryOptions". + * + * Merges "interceptors" by creating a new array that contains interceptors + * from "defaults" first, then interceptors from "options". + * + * Works with objects that extend `RpcOptions`, but only if the added + * properties are of type Date, primitive like string, boolean, or Array + * of primitives. If you have other property types, you have to merge them + * yourself. + */ +function mergeRpcOptions(defaults, options) { + if (!options) + return defaults; + let o = {}; + copy(defaults, o); + copy(options, o); + for (let key of Object.keys(options)) { + let val = options[key]; + switch (key) { + case "jsonOptions": + o.jsonOptions = runtime_1.mergeJsonOptions(defaults.jsonOptions, o.jsonOptions); + break; + case "binaryOptions": + o.binaryOptions = runtime_1.mergeBinaryOptions(defaults.binaryOptions, o.binaryOptions); + break; + case "meta": + o.meta = {}; + copy(defaults.meta, o.meta); + copy(options.meta, o.meta); + break; + case "interceptors": + o.interceptors = defaults.interceptors ? defaults.interceptors.concat(val) : val.concat(); + break; + } } - default: { // client_secret_basic - // This is correct behaviour, see https://tools.ietf.org/html/rfc6749#section-2.3.1 and the - // related appendix. (also https://github.com/panva/node-openid-client/pull/91) - // > The client identifier is encoded using the - // > "application/x-www-form-urlencoded" encoding algorithm per - // > Appendix B, and the encoded value is used as the username; the client - // > password is encoded using the same algorithm and used as the - // > password. - if (!this.client_secret) { - throw new TypeError('client_secret_basic client authentication method requires a client_secret'); - } - const encoded = `${formUrlEncode(this.client_id)}:${formUrlEncode(this.client_secret)}`; - const value = Buffer.from(encoded).toString('base64'); - return { headers: { Authorization: `Basic ${value}` } }; + return o; +} +exports.mergeRpcOptions = mergeRpcOptions; +function copy(a, into) { + if (!a) + return; + let c = into; + for (let [k, v] of Object.entries(a)) { + if (v instanceof Date) + c[k] = new Date(v.getTime()); + else if (Array.isArray(v)) + c[k] = v.concat(); + else + c[k] = v; } - } } -function resolveResponseType() { - const { length, 0: value } = this.response_types; - - if (length === 1) { - return value; - } - return undefined; -} +/***/ }), -function resolveRedirectUri() { - const { length, 0: value } = this.redirect_uris || []; +/***/ 76637: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (length === 1) { - return value; - } +"use strict"; - return undefined; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.RpcOutputStreamController = void 0; +const deferred_1 = __nccwpck_require__(85702); +const runtime_1 = __nccwpck_require__(4061); +/** + * A `RpcOutputStream` that you control. + */ +class RpcOutputStreamController { + constructor() { + this._lis = { + nxt: [], + msg: [], + err: [], + cmp: [], + }; + this._closed = false; + } + // --- RpcOutputStream callback API + onNext(callback) { + return this.addLis(callback, this._lis.nxt); + } + onMessage(callback) { + return this.addLis(callback, this._lis.msg); + } + onError(callback) { + return this.addLis(callback, this._lis.err); + } + onComplete(callback) { + return this.addLis(callback, this._lis.cmp); + } + addLis(callback, list) { + list.push(callback); + return () => { + let i = list.indexOf(callback); + if (i >= 0) + list.splice(i, 1); + }; + } + // remove all listeners + clearLis() { + for (let l of Object.values(this._lis)) + l.splice(0, l.length); + } + // --- Controller API + /** + * Is this stream already closed by a completion or error? + */ + get closed() { + return this._closed !== false; + } + /** + * Emit message, close with error, or close successfully, but only one + * at a time. + * Can be used to wrap a stream by using the other stream's `onNext`. + */ + notifyNext(message, error, complete) { + runtime_1.assert((message ? 1 : 0) + (error ? 1 : 0) + (complete ? 1 : 0) <= 1, 'only one emission at a time'); + if (message) + this.notifyMessage(message); + if (error) + this.notifyError(error); + if (complete) + this.notifyComplete(); + } + /** + * Emits a new message. Throws if stream is closed. + * + * Triggers onNext and onMessage callbacks. + */ + notifyMessage(message) { + runtime_1.assert(!this.closed, 'stream is closed'); + this.pushIt({ value: message, done: false }); + this._lis.msg.forEach(l => l(message)); + this._lis.nxt.forEach(l => l(message, undefined, false)); + } + /** + * Closes the stream with an error. Throws if stream is closed. + * + * Triggers onNext and onError callbacks. + */ + notifyError(error) { + runtime_1.assert(!this.closed, 'stream is closed'); + this._closed = error; + this.pushIt(error); + this._lis.err.forEach(l => l(error)); + this._lis.nxt.forEach(l => l(undefined, error, false)); + this.clearLis(); + } + /** + * Closes the stream successfully. Throws if stream is closed. + * + * Triggers onNext and onComplete callbacks. + */ + notifyComplete() { + runtime_1.assert(!this.closed, 'stream is closed'); + this._closed = true; + this.pushIt({ value: null, done: true }); + this._lis.cmp.forEach(l => l()); + this._lis.nxt.forEach(l => l(undefined, undefined, true)); + this.clearLis(); + } + /** + * Creates an async iterator (that can be used with `for await {...}`) + * to consume the stream. + * + * Some things to note: + * - If an error occurs, the `for await` will throw it. + * - If an error occurred before the `for await` was started, `for await` + * will re-throw it. + * - If the stream is already complete, the `for await` will be empty. + * - If your `for await` consumes slower than the stream produces, + * for example because you are relaying messages in a slow operation, + * messages are queued. + */ + [Symbol.asyncIterator]() { + // init the iterator state, enabling pushIt() + if (!this._itState) { + this._itState = { q: [] }; + } + // if we are closed, we are definitely not receiving any more messages. + // but we can't let the iterator get stuck. we want to either: + // a) finish the new iterator immediately, because we are completed + // b) reject the new iterator, because we errored + if (this._closed === true) + this.pushIt({ value: null, done: true }); + else if (this._closed !== false) + this.pushIt(this._closed); + // the async iterator + return { + next: () => { + let state = this._itState; + runtime_1.assert(state, "bad state"); // if we don't have a state here, code is broken + // there should be no pending result. + // did the consumer call next() before we resolved our previous result promise? + runtime_1.assert(!state.p, "iterator contract broken"); + // did we produce faster than the iterator consumed? + // return the oldest result from the queue. + let first = state.q.shift(); + if (first) + return ("value" in first) ? Promise.resolve(first) : Promise.reject(first); + // we have no result ATM, but we promise one. + // as soon as we have a result, we must resolve promise. + state.p = new deferred_1.Deferred(); + return state.p.promise; + }, + }; + } + // "push" a new iterator result. + // this either resolves a pending promise, or enqueues the result. + pushIt(result) { + let state = this._itState; + if (!state) + return; + // is the consumer waiting for us? + if (state.p) { + // yes, consumer is waiting for this promise. + const p = state.p; + runtime_1.assert(p.state == deferred_1.DeferredState.PENDING, "iterator contract broken"); + // resolve the promise + ("value" in result) ? p.resolve(result) : p.reject(result); + // must cleanup, otherwise iterator.next() would pick it up again. + delete state.p; + } + else { + // we are producing faster than the iterator consumes. + // push result onto queue. + state.q.push(result); + } + } } +exports.RpcOutputStreamController = RpcOutputStreamController; -async function authenticatedPost(endpoint, opts, { - clientAssertionPayload, endpointAuthMethod = endpoint, DPoP, -} = {}) { - const auth = await authFor.call(this, endpointAuthMethod, { clientAssertionPayload }); - const requestOpts = merge(opts, auth); - const mTLS = this[`${endpointAuthMethod}_endpoint_auth_method`].includes('tls_client_auth') - || (endpoint === 'token' && this.tls_client_certificate_bound_access_tokens); +/***/ }), - let targetUrl; - if (mTLS && this.issuer.mtls_endpoint_aliases) { - targetUrl = this.issuer.mtls_endpoint_aliases[`${endpoint}_endpoint`]; - } +/***/ 25320: +/***/ ((__unused_webpack_module, exports) => { - targetUrl = targetUrl || this.issuer[`${endpoint}_endpoint`]; +"use strict"; - if ('form' in requestOpts) { - for (const [key, value] of Object.entries(requestOpts.form)) { // eslint-disable-line no-restricted-syntax, max-len - if (typeof value === 'undefined') { - delete requestOpts.form[key]; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ServerCallContextController = void 0; +class ServerCallContextController { + constructor(method, headers, deadline, sendResponseHeadersFn, defaultStatus = { code: 'OK', detail: '' }) { + this._cancelled = false; + this._listeners = []; + this.method = method; + this.headers = headers; + this.deadline = deadline; + this.trailers = {}; + this._sendRH = sendResponseHeadersFn; + this.status = defaultStatus; + } + /** + * Set the call cancelled. + * + * Invokes all callbacks registered with onCancel() and + * sets `cancelled = true`. + */ + notifyCancelled() { + if (!this._cancelled) { + this._cancelled = true; + for (let l of this._listeners) { + l(); + } + } + } + /** + * Send response headers. + */ + sendResponseHeaders(data) { + this._sendRH(data); + } + /** + * Is the call cancelled? + * + * When the client closes the connection before the server + * is done, the call is cancelled. + * + * If you want to cancel a request on the server, throw a + * RpcError with the CANCELLED status code. + */ + get cancelled() { + return this._cancelled; + } + /** + * Add a callback for cancellation. + */ + onCancel(callback) { + const l = this._listeners; + l.push(callback); + return () => { + let i = l.indexOf(callback); + if (i >= 0) + l.splice(i, 1); + }; } - } - - return request.call(this, { - ...requestOpts, - method: 'POST', - url: targetUrl, - }, { mTLS, DPoP }); } - -module.exports = { - resolveResponseType, - resolveRedirectUri, - authFor, - authenticatedPost, -}; +exports.ServerCallContextController = ServerCallContextController; /***/ }), -/***/ 6144: -/***/ ((module) => { - -const OIDC_DISCOVERY = '/.well-known/openid-configuration'; -const OAUTH2_DISCOVERY = '/.well-known/oauth-authorization-server'; -const WEBFINGER = '/.well-known/webfinger'; -const REL = 'http://openid.net/specs/connect/1.0/issuer'; -const AAD_MULTITENANT_DISCOVERY = [ - `https://login.microsoftonline.com/common${OIDC_DISCOVERY}`, - `https://login.microsoftonline.com/common/v2.0${OIDC_DISCOVERY}`, - `https://login.microsoftonline.com/organizations/v2.0${OIDC_DISCOVERY}`, - `https://login.microsoftonline.com/consumers/v2.0${OIDC_DISCOVERY}`, -]; - -const CLIENT_DEFAULTS = { - grant_types: ['authorization_code'], - id_token_signed_response_alg: 'RS256', - authorization_signed_response_alg: 'RS256', - response_types: ['code'], - token_endpoint_auth_method: 'client_secret_basic', -}; - -const ISSUER_DEFAULTS = { - claim_types_supported: ['normal'], - claims_parameter_supported: false, - grant_types_supported: ['authorization_code', 'implicit'], - request_parameter_supported: false, - request_uri_parameter_supported: true, - require_request_uri_registration: false, - response_modes_supported: ['query', 'fragment'], - token_endpoint_auth_methods_supported: ['client_secret_basic'], -}; - -const CALLBACK_PROPERTIES = [ - 'access_token', // 6749 - 'code', // 6749 - 'error', // 6749 - 'error_description', // 6749 - 'error_uri', // 6749 - 'expires_in', // 6749 - 'id_token', // Core 1.0 - 'state', // 6749 - 'token_type', // 6749 - 'session_state', // Session Management - 'response', // JARM -]; - -const JWT_CONTENT = /^application\/jwt/; +/***/ 30066: +/***/ (function(__unused_webpack_module, exports) { -const HTTP_OPTIONS = Symbol('openid-client.custom.http-options'); -const CLOCK_TOLERANCE = Symbol('openid-client.custom.clock-tolerance'); +"use strict"; -module.exports = { - AAD_MULTITENANT_DISCOVERY, - CALLBACK_PROPERTIES, - CLIENT_DEFAULTS, - CLOCK_TOLERANCE, - HTTP_OPTIONS, - ISSUER_DEFAULTS, - JWT_CONTENT, - OAUTH2_DISCOVERY, - OIDC_DISCOVERY, - REL, - WEBFINGER, +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ServerStreamingCall = void 0; +/** + * A server streaming RPC call. The client provides exactly one input message + * but the server may respond with 0, 1, or more messages. + */ +class ServerStreamingCall { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.request = request; + this.headers = headers; + this.responses = response; + this.status = status; + this.trailers = trailers; + } + /** + * Instead of awaiting the response status and trailers, you can + * just as well await this call itself to receive the server outcome. + * You should first setup some listeners to the `request` to + * see the actual messages the server replied with. + */ + then(onfulfilled, onrejected) { + return this.promiseFinished().then(value => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, reason => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter(this, void 0, void 0, function* () { + let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + request: this.request, + headers, + status, + trailers, + }; + }); + } +} +exports.ServerStreamingCall = ServerStreamingCall; /***/ }), -/***/ 85618: -/***/ ((module) => { - -module.exports = (obj) => JSON.parse(JSON.stringify(obj)); - - -/***/ }), - -/***/ 44129: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/* eslint-disable no-restricted-syntax, no-continue */ - -const isPlainObject = __nccwpck_require__(89717); +/***/ 14107: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function defaults(deep, target, ...sources) { - for (const source of sources) { - if (!isPlainObject(source)) { - continue; - } - for (const [key, value] of Object.entries(source)) { - /* istanbul ignore if */ - if (key === '__proto__' || key === 'constructor') { - continue; - } - if (typeof target[key] === 'undefined' && typeof value !== 'undefined') { - target[key] = value; - } +"use strict"; - if (deep && isPlainObject(target[key]) && isPlainObject(value)) { - defaults(true, target[key], value); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ServiceType = void 0; +const reflection_info_1 = __nccwpck_require__(44331); +class ServiceType { + constructor(typeName, methods, options) { + this.typeName = typeName; + this.methods = methods.map(i => reflection_info_1.normalizeMethodInfo(i, this)); + this.options = options !== null && options !== void 0 ? options : {}; } - } - - return target; } - -module.exports = defaults.bind(undefined, false); -module.exports.deep = defaults.bind(undefined, true); +exports.ServiceType = ServiceType; /***/ }), -/***/ 65894: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { createHash, randomBytes } = __nccwpck_require__(6113); - -const base64url = __nccwpck_require__(23570); +/***/ 87008: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -const random = (bytes = 32) => base64url.encode(randomBytes(bytes)); +"use strict"; -module.exports = { - random, - state: random, - nonce: random, - codeVerifier: random, - codeChallenge: (codeVerifier) => base64url.encode(createHash('sha256').update(codeVerifier).digest()), +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TestTransport = void 0; +const rpc_error_1 = __nccwpck_require__(63159); +const runtime_1 = __nccwpck_require__(4061); +const rpc_output_stream_1 = __nccwpck_require__(76637); +const rpc_options_1 = __nccwpck_require__(67386); +const unary_call_1 = __nccwpck_require__(84175); +const server_streaming_call_1 = __nccwpck_require__(30066); +const client_streaming_call_1 = __nccwpck_require__(29912); +const duplex_streaming_call_1 = __nccwpck_require__(17042); +/** + * Transport for testing. + */ +class TestTransport { + /** + * Initialize with mock data. Omitted fields have default value. + */ + constructor(data) { + /** + * Suppress warning / error about uncaught rejections of + * "status" and "trailers". + */ + this.suppressUncaughtRejections = true; + this.headerDelay = 10; + this.responseDelay = 50; + this.betweenResponseDelay = 10; + this.afterResponseDelay = 10; + this.data = data !== null && data !== void 0 ? data : {}; + } + /** + * Sent message(s) during the last operation. + */ + get sentMessages() { + if (this.lastInput instanceof TestInputStream) { + return this.lastInput.sent; + } + else if (typeof this.lastInput == "object") { + return [this.lastInput.single]; + } + return []; + } + /** + * Sending message(s) completed? + */ + get sendComplete() { + if (this.lastInput instanceof TestInputStream) { + return this.lastInput.completed; + } + else if (typeof this.lastInput == "object") { + return true; + } + return false; + } + // Creates a promise for response headers from the mock data. + promiseHeaders() { + var _a; + const headers = (_a = this.data.headers) !== null && _a !== void 0 ? _a : TestTransport.defaultHeaders; + return headers instanceof rpc_error_1.RpcError + ? Promise.reject(headers) + : Promise.resolve(headers); + } + // Creates a promise for a single, valid, message from the mock data. + promiseSingleResponse(method) { + if (this.data.response instanceof rpc_error_1.RpcError) { + return Promise.reject(this.data.response); + } + let r; + if (Array.isArray(this.data.response)) { + runtime_1.assert(this.data.response.length > 0); + r = this.data.response[0]; + } + else if (this.data.response !== undefined) { + r = this.data.response; + } + else { + r = method.O.create(); + } + runtime_1.assert(method.O.is(r)); + return Promise.resolve(r); + } + /** + * Pushes response messages from the mock data to the output stream. + * If an error response, status or trailers are mocked, the stream is + * closed with the respective error. + * Otherwise, stream is completed successfully. + * + * The returned promise resolves when the stream is closed. It should + * not reject. If it does, code is broken. + */ + streamResponses(method, stream, abort) { + return __awaiter(this, void 0, void 0, function* () { + // normalize "data.response" into an array of valid output messages + const messages = []; + if (this.data.response === undefined) { + messages.push(method.O.create()); + } + else if (Array.isArray(this.data.response)) { + for (let msg of this.data.response) { + runtime_1.assert(method.O.is(msg)); + messages.push(msg); + } + } + else if (!(this.data.response instanceof rpc_error_1.RpcError)) { + runtime_1.assert(method.O.is(this.data.response)); + messages.push(this.data.response); + } + // start the stream with an initial delay. + // if the request is cancelled, notify() error and exit. + try { + yield delay(this.responseDelay, abort)(undefined); + } + catch (error) { + stream.notifyError(error); + return; + } + // if error response was mocked, notify() error (stream is now closed with error) and exit. + if (this.data.response instanceof rpc_error_1.RpcError) { + stream.notifyError(this.data.response); + return; + } + // regular response messages were mocked. notify() them. + for (let msg of messages) { + stream.notifyMessage(msg); + // add a short delay between responses + // if the request is cancelled, notify() error and exit. + try { + yield delay(this.betweenResponseDelay, abort)(undefined); + } + catch (error) { + stream.notifyError(error); + return; + } + } + // error status was mocked, notify() error (stream is now closed with error) and exit. + if (this.data.status instanceof rpc_error_1.RpcError) { + stream.notifyError(this.data.status); + return; + } + // error trailers were mocked, notify() error (stream is now closed with error) and exit. + if (this.data.trailers instanceof rpc_error_1.RpcError) { + stream.notifyError(this.data.trailers); + return; + } + // stream completed successfully + stream.notifyComplete(); + }); + } + // Creates a promise for response status from the mock data. + promiseStatus() { + var _a; + const status = (_a = this.data.status) !== null && _a !== void 0 ? _a : TestTransport.defaultStatus; + return status instanceof rpc_error_1.RpcError + ? Promise.reject(status) + : Promise.resolve(status); + } + // Creates a promise for response trailers from the mock data. + promiseTrailers() { + var _a; + const trailers = (_a = this.data.trailers) !== null && _a !== void 0 ? _a : TestTransport.defaultTrailers; + return trailers instanceof rpc_error_1.RpcError + ? Promise.reject(trailers) + : Promise.resolve(trailers); + } + maybeSuppressUncaught(...promise) { + if (this.suppressUncaughtRejections) { + for (let p of promise) { + p.catch(() => { + }); + } + } + } + mergeOptions(options) { + return rpc_options_1.mergeRpcOptions({}, options); + } + unary(method, input, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders() + .then(delay(this.headerDelay, options.abort)), responsePromise = headersPromise + .catch(_ => { + }) + .then(delay(this.responseDelay, options.abort)) + .then(_ => this.promiseSingleResponse(method)), statusPromise = responsePromise + .catch(_ => { + }) + .then(delay(this.afterResponseDelay, options.abort)) + .then(_ => this.promiseStatus()), trailersPromise = responsePromise + .catch(_ => { + }) + .then(delay(this.afterResponseDelay, options.abort)) + .then(_ => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = { single: input }; + return new unary_call_1.UnaryCall(method, requestHeaders, input, headersPromise, responsePromise, statusPromise, trailersPromise); + } + serverStreaming(method, input, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders() + .then(delay(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise + .then(delay(this.responseDelay, options.abort)) + .catch(() => { + }) + .then(() => this.streamResponses(method, outputStream, options.abort)) + .then(delay(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise + .then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise + .then(() => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = { single: input }; + return new server_streaming_call_1.ServerStreamingCall(method, requestHeaders, input, headersPromise, outputStream, statusPromise, trailersPromise); + } + clientStreaming(method, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders() + .then(delay(this.headerDelay, options.abort)), responsePromise = headersPromise + .catch(_ => { + }) + .then(delay(this.responseDelay, options.abort)) + .then(_ => this.promiseSingleResponse(method)), statusPromise = responsePromise + .catch(_ => { + }) + .then(delay(this.afterResponseDelay, options.abort)) + .then(_ => this.promiseStatus()), trailersPromise = responsePromise + .catch(_ => { + }) + .then(delay(this.afterResponseDelay, options.abort)) + .then(_ => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = new TestInputStream(this.data, options.abort); + return new client_streaming_call_1.ClientStreamingCall(method, requestHeaders, this.lastInput, headersPromise, responsePromise, statusPromise, trailersPromise); + } + duplex(method, options) { + var _a; + const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders() + .then(delay(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise + .then(delay(this.responseDelay, options.abort)) + .catch(() => { + }) + .then(() => this.streamResponses(method, outputStream, options.abort)) + .then(delay(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise + .then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise + .then(() => this.promiseTrailers()); + this.maybeSuppressUncaught(statusPromise, trailersPromise); + this.lastInput = new TestInputStream(this.data, options.abort); + return new duplex_streaming_call_1.DuplexStreamingCall(method, requestHeaders, this.lastInput, headersPromise, outputStream, statusPromise, trailersPromise); + } +} +exports.TestTransport = TestTransport; +TestTransport.defaultHeaders = { + responseHeader: "test" +}; +TestTransport.defaultStatus = { + code: "OK", detail: "all good" +}; +TestTransport.defaultTrailers = { + responseTrailer: "test" }; +function delay(ms, abort) { + return (v) => new Promise((resolve, reject) => { + if (abort === null || abort === void 0 ? void 0 : abort.aborted) { + reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); + } + else { + const id = setTimeout(() => resolve(v), ms); + if (abort) { + abort.addEventListener("abort", ev => { + clearTimeout(id); + reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); + }); + } + } + }); +} +class TestInputStream { + constructor(data, abort) { + this._completed = false; + this._sent = []; + this.data = data; + this.abort = abort; + } + get sent() { + return this._sent; + } + get completed() { + return this._completed; + } + send(message) { + if (this.data.inputMessage instanceof rpc_error_1.RpcError) { + return Promise.reject(this.data.inputMessage); + } + const delayMs = this.data.inputMessage === undefined + ? 10 + : this.data.inputMessage; + return Promise.resolve(undefined) + .then(() => { + this._sent.push(message); + }) + .then(delay(delayMs, this.abort)); + } + complete() { + if (this.data.inputComplete instanceof rpc_error_1.RpcError) { + return Promise.reject(this.data.inputComplete); + } + const delayMs = this.data.inputComplete === undefined + ? 10 + : this.data.inputComplete; + return Promise.resolve(undefined) + .then(() => { + this._completed = true; + }) + .then(delay(delayMs, this.abort)); + } +} /***/ }), -/***/ 61758: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 84175: +/***/ (function(__unused_webpack_module, exports) { -const url = __nccwpck_require__(57310); -const { strict: assert } = __nccwpck_require__(39491); +"use strict"; -module.exports = (target) => { - try { - const { protocol } = new url.URL(target); - assert(protocol.match(/^(https?:)$/)); - return true; - } catch (err) { - throw new TypeError('only valid absolute URLs can be requested'); - } +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.UnaryCall = void 0; +/** + * A unary RPC call. Unary means there is exactly one input message and + * exactly one output message unless an error occurred. + */ +class UnaryCall { + constructor(method, requestHeaders, request, headers, response, status, trailers) { + this.method = method; + this.requestHeaders = requestHeaders; + this.request = request; + this.headers = headers; + this.response = response; + this.status = status; + this.trailers = trailers; + } + /** + * If you are only interested in the final outcome of this call, + * you can await it to receive a `FinishedUnaryCall`. + */ + then(onfulfilled, onrejected) { + return this.promiseFinished().then(value => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, reason => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + } + promiseFinished() { + return __awaiter(this, void 0, void 0, function* () { + let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); + return { + method: this.method, + requestHeaders: this.requestHeaders, + request: this.request, + headers, + response, + status, + trailers + }; + }); + } +} +exports.UnaryCall = UnaryCall; /***/ }), -/***/ 89717: -/***/ ((module) => { +/***/ 54253: +/***/ ((__unused_webpack_module, exports) => { -module.exports = (a) => !!a && a.constructor === Object; +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.assertFloat32 = exports.assertUInt32 = exports.assertInt32 = exports.assertNever = exports.assert = void 0; +/** + * assert that condition is true or throw error (with message) + */ +function assert(condition, msg) { + if (!condition) { + throw new Error(msg); + } +} +exports.assert = assert; +/** + * assert that value cannot exist = type `never`. throw runtime error if it does. + */ +function assertNever(value, msg) { + throw new Error(msg !== null && msg !== void 0 ? msg : 'Unexpected object: ' + value); +} +exports.assertNever = assertNever; +const FLOAT32_MAX = 3.4028234663852886e+38, FLOAT32_MIN = -3.4028234663852886e+38, UINT32_MAX = 0xFFFFFFFF, INT32_MAX = 0X7FFFFFFF, INT32_MIN = -0X80000000; +function assertInt32(arg) { + if (typeof arg !== "number") + throw new Error('invalid int 32: ' + typeof arg); + if (!Number.isInteger(arg) || arg > INT32_MAX || arg < INT32_MIN) + throw new Error('invalid int 32: ' + arg); +} +exports.assertInt32 = assertInt32; +function assertUInt32(arg) { + if (typeof arg !== "number") + throw new Error('invalid uint 32: ' + typeof arg); + if (!Number.isInteger(arg) || arg > UINT32_MAX || arg < 0) + throw new Error('invalid uint 32: ' + arg); +} +exports.assertUInt32 = assertUInt32; +function assertFloat32(arg) { + if (typeof arg !== "number") + throw new Error('invalid float 32: ' + typeof arg); + if (!Number.isFinite(arg)) + return; + if (arg > FLOAT32_MAX || arg < FLOAT32_MIN) + throw new Error('invalid float 32: ' + arg); +} +exports.assertFloat32 = assertFloat32; /***/ }), -/***/ 71839: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/* eslint-disable no-restricted-syntax, no-param-reassign, no-continue */ +/***/ 20196: +/***/ ((__unused_webpack_module, exports) => { -const isPlainObject = __nccwpck_require__(89717); +"use strict"; -function merge(target, ...sources) { - for (const source of sources) { - if (!isPlainObject(source)) { - continue; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.base64encode = exports.base64decode = void 0; +// lookup table from base64 character to byte +let encTable = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); +// lookup table from base64 character *code* to byte because lookup by number is fast +let decTable = []; +for (let i = 0; i < encTable.length; i++) + decTable[encTable[i].charCodeAt(0)] = i; +// support base64url variants +decTable["-".charCodeAt(0)] = encTable.indexOf("+"); +decTable["_".charCodeAt(0)] = encTable.indexOf("/"); +/** + * Decodes a base64 string to a byte array. + * + * - ignores white-space, including line breaks and tabs + * - allows inner padding (can decode concatenated base64 strings) + * - does not require padding + * - understands base64url encoding: + * "-" instead of "+", + * "_" instead of "/", + * no padding + */ +function base64decode(base64Str) { + // estimate byte size, not accounting for inner padding and whitespace + let es = base64Str.length * 3 / 4; + // if (es % 3 !== 0) + // throw new Error('invalid base64 string'); + if (base64Str[base64Str.length - 2] == '=') + es -= 2; + else if (base64Str[base64Str.length - 1] == '=') + es -= 1; + let bytes = new Uint8Array(es), bytePos = 0, // position in byte array + groupPos = 0, // position in base64 group + b, // current byte + p = 0 // previous byte + ; + for (let i = 0; i < base64Str.length; i++) { + b = decTable[base64Str.charCodeAt(i)]; + if (b === undefined) { + // noinspection FallThroughInSwitchStatementJS + switch (base64Str[i]) { + case '=': + groupPos = 0; // reset state when padding found + case '\n': + case '\r': + case '\t': + case ' ': + continue; // skip white-space, and padding + default: + throw Error(`invalid base64 string.`); + } + } + switch (groupPos) { + case 0: + p = b; + groupPos = 1; + break; + case 1: + bytes[bytePos++] = p << 2 | (b & 48) >> 4; + p = b; + groupPos = 2; + break; + case 2: + bytes[bytePos++] = (p & 15) << 4 | (b & 60) >> 2; + p = b; + groupPos = 3; + break; + case 3: + bytes[bytePos++] = (p & 3) << 6 | b; + groupPos = 0; + break; + } } - for (const [key, value] of Object.entries(source)) { - /* istanbul ignore if */ - if (key === '__proto__' || key === 'constructor') { - continue; - } - if (isPlainObject(target[key]) && isPlainObject(value)) { - target[key] = merge(target[key], value); - } else if (typeof value !== 'undefined') { - target[key] = value; - } + if (groupPos == 1) + throw Error(`invalid base64 string.`); + return bytes.subarray(0, bytePos); +} +exports.base64decode = base64decode; +/** + * Encodes a byte array to a base64 string. + * Adds padding at the end. + * Does not insert newlines. + */ +function base64encode(bytes) { + let base64 = '', groupPos = 0, // position in base64 group + b, // current byte + p = 0; // carry over from previous byte + for (let i = 0; i < bytes.length; i++) { + b = bytes[i]; + switch (groupPos) { + case 0: + base64 += encTable[b >> 2]; + p = (b & 3) << 4; + groupPos = 1; + break; + case 1: + base64 += encTable[p | b >> 4]; + p = (b & 15) << 2; + groupPos = 2; + break; + case 2: + base64 += encTable[p | b >> 6]; + base64 += encTable[b & 63]; + groupPos = 0; + break; + } } - } - - return target; + // padding required? + if (groupPos) { + base64 += encTable[p]; + base64 += '='; + if (groupPos == 1) + base64 += '='; + } + return base64; } - -module.exports = merge; +exports.base64encode = base64encode; /***/ }), -/***/ 70260: -/***/ ((module) => { - -module.exports = function pick(object, ...paths) { - const obj = {}; - for (const path of paths) { // eslint-disable-line no-restricted-syntax - if (object[path]) { - obj[path] = object[path]; - } - } - return obj; -}; +/***/ 84921: +/***/ ((__unused_webpack_module, exports) => { +"use strict"; -/***/ }), +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.WireType = exports.mergeBinaryOptions = exports.UnknownFieldHandler = void 0; +/** + * This handler implements the default behaviour for unknown fields. + * When reading data, unknown fields are stored on the message, in a + * symbol property. + * When writing data, the symbol property is queried and unknown fields + * are serialized into the output again. + */ +var UnknownFieldHandler; +(function (UnknownFieldHandler) { + /** + * The symbol used to store unknown fields for a message. + * The property must conform to `UnknownFieldContainer`. + */ + UnknownFieldHandler.symbol = Symbol.for("protobuf-ts/unknown"); + /** + * Store an unknown field during binary read directly on the message. + * This method is compatible with `BinaryReadOptions.readUnknownField`. + */ + UnknownFieldHandler.onRead = (typeName, message, fieldNo, wireType, data) => { + let container = is(message) ? message[UnknownFieldHandler.symbol] : message[UnknownFieldHandler.symbol] = []; + container.push({ no: fieldNo, wireType, data }); + }; + /** + * Write unknown fields stored for the message to the writer. + * This method is compatible with `BinaryWriteOptions.writeUnknownFields`. + */ + UnknownFieldHandler.onWrite = (typeName, message, writer) => { + for (let { no, wireType, data } of UnknownFieldHandler.list(message)) + writer.tag(no, wireType).raw(data); + }; + /** + * List unknown fields stored for the message. + * Note that there may be multiples fields with the same number. + */ + UnknownFieldHandler.list = (message, fieldNo) => { + if (is(message)) { + let all = message[UnknownFieldHandler.symbol]; + return fieldNo ? all.filter(uf => uf.no == fieldNo) : all; + } + return []; + }; + /** + * Returns the last unknown field by field number. + */ + UnknownFieldHandler.last = (message, fieldNo) => UnknownFieldHandler.list(message, fieldNo).slice(-1)[0]; + const is = (message) => message && Array.isArray(message[UnknownFieldHandler.symbol]); +})(UnknownFieldHandler = exports.UnknownFieldHandler || (exports.UnknownFieldHandler = {})); +/** + * Merges binary write or read options. Later values override earlier values. + */ +function mergeBinaryOptions(a, b) { + return Object.assign(Object.assign({}, a), b); +} +exports.mergeBinaryOptions = mergeBinaryOptions; +/** + * Protobuf binary format wire types. + * + * A wire type provides just enough information to find the length of the + * following value. + * + * See https://developers.google.com/protocol-buffers/docs/encoding#structure + */ +var WireType; +(function (WireType) { + /** + * Used for int32, int64, uint32, uint64, sint32, sint64, bool, enum + */ + WireType[WireType["Varint"] = 0] = "Varint"; + /** + * Used for fixed64, sfixed64, double. + * Always 8 bytes with little-endian byte order. + */ + WireType[WireType["Bit64"] = 1] = "Bit64"; + /** + * Used for string, bytes, embedded messages, packed repeated fields + * + * Only repeated numeric types (types which use the varint, 32-bit, + * or 64-bit wire types) can be packed. In proto3, such fields are + * packed by default. + */ + WireType[WireType["LengthDelimited"] = 2] = "LengthDelimited"; + /** + * Used for groups + * @deprecated + */ + WireType[WireType["StartGroup"] = 3] = "StartGroup"; + /** + * Used for groups + * @deprecated + */ + WireType[WireType["EndGroup"] = 4] = "EndGroup"; + /** + * Used for fixed32, sfixed32, float. + * Always 4 bytes with little-endian byte order. + */ + WireType[WireType["Bit32"] = 5] = "Bit32"; +})(WireType = exports.WireType || (exports.WireType = {})); -/***/ 59980: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const { STATUS_CODES } = __nccwpck_require__(13685); -const { format } = __nccwpck_require__(73837); +/***/ }), -const { OPError } = __nccwpck_require__(31151); +/***/ 65210: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const REGEXP = /(\w+)=("[^"]*")/g; -const throwAuthenticateErrors = (response) => { - const params = {}; - try { - while ((REGEXP.exec(response.headers['www-authenticate'])) !== null) { - if (RegExp.$1 && RegExp.$2) { - params[RegExp.$1] = RegExp.$2.slice(1, -1); - } - } - } catch (err) {} +"use strict"; - if (params.error) { - throw new OPError(params, response); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BinaryReader = exports.binaryReadOptions = void 0; +const binary_format_contract_1 = __nccwpck_require__(84921); +const pb_long_1 = __nccwpck_require__(47777); +const goog_varint_1 = __nccwpck_require__(30433); +const defaultsRead = { + readUnknownField: true, + readerFactory: bytes => new BinaryReader(bytes), }; - -const isStandardBodyError = (response) => { - let result = false; - try { - let jsonbody; - if (typeof response.body !== 'object' || Buffer.isBuffer(response.body)) { - jsonbody = JSON.parse(response.body); - } else { - jsonbody = response.body; +/** + * Make options for reading binary data form partial options. + */ +function binaryReadOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; +} +exports.binaryReadOptions = binaryReadOptions; +class BinaryReader { + constructor(buf, textDecoder) { + this.varint64 = goog_varint_1.varint64read; // dirty cast for `this` + /** + * Read a `uint32` field, an unsigned 32 bit varint. + */ + this.uint32 = goog_varint_1.varint32read; // dirty cast for `this` and access to protected `buf` + this.buf = buf; + this.len = buf.length; + this.pos = 0; + this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength); + this.textDecoder = textDecoder !== null && textDecoder !== void 0 ? textDecoder : new TextDecoder("utf-8", { + fatal: true, + ignoreBOM: true, + }); } - result = typeof jsonbody.error === 'string' && jsonbody.error.length; - if (result) response.body = jsonbody; - } catch (err) {} - - return result; -}; - -function processResponse(response, { statusCode = 200, body = true, bearer = false } = {}) { - if (response.statusCode !== statusCode) { - if (bearer) { - throwAuthenticateErrors(response); + /** + * Reads a tag - field number and wire type. + */ + tag() { + let tag = this.uint32(), fieldNo = tag >>> 3, wireType = tag & 7; + if (fieldNo <= 0 || wireType < 0 || wireType > 5) + throw new Error("illegal tag: field no " + fieldNo + " wire type " + wireType); + return [fieldNo, wireType]; } - - if (isStandardBodyError(response)) { - throw new OPError(response.body, response); + /** + * Skip one element on the wire and return the skipped data. + * Supports WireType.StartGroup since v2.0.0-alpha.23. + */ + skip(wireType) { + let start = this.pos; + // noinspection FallThroughInSwitchStatementJS + switch (wireType) { + case binary_format_contract_1.WireType.Varint: + while (this.buf[this.pos++] & 0x80) { + // ignore + } + break; + case binary_format_contract_1.WireType.Bit64: + this.pos += 4; + case binary_format_contract_1.WireType.Bit32: + this.pos += 4; + break; + case binary_format_contract_1.WireType.LengthDelimited: + let len = this.uint32(); + this.pos += len; + break; + case binary_format_contract_1.WireType.StartGroup: + // From descriptor.proto: Group type is deprecated, not supported in proto3. + // But we must still be able to parse and treat as unknown. + let t; + while ((t = this.tag()[1]) !== binary_format_contract_1.WireType.EndGroup) { + this.skip(t); + } + break; + default: + throw new Error("cant skip wire type " + wireType); + } + this.assertBounds(); + return this.buf.subarray(start, this.pos); + } + /** + * Throws error if position in byte array is out of range. + */ + assertBounds() { + if (this.pos > this.len) + throw new RangeError("premature EOF"); + } + /** + * Read a `int32` field, a signed 32 bit varint. + */ + int32() { + return this.uint32() | 0; + } + /** + * Read a `sint32` field, a signed, zigzag-encoded 32-bit varint. + */ + sint32() { + let zze = this.uint32(); + // decode zigzag + return (zze >>> 1) ^ -(zze & 1); + } + /** + * Read a `int64` field, a signed 64-bit varint. + */ + int64() { + return new pb_long_1.PbLong(...this.varint64()); + } + /** + * Read a `uint64` field, an unsigned 64-bit varint. + */ + uint64() { + return new pb_long_1.PbULong(...this.varint64()); + } + /** + * Read a `sint64` field, a signed, zig-zag-encoded 64-bit varint. + */ + sint64() { + let [lo, hi] = this.varint64(); + // decode zig zag + let s = -(lo & 1); + lo = ((lo >>> 1 | (hi & 1) << 31) ^ s); + hi = (hi >>> 1 ^ s); + return new pb_long_1.PbLong(lo, hi); + } + /** + * Read a `bool` field, a variant. + */ + bool() { + let [lo, hi] = this.varint64(); + return lo !== 0 || hi !== 0; + } + /** + * Read a `fixed32` field, an unsigned, fixed-length 32-bit integer. + */ + fixed32() { + return this.view.getUint32((this.pos += 4) - 4, true); + } + /** + * Read a `sfixed32` field, a signed, fixed-length 32-bit integer. + */ + sfixed32() { + return this.view.getInt32((this.pos += 4) - 4, true); + } + /** + * Read a `fixed64` field, an unsigned, fixed-length 64 bit integer. + */ + fixed64() { + return new pb_long_1.PbULong(this.sfixed32(), this.sfixed32()); + } + /** + * Read a `fixed64` field, a signed, fixed-length 64-bit integer. + */ + sfixed64() { + return new pb_long_1.PbLong(this.sfixed32(), this.sfixed32()); + } + /** + * Read a `float` field, 32-bit floating point number. + */ + float() { + return this.view.getFloat32((this.pos += 4) - 4, true); + } + /** + * Read a `double` field, a 64-bit floating point number. + */ + double() { + return this.view.getFloat64((this.pos += 8) - 8, true); + } + /** + * Read a `bytes` field, length-delimited arbitrary data. + */ + bytes() { + let len = this.uint32(); + let start = this.pos; + this.pos += len; + this.assertBounds(); + return this.buf.subarray(start, start + len); + } + /** + * Read a `string` field, length-delimited data converted to UTF-8 text. + */ + string() { + return this.textDecoder.decode(this.bytes()); } - - throw new OPError({ - error: format('expected %i %s, got: %i %s', statusCode, STATUS_CODES[statusCode], response.statusCode, STATUS_CODES[response.statusCode]), - }, response); - } - - if (body && !response.body) { - throw new OPError({ - error: format('expected %i %s with body but no body was returned', statusCode, STATUS_CODES[statusCode]), - }, response); - } - - return response.body; } - -module.exports = processResponse; +exports.BinaryReader = BinaryReader; /***/ }), -/***/ 8048: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const Got = __nccwpck_require__(93061); - -const pkg = __nccwpck_require__(51513); - -const { deep: defaultsDeep } = __nccwpck_require__(44129); -const isAbsoluteUrl = __nccwpck_require__(61758); -const { HTTP_OPTIONS } = __nccwpck_require__(6144); - -let DEFAULT_HTTP_OPTIONS; -let got; - -const setDefaults = (options) => { - DEFAULT_HTTP_OPTIONS = defaultsDeep({}, options, DEFAULT_HTTP_OPTIONS); - got = Got.extend(DEFAULT_HTTP_OPTIONS); -}; - -setDefaults({ - followRedirect: false, - headers: { 'User-Agent': `${pkg.name}/${pkg.version} (${pkg.homepage})` }, - retry: 0, - timeout: 3500, - throwHttpErrors: false, -}); - -module.exports = async function request(options, { accessToken, mTLS = false, DPoP } = {}) { - const { url } = options; - isAbsoluteUrl(url); - const optsFn = this[HTTP_OPTIONS]; - let opts = options; - - if (DPoP && 'dpopProof' in this) { - opts.headers = opts.headers || {}; - opts.headers.DPoP = this.dpopProof({ - htu: url, - htm: options.method, - }, DPoP, accessToken); - } - - if (optsFn) { - opts = optsFn.call(this, defaultsDeep({}, opts, DEFAULT_HTTP_OPTIONS)); - } +/***/ 44354: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if ( - mTLS - && ( - (!opts.key || !opts.cert) - && (!opts.https || !((opts.https.key && opts.https.certificate) || opts.https.pfx)) - ) - ) { - throw new TypeError('mutual-TLS certificate and key not set'); - } +"use strict"; - return got(opts); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BinaryWriter = exports.binaryWriteOptions = void 0; +const pb_long_1 = __nccwpck_require__(47777); +const goog_varint_1 = __nccwpck_require__(30433); +const assert_1 = __nccwpck_require__(54253); +const defaultsWrite = { + writeUnknownFields: true, + writerFactory: () => new BinaryWriter(), }; - -module.exports.setDefaults = setDefaults; - - -/***/ }), - -/***/ 24393: -/***/ ((module) => { - -module.exports = () => Math.floor(Date.now() / 1000); +/** + * Make options for writing binary data form partial options. + */ +function binaryWriteOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; +} +exports.binaryWriteOptions = binaryWriteOptions; +class BinaryWriter { + constructor(textEncoder) { + /** + * Previous fork states. + */ + this.stack = []; + this.textEncoder = textEncoder !== null && textEncoder !== void 0 ? textEncoder : new TextEncoder(); + this.chunks = []; + this.buf = []; + } + /** + * Return all bytes written and reset this writer. + */ + finish() { + this.chunks.push(new Uint8Array(this.buf)); // flush the buffer + let len = 0; + for (let i = 0; i < this.chunks.length; i++) + len += this.chunks[i].length; + let bytes = new Uint8Array(len); + let offset = 0; + for (let i = 0; i < this.chunks.length; i++) { + bytes.set(this.chunks[i], offset); + offset += this.chunks[i].length; + } + this.chunks = []; + return bytes; + } + /** + * Start a new fork for length-delimited data like a message + * or a packed repeated field. + * + * Must be joined later with `join()`. + */ + fork() { + this.stack.push({ chunks: this.chunks, buf: this.buf }); + this.chunks = []; + this.buf = []; + return this; + } + /** + * Join the last fork. Write its length and bytes, then + * return to the previous state. + */ + join() { + // get chunk of fork + let chunk = this.finish(); + // restore previous state + let prev = this.stack.pop(); + if (!prev) + throw new Error('invalid state, fork stack empty'); + this.chunks = prev.chunks; + this.buf = prev.buf; + // write length of chunk as varint + this.uint32(chunk.byteLength); + return this.raw(chunk); + } + /** + * Writes a tag (field number and wire type). + * + * Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`. + * + * Generated code should compute the tag ahead of time and call `uint32()`. + */ + tag(fieldNo, type) { + return this.uint32((fieldNo << 3 | type) >>> 0); + } + /** + * Write a chunk of raw bytes. + */ + raw(chunk) { + if (this.buf.length) { + this.chunks.push(new Uint8Array(this.buf)); + this.buf = []; + } + this.chunks.push(chunk); + return this; + } + /** + * Write a `uint32` value, an unsigned 32 bit varint. + */ + uint32(value) { + assert_1.assertUInt32(value); + // write value as varint 32, inlined for speed + while (value > 0x7f) { + this.buf.push((value & 0x7f) | 0x80); + value = value >>> 7; + } + this.buf.push(value); + return this; + } + /** + * Write a `int32` value, a signed 32 bit varint. + */ + int32(value) { + assert_1.assertInt32(value); + goog_varint_1.varint32write(value, this.buf); + return this; + } + /** + * Write a `bool` value, a variant. + */ + bool(value) { + this.buf.push(value ? 1 : 0); + return this; + } + /** + * Write a `bytes` value, length-delimited arbitrary data. + */ + bytes(value) { + this.uint32(value.byteLength); // write length of chunk as varint + return this.raw(value); + } + /** + * Write a `string` value, length-delimited data converted to UTF-8 text. + */ + string(value) { + let chunk = this.textEncoder.encode(value); + this.uint32(chunk.byteLength); // write length of chunk as varint + return this.raw(chunk); + } + /** + * Write a `float` value, 32-bit floating point number. + */ + float(value) { + assert_1.assertFloat32(value); + let chunk = new Uint8Array(4); + new DataView(chunk.buffer).setFloat32(0, value, true); + return this.raw(chunk); + } + /** + * Write a `double` value, a 64-bit floating point number. + */ + double(value) { + let chunk = new Uint8Array(8); + new DataView(chunk.buffer).setFloat64(0, value, true); + return this.raw(chunk); + } + /** + * Write a `fixed32` value, an unsigned, fixed-length 32-bit integer. + */ + fixed32(value) { + assert_1.assertUInt32(value); + let chunk = new Uint8Array(4); + new DataView(chunk.buffer).setUint32(0, value, true); + return this.raw(chunk); + } + /** + * Write a `sfixed32` value, a signed, fixed-length 32-bit integer. + */ + sfixed32(value) { + assert_1.assertInt32(value); + let chunk = new Uint8Array(4); + new DataView(chunk.buffer).setInt32(0, value, true); + return this.raw(chunk); + } + /** + * Write a `sint32` value, a signed, zigzag-encoded 32-bit varint. + */ + sint32(value) { + assert_1.assertInt32(value); + // zigzag encode + value = ((value << 1) ^ (value >> 31)) >>> 0; + goog_varint_1.varint32write(value, this.buf); + return this; + } + /** + * Write a `fixed64` value, a signed, fixed-length 64-bit integer. + */ + sfixed64(value) { + let chunk = new Uint8Array(8); + let view = new DataView(chunk.buffer); + let long = pb_long_1.PbLong.from(value); + view.setInt32(0, long.lo, true); + view.setInt32(4, long.hi, true); + return this.raw(chunk); + } + /** + * Write a `fixed64` value, an unsigned, fixed-length 64 bit integer. + */ + fixed64(value) { + let chunk = new Uint8Array(8); + let view = new DataView(chunk.buffer); + let long = pb_long_1.PbULong.from(value); + view.setInt32(0, long.lo, true); + view.setInt32(4, long.hi, true); + return this.raw(chunk); + } + /** + * Write a `int64` value, a signed 64-bit varint. + */ + int64(value) { + let long = pb_long_1.PbLong.from(value); + goog_varint_1.varint64write(long.lo, long.hi, this.buf); + return this; + } + /** + * Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint. + */ + sint64(value) { + let long = pb_long_1.PbLong.from(value), + // zigzag encode + sign = long.hi >> 31, lo = (long.lo << 1) ^ sign, hi = ((long.hi << 1) | (long.lo >>> 31)) ^ sign; + goog_varint_1.varint64write(lo, hi, this.buf); + return this; + } + /** + * Write a `uint64` value, an unsigned 64-bit varint. + */ + uint64(value) { + let long = pb_long_1.PbULong.from(value); + goog_varint_1.varint64write(long.lo, long.hi, this.buf); + return this; + } +} +exports.BinaryWriter = BinaryWriter; /***/ }), -/***/ 69020: -/***/ ((module) => { +/***/ 20085: +/***/ ((__unused_webpack_module, exports) => { -const privateProps = new WeakMap(); +"use strict"; -module.exports = (ctx) => { - if (!privateProps.has(ctx)) { - privateProps.set(ctx, new Map([['metadata', new Map()]])); - } - return privateProps.get(ctx); -}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.listEnumNumbers = exports.listEnumNames = exports.listEnumValues = exports.isEnumObject = void 0; +/** + * Is this a lookup object generated by Typescript, for a Typescript enum + * generated by protobuf-ts? + * + * - No `const enum` (enum must not be inlined, we need reverse mapping). + * - No string enum (we need int32 for protobuf). + * - Must have a value for 0 (otherwise, we would need to support custom default values). + */ +function isEnumObject(arg) { + if (typeof arg != 'object' || arg === null) { + return false; + } + if (!arg.hasOwnProperty(0)) { + return false; + } + for (let k of Object.keys(arg)) { + let num = parseInt(k); + if (!Number.isNaN(num)) { + // is there a name for the number? + let nam = arg[num]; + if (nam === undefined) + return false; + // does the name resolve back to the number? + if (arg[nam] !== num) + return false; + } + else { + // is there a number for the name? + let num = arg[k]; + if (num === undefined) + return false; + // is it a string enum? + if (typeof num !== 'number') + return false; + // do we know the number? + if (arg[num] === undefined) + return false; + } + } + return true; +} +exports.isEnumObject = isEnumObject; +/** + * Lists all values of a Typescript enum, as an array of objects with a "name" + * property and a "number" property. + * + * Note that it is possible that a number appears more than once, because it is + * possible to have aliases in an enum. + * + * Throws if the enum does not adhere to the rules of enums generated by + * protobuf-ts. See `isEnumObject()`. + */ +function listEnumValues(enumObject) { + if (!isEnumObject(enumObject)) + throw new Error("not a typescript enum object"); + let values = []; + for (let [name, number] of Object.entries(enumObject)) + if (typeof number == "number") + values.push({ name, number }); + return values; +} +exports.listEnumValues = listEnumValues; +/** + * Lists the names of a Typescript enum. + * + * Throws if the enum does not adhere to the rules of enums generated by + * protobuf-ts. See `isEnumObject()`. + */ +function listEnumNames(enumObject) { + return listEnumValues(enumObject).map(val => val.name); +} +exports.listEnumNames = listEnumNames; +/** + * Lists the numbers of a Typescript enum. + * + * Throws if the enum does not adhere to the rules of enums generated by + * protobuf-ts. See `isEnumObject()`. + */ +function listEnumNumbers(enumObject) { + return listEnumValues(enumObject) + .map(val => val.number) + .filter((num, index, arr) => arr.indexOf(num) == index); +} +exports.listEnumNumbers = listEnumNumbers; /***/ }), -/***/ 10304: -/***/ ((module) => { +/***/ 30433: +/***/ ((__unused_webpack_module, exports) => { -// Credit: https://github.com/rohe/pyoidc/blob/master/src/oic/utils/webfinger.py +"use strict"; -// -- Normalization -- -// A string of any other type is interpreted as a URI either the form of scheme -// "://" authority path-abempty [ "?" query ] [ "#" fragment ] or authority -// path-abempty [ "?" query ] [ "#" fragment ] per RFC 3986 [RFC3986] and is -// normalized according to the following rules: +// Copyright 2008 Google Inc. All rights reserved. // -// If the user input Identifier does not have an RFC 3986 [RFC3986] scheme -// portion, the string is interpreted as [userinfo "@"] host [":" port] -// path-abempty [ "?" query ] [ "#" fragment ] per RFC 3986 [RFC3986]. -// If the userinfo component is present and all of the path component, query -// component, and port component are empty, the acct scheme is assumed. In this -// case, the normalized URI is formed by prefixing acct: to the string as the -// scheme. Per the 'acct' URI Scheme [I‑D.ietf‑appsawg‑acct‑uri], if there is an -// at-sign character ('@') in the userinfo component, it needs to be -// percent-encoded as described in RFC 3986 [RFC3986]. -// For all other inputs without a scheme portion, the https scheme is assumed, -// and the normalized URI is formed by prefixing https:// to the string as the -// scheme. -// If the resulting URI contains a fragment portion, it MUST be stripped off -// together with the fragment delimiter character "#". -// The WebFinger [I‑D.ietf‑appsawg‑webfinger] Resource in this case is the -// resulting URI, and the WebFinger Host is the authority component. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: // -// Note: Since the definition of authority in RFC 3986 [RFC3986] is -// [ userinfo "@" ] host [ ":" port ], it is legal to have a user input -// identifier like userinfo@host:port, e.g., alice@example.com:8080. - -const PORT = /^\d+$/; - -function hasScheme(input) { - if (input.includes('://')) return true; - - const authority = input.replace(/(\/|\?)/g, '#').split('#')[0]; - if (authority.includes(':')) { - const index = authority.indexOf(':'); - const hostOrPort = authority.slice(index + 1); - if (!PORT.test(hostOrPort)) { - return true; +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Code generated by the Protocol Buffer compiler is owned by the owner +// of the input file used when generating it. This code is not +// standalone and requires a support library to be linked with it. This +// support library is itself covered by the above license. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.varint32read = exports.varint32write = exports.int64toString = exports.int64fromString = exports.varint64write = exports.varint64read = void 0; +/** + * Read a 64 bit varint as two JS numbers. + * + * Returns tuple: + * [0]: low bits + * [0]: high bits + * + * Copyright 2008 Google Inc. All rights reserved. + * + * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L175 + */ +function varint64read() { + let lowBits = 0; + let highBits = 0; + for (let shift = 0; shift < 28; shift += 7) { + let b = this.buf[this.pos++]; + lowBits |= (b & 0x7F) << shift; + if ((b & 0x80) == 0) { + this.assertBounds(); + return [lowBits, highBits]; + } } - } - - return false; + let middleByte = this.buf[this.pos++]; + // last four bits of the first 32 bit number + lowBits |= (middleByte & 0x0F) << 28; + // 3 upper bits are part of the next 32 bit number + highBits = (middleByte & 0x70) >> 4; + if ((middleByte & 0x80) == 0) { + this.assertBounds(); + return [lowBits, highBits]; + } + for (let shift = 3; shift <= 31; shift += 7) { + let b = this.buf[this.pos++]; + highBits |= (b & 0x7F) << shift; + if ((b & 0x80) == 0) { + this.assertBounds(); + return [lowBits, highBits]; + } + } + throw new Error('invalid varint'); } - -function acctSchemeAssumed(input) { - if (!input.includes('@')) return false; - const parts = input.split('@'); - const host = parts[parts.length - 1]; - return !(host.includes(':') || host.includes('/') || host.includes('?')); +exports.varint64read = varint64read; +/** + * Write a 64 bit varint, given as two JS numbers, to the given bytes array. + * + * Copyright 2008 Google Inc. All rights reserved. + * + * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/writer.js#L344 + */ +function varint64write(lo, hi, bytes) { + for (let i = 0; i < 28; i = i + 7) { + const shift = lo >>> i; + const hasNext = !((shift >>> 7) == 0 && hi == 0); + const byte = (hasNext ? shift | 0x80 : shift) & 0xFF; + bytes.push(byte); + if (!hasNext) { + return; + } + } + const splitBits = ((lo >>> 28) & 0x0F) | ((hi & 0x07) << 4); + const hasMoreBits = !((hi >> 3) == 0); + bytes.push((hasMoreBits ? splitBits | 0x80 : splitBits) & 0xFF); + if (!hasMoreBits) { + return; + } + for (let i = 3; i < 31; i = i + 7) { + const shift = hi >>> i; + const hasNext = !((shift >>> 7) == 0); + const byte = (hasNext ? shift | 0x80 : shift) & 0xFF; + bytes.push(byte); + if (!hasNext) { + return; + } + } + bytes.push((hi >>> 31) & 0x01); } - -function normalize(input) { - if (typeof input !== 'string') { - throw new TypeError('input must be a string'); - } - - let output; - if (hasScheme(input)) { - output = input; - } else if (acctSchemeAssumed(input)) { - output = `acct:${input}`; - } else { - output = `https://${input}`; - } - - return output.split('#')[0]; -} - -module.exports = normalize; - - -/***/ }), - -/***/ 22881: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const Issuer = __nccwpck_require__(14470); -const { OPError, RPError } = __nccwpck_require__(31151); -const Registry = __nccwpck_require__(70011); -const Strategy = __nccwpck_require__(84114); -const TokenSet = __nccwpck_require__(14974); -const { CLOCK_TOLERANCE, HTTP_OPTIONS } = __nccwpck_require__(6144); -const generators = __nccwpck_require__(65894); -const { setDefaults } = __nccwpck_require__(8048); - -module.exports = { - Issuer, - Registry, - Strategy, - TokenSet, - errors: { - OPError, - RPError, - }, - custom: { - setHttpOptionsDefaults: setDefaults, - http_options: HTTP_OPTIONS, - clock_tolerance: CLOCK_TOLERANCE, - }, - generators, -}; - - -/***/ }), - -/***/ 14470: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/* eslint-disable max-classes-per-file */ - -const { inspect } = __nccwpck_require__(73837); -const url = __nccwpck_require__(57310); - -const AggregateError = __nccwpck_require__(61231); -const jose = __nccwpck_require__(87115); -const LRU = __nccwpck_require__(7129); -const objectHash = __nccwpck_require__(24856); - -const { RPError } = __nccwpck_require__(31151); -const getClient = __nccwpck_require__(49609); -const registry = __nccwpck_require__(70011); -const processResponse = __nccwpck_require__(59980); -const webfingerNormalize = __nccwpck_require__(10304); -const instance = __nccwpck_require__(69020); -const request = __nccwpck_require__(8048); -const { assertIssuerConfiguration } = __nccwpck_require__(68973); -const { - ISSUER_DEFAULTS, OIDC_DISCOVERY, OAUTH2_DISCOVERY, WEBFINGER, REL, AAD_MULTITENANT_DISCOVERY, -} = __nccwpck_require__(6144); - -const AAD_MULTITENANT = Symbol('AAD_MULTITENANT'); - -class Issuer { - /** - * @name constructor - * @api public - */ - constructor(meta = {}) { - const aadIssValidation = meta[AAD_MULTITENANT]; - delete meta[AAD_MULTITENANT]; - - ['introspection', 'revocation'].forEach((endpoint) => { - // if intro/revocation endpoint auth specific meta is missing use the token ones if they - // are defined - if ( - meta[`${endpoint}_endpoint`] - && meta[`${endpoint}_endpoint_auth_methods_supported`] === undefined - && meta[`${endpoint}_endpoint_auth_signing_alg_values_supported`] === undefined - ) { - if (meta.token_endpoint_auth_methods_supported) { - meta[`${endpoint}_endpoint_auth_methods_supported`] = meta.token_endpoint_auth_methods_supported; - } - if (meta.token_endpoint_auth_signing_alg_values_supported) { - meta[`${endpoint}_endpoint_auth_signing_alg_values_supported`] = meta.token_endpoint_auth_signing_alg_values_supported; +exports.varint64write = varint64write; +// constants for binary math +const TWO_PWR_32_DBL = (1 << 16) * (1 << 16); +/** + * Parse decimal string of 64 bit integer value as two JS numbers. + * + * Returns tuple: + * [0]: minus sign? + * [1]: low bits + * [2]: high bits + * + * Copyright 2008 Google Inc. + */ +function int64fromString(dec) { + // Check for minus sign. + let minus = dec[0] == '-'; + if (minus) + dec = dec.slice(1); + // Work 6 decimal digits at a time, acting like we're converting base 1e6 + // digits to binary. This is safe to do with floating point math because + // Number.isSafeInteger(ALL_32_BITS * 1e6) == true. + const base = 1e6; + let lowBits = 0; + let highBits = 0; + function add1e6digit(begin, end) { + // Note: Number('') is 0. + const digit1e6 = Number(dec.slice(begin, end)); + highBits *= base; + lowBits = lowBits * base + digit1e6; + // Carry bits from lowBits to highBits + if (lowBits >= TWO_PWR_32_DBL) { + highBits = highBits + ((lowBits / TWO_PWR_32_DBL) | 0); + lowBits = lowBits % TWO_PWR_32_DBL; } - } - }); - - Object.entries(meta).forEach(([key, value]) => { - instance(this).get('metadata').set(key, value); - if (!this[key]) { - Object.defineProperty(this, key, { - get() { return instance(this).get('metadata').get(key); }, - enumerable: true, - }); - } - }); - - instance(this).set('cache', new LRU({ max: 100 })); - - registry.set(this.issuer, this); - - const Client = getClient(this, aadIssValidation); - - Object.defineProperties(this, { - Client: { value: Client }, - FAPIClient: { value: class FAPIClient extends Client {} }, - }); - } - - /** - * @name keystore - * @api public - */ - async keystore(reload = false) { - assertIssuerConfiguration(this, 'jwks_uri'); - - const keystore = instance(this).get('keystore'); - const cache = instance(this).get('cache'); - - if (reload || !keystore) { - cache.reset(); - const response = await request.call(this, { - method: 'GET', - responseType: 'json', - url: this.jwks_uri, - }); - const jwks = processResponse(response); - - const joseKeyStore = jose.JWKS.asKeyStore(jwks, { ignoreErrors: true }); - cache.set('throttle', true, 60 * 1000); - instance(this).set('keystore', joseKeyStore); - return joseKeyStore; } - - return keystore; - } - - /** - * @name queryKeyStore - * @api private - */ - async queryKeyStore({ - kid, kty, alg, use, key_ops: ops, - }, { allowMulti = false } = {}) { - const cache = instance(this).get('cache'); - - const def = { - kid, kty, alg, use, key_ops: ops, - }; - - const defHash = objectHash(def, { - algorithm: 'sha256', - ignoreUnknown: true, - unorderedArrays: true, - unorderedSets: true, - }); - - // refresh keystore on every unknown key but also only upto once every minute - const freshJwksUri = cache.get(defHash) || cache.get('throttle'); - - const keystore = await this.keystore(!freshJwksUri); - const keys = keystore.all(def); - - if (keys.length === 0) { - throw new RPError({ - printf: ["no valid key found in issuer's jwks_uri for key parameters %j", def], - jwks: keystore, - }); + add1e6digit(-24, -18); + add1e6digit(-18, -12); + add1e6digit(-12, -6); + add1e6digit(-6); + return [minus, lowBits, highBits]; +} +exports.int64fromString = int64fromString; +/** + * Format 64 bit integer value (as two JS numbers) to decimal string. + * + * Copyright 2008 Google Inc. + */ +function int64toString(bitsLow, bitsHigh) { + // Skip the expensive conversion if the number is small enough to use the + // built-in conversions. + if ((bitsHigh >>> 0) <= 0x1FFFFF) { + return '' + (TWO_PWR_32_DBL * bitsHigh + (bitsLow >>> 0)); } - - if (!allowMulti && keys.length > 1 && !kid) { - throw new RPError({ - printf: ["multiple matching keys found in issuer's jwks_uri for key parameters %j, kid must be provided in this case", def], - jwks: keystore, - }); + // What this code is doing is essentially converting the input number from + // base-2 to base-1e7, which allows us to represent the 64-bit range with + // only 3 (very large) digits. Those digits are then trivial to convert to + // a base-10 string. + // The magic numbers used here are - + // 2^24 = 16777216 = (1,6777216) in base-1e7. + // 2^48 = 281474976710656 = (2,8147497,6710656) in base-1e7. + // Split 32:32 representation into 16:24:24 representation so our + // intermediate digits don't overflow. + let low = bitsLow & 0xFFFFFF; + let mid = (((bitsLow >>> 24) | (bitsHigh << 8)) >>> 0) & 0xFFFFFF; + let high = (bitsHigh >> 16) & 0xFFFF; + // Assemble our three base-1e7 digits, ignoring carries. The maximum + // value in a digit at this step is representable as a 48-bit integer, which + // can be stored in a 64-bit floating point number. + let digitA = low + (mid * 6777216) + (high * 6710656); + let digitB = mid + (high * 8147497); + let digitC = (high * 2); + // Apply carries from A to B and from B to C. + let base = 10000000; + if (digitA >= base) { + digitB += Math.floor(digitA / base); + digitA %= base; } - - cache.set(defHash, true); - - return new jose.JWKS.KeyStore(keys); - } - - /** - * @name metadata - * @api public - */ - get metadata() { - const copy = {}; - instance(this).get('metadata').forEach((value, key) => { - copy[key] = value; - }); - return copy; - } - - /** - * @name webfinger - * @api public - */ - static async webfinger(input) { - const resource = webfingerNormalize(input); - const { host } = url.parse(resource); - const webfingerUrl = `https://${host}${WEBFINGER}`; - - const response = await request.call(this, { - method: 'GET', - url: webfingerUrl, - responseType: 'json', - searchParams: { resource, rel: REL }, - followRedirect: true, - }); - const body = processResponse(response); - - const location = Array.isArray(body.links) && body.links.find((link) => typeof link === 'object' && link.rel === REL && link.href); - - if (!location) { - throw new RPError({ - message: 'no issuer found in webfinger response', - body, - }); + if (digitB >= base) { + digitC += Math.floor(digitB / base); + digitB %= base; } - - if (typeof location.href !== 'string' || !location.href.startsWith('https://')) { - throw new RPError({ - printf: ['invalid issuer location %s', location.href], - body, - }); + // Convert base-1e7 digits to base-10, with optional leading zeroes. + function decimalFrom1e7(digit1e7, needLeadingZeros) { + let partial = digit1e7 ? String(digit1e7) : ''; + if (needLeadingZeros) { + return '0000000'.slice(partial.length) + partial; + } + return partial; } - - const expectedIssuer = location.href; - if (registry.has(expectedIssuer)) { - return registry.get(expectedIssuer); + return decimalFrom1e7(digitC, /*needLeadingZeros=*/ 0) + + decimalFrom1e7(digitB, /*needLeadingZeros=*/ digitC) + + // If the final 1e7 digit didn't need leading zeros, we would have + // returned via the trivial code path at the top. + decimalFrom1e7(digitA, /*needLeadingZeros=*/ 1); +} +exports.int64toString = int64toString; +/** + * Write a 32 bit varint, signed or unsigned. Same as `varint64write(0, value, bytes)` + * + * Copyright 2008 Google Inc. All rights reserved. + * + * See https://github.com/protocolbuffers/protobuf/blob/1b18833f4f2a2f681f4e4a25cdf3b0a43115ec26/js/binary/encoder.js#L144 + */ +function varint32write(value, bytes) { + if (value >= 0) { + // write value as varint 32 + while (value > 0x7f) { + bytes.push((value & 0x7f) | 0x80); + value = value >>> 7; + } + bytes.push(value); } - - const issuer = await this.discover(expectedIssuer); - - if (issuer.issuer !== expectedIssuer) { - registry.delete(issuer.issuer); - throw new RPError('discovered issuer mismatch, expected %s, got: %s', expectedIssuer, issuer.issuer); + else { + for (let i = 0; i < 9; i++) { + bytes.push(value & 127 | 128); + value = value >> 7; + } + bytes.push(1); } - return issuer; - } - - /** - * @name discover - * @api public - */ - static async discover(uri) { - const parsed = url.parse(uri); - - if (parsed.pathname.includes('/.well-known/')) { - const response = await request.call(this, { - method: 'GET', - responseType: 'json', - url: uri, - }); - const body = processResponse(response); - return new Issuer({ - ...ISSUER_DEFAULTS, - ...body, - [AAD_MULTITENANT]: !!AAD_MULTITENANT_DISCOVERY.find( - (discoveryURL) => uri.startsWith(discoveryURL), - ), - }); +} +exports.varint32write = varint32write; +/** + * Read an unsigned 32 bit varint. + * + * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L220 + */ +function varint32read() { + let b = this.buf[this.pos++]; + let result = b & 0x7F; + if ((b & 0x80) == 0) { + this.assertBounds(); + return result; } - - const pathnames = []; - if (parsed.pathname.endsWith('/')) { - pathnames.push(`${parsed.pathname}${OIDC_DISCOVERY.substring(1)}`); - } else { - pathnames.push(`${parsed.pathname}${OIDC_DISCOVERY}`); + b = this.buf[this.pos++]; + result |= (b & 0x7F) << 7; + if ((b & 0x80) == 0) { + this.assertBounds(); + return result; } - if (parsed.pathname === '/') { - pathnames.push(`${OAUTH2_DISCOVERY}`); - } else { - pathnames.push(`${OAUTH2_DISCOVERY}${parsed.pathname}`); + b = this.buf[this.pos++]; + result |= (b & 0x7F) << 14; + if ((b & 0x80) == 0) { + this.assertBounds(); + return result; } - - const errors = []; - // eslint-disable-next-line no-restricted-syntax - for (const pathname of pathnames) { - try { - const wellKnownUri = url.format({ ...parsed, pathname }); - // eslint-disable-next-line no-await-in-loop - const response = await request.call(this, { - method: 'GET', - responseType: 'json', - url: wellKnownUri, - }); - const body = processResponse(response); - return new Issuer({ - ...ISSUER_DEFAULTS, - ...body, - [AAD_MULTITENANT]: !!AAD_MULTITENANT_DISCOVERY.find( - (discoveryURL) => wellKnownUri.startsWith(discoveryURL), - ), - }); - } catch (err) { - errors.push(err); - } + b = this.buf[this.pos++]; + result |= (b & 0x7F) << 21; + if ((b & 0x80) == 0) { + this.assertBounds(); + return result; } - - const err = new AggregateError(errors); - err.message = `Issuer.discover() failed.${err.message.split('\n') - .filter((line) => !line.startsWith(' at')).join('\n')}`; - throw err; - } - - /* istanbul ignore next */ - [inspect.custom]() { - return `${this.constructor.name} ${inspect(this.metadata, { - depth: Infinity, - colors: process.stdout.isTTY, - compact: false, - sorted: true, - })}`; - } + // Extract only last 4 bits + b = this.buf[this.pos++]; + result |= (b & 0x0F) << 28; + for (let readBytes = 5; ((b & 0x80) !== 0) && readBytes < 10; readBytes++) + b = this.buf[this.pos++]; + if ((b & 0x80) != 0) + throw new Error('invalid varint'); + this.assertBounds(); + // Result can have 32 bits, convert it to unsigned + return result >>> 0; } - -module.exports = Issuer; +exports.varint32read = varint32read; /***/ }), -/***/ 70011: -/***/ ((module) => { +/***/ 4061: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const REGISTRY = new Map(); +"use strict"; -module.exports = REGISTRY; +// Public API of the protobuf-ts runtime. +// Note: we do not use `export * from ...` to help tree shakers, +// webpack verbose output hints that this should be useful +Object.defineProperty(exports, "__esModule", ({ value: true })); +// Convenience JSON typings and corresponding type guards +var json_typings_1 = __nccwpck_require__(70661); +Object.defineProperty(exports, "typeofJsonValue", ({ enumerable: true, get: function () { return json_typings_1.typeofJsonValue; } })); +Object.defineProperty(exports, "isJsonObject", ({ enumerable: true, get: function () { return json_typings_1.isJsonObject; } })); +// Base 64 encoding +var base64_1 = __nccwpck_require__(20196); +Object.defineProperty(exports, "base64decode", ({ enumerable: true, get: function () { return base64_1.base64decode; } })); +Object.defineProperty(exports, "base64encode", ({ enumerable: true, get: function () { return base64_1.base64encode; } })); +// UTF8 encoding +var protobufjs_utf8_1 = __nccwpck_require__(95290); +Object.defineProperty(exports, "utf8read", ({ enumerable: true, get: function () { return protobufjs_utf8_1.utf8read; } })); +// Binary format contracts, options for reading and writing, for example +var binary_format_contract_1 = __nccwpck_require__(84921); +Object.defineProperty(exports, "WireType", ({ enumerable: true, get: function () { return binary_format_contract_1.WireType; } })); +Object.defineProperty(exports, "mergeBinaryOptions", ({ enumerable: true, get: function () { return binary_format_contract_1.mergeBinaryOptions; } })); +Object.defineProperty(exports, "UnknownFieldHandler", ({ enumerable: true, get: function () { return binary_format_contract_1.UnknownFieldHandler; } })); +// Standard IBinaryReader implementation +var binary_reader_1 = __nccwpck_require__(65210); +Object.defineProperty(exports, "BinaryReader", ({ enumerable: true, get: function () { return binary_reader_1.BinaryReader; } })); +Object.defineProperty(exports, "binaryReadOptions", ({ enumerable: true, get: function () { return binary_reader_1.binaryReadOptions; } })); +// Standard IBinaryWriter implementation +var binary_writer_1 = __nccwpck_require__(44354); +Object.defineProperty(exports, "BinaryWriter", ({ enumerable: true, get: function () { return binary_writer_1.BinaryWriter; } })); +Object.defineProperty(exports, "binaryWriteOptions", ({ enumerable: true, get: function () { return binary_writer_1.binaryWriteOptions; } })); +// Int64 and UInt64 implementations required for the binary format +var pb_long_1 = __nccwpck_require__(47777); +Object.defineProperty(exports, "PbLong", ({ enumerable: true, get: function () { return pb_long_1.PbLong; } })); +Object.defineProperty(exports, "PbULong", ({ enumerable: true, get: function () { return pb_long_1.PbULong; } })); +// JSON format contracts, options for reading and writing, for example +var json_format_contract_1 = __nccwpck_require__(48139); +Object.defineProperty(exports, "jsonReadOptions", ({ enumerable: true, get: function () { return json_format_contract_1.jsonReadOptions; } })); +Object.defineProperty(exports, "jsonWriteOptions", ({ enumerable: true, get: function () { return json_format_contract_1.jsonWriteOptions; } })); +Object.defineProperty(exports, "mergeJsonOptions", ({ enumerable: true, get: function () { return json_format_contract_1.mergeJsonOptions; } })); +// Message type contract +var message_type_contract_1 = __nccwpck_require__(1682); +Object.defineProperty(exports, "MESSAGE_TYPE", ({ enumerable: true, get: function () { return message_type_contract_1.MESSAGE_TYPE; } })); +// Message type implementation via reflection +var message_type_1 = __nccwpck_require__(63664); +Object.defineProperty(exports, "MessageType", ({ enumerable: true, get: function () { return message_type_1.MessageType; } })); +// Reflection info, generated by the plugin, exposed to the user, used by reflection ops +var reflection_info_1 = __nccwpck_require__(21370); +Object.defineProperty(exports, "ScalarType", ({ enumerable: true, get: function () { return reflection_info_1.ScalarType; } })); +Object.defineProperty(exports, "LongType", ({ enumerable: true, get: function () { return reflection_info_1.LongType; } })); +Object.defineProperty(exports, "RepeatType", ({ enumerable: true, get: function () { return reflection_info_1.RepeatType; } })); +Object.defineProperty(exports, "normalizeFieldInfo", ({ enumerable: true, get: function () { return reflection_info_1.normalizeFieldInfo; } })); +Object.defineProperty(exports, "readFieldOptions", ({ enumerable: true, get: function () { return reflection_info_1.readFieldOptions; } })); +Object.defineProperty(exports, "readFieldOption", ({ enumerable: true, get: function () { return reflection_info_1.readFieldOption; } })); +Object.defineProperty(exports, "readMessageOption", ({ enumerable: true, get: function () { return reflection_info_1.readMessageOption; } })); +// Message operations via reflection +var reflection_type_check_1 = __nccwpck_require__(20903); +Object.defineProperty(exports, "ReflectionTypeCheck", ({ enumerable: true, get: function () { return reflection_type_check_1.ReflectionTypeCheck; } })); +var reflection_create_1 = __nccwpck_require__(60390); +Object.defineProperty(exports, "reflectionCreate", ({ enumerable: true, get: function () { return reflection_create_1.reflectionCreate; } })); +var reflection_scalar_default_1 = __nccwpck_require__(74863); +Object.defineProperty(exports, "reflectionScalarDefault", ({ enumerable: true, get: function () { return reflection_scalar_default_1.reflectionScalarDefault; } })); +var reflection_merge_partial_1 = __nccwpck_require__(7869); +Object.defineProperty(exports, "reflectionMergePartial", ({ enumerable: true, get: function () { return reflection_merge_partial_1.reflectionMergePartial; } })); +var reflection_equals_1 = __nccwpck_require__(39473); +Object.defineProperty(exports, "reflectionEquals", ({ enumerable: true, get: function () { return reflection_equals_1.reflectionEquals; } })); +var reflection_binary_reader_1 = __nccwpck_require__(91593); +Object.defineProperty(exports, "ReflectionBinaryReader", ({ enumerable: true, get: function () { return reflection_binary_reader_1.ReflectionBinaryReader; } })); +var reflection_binary_writer_1 = __nccwpck_require__(57170); +Object.defineProperty(exports, "ReflectionBinaryWriter", ({ enumerable: true, get: function () { return reflection_binary_writer_1.ReflectionBinaryWriter; } })); +var reflection_json_reader_1 = __nccwpck_require__(229); +Object.defineProperty(exports, "ReflectionJsonReader", ({ enumerable: true, get: function () { return reflection_json_reader_1.ReflectionJsonReader; } })); +var reflection_json_writer_1 = __nccwpck_require__(68980); +Object.defineProperty(exports, "ReflectionJsonWriter", ({ enumerable: true, get: function () { return reflection_json_writer_1.ReflectionJsonWriter; } })); +var reflection_contains_message_type_1 = __nccwpck_require__(67317); +Object.defineProperty(exports, "containsMessageType", ({ enumerable: true, get: function () { return reflection_contains_message_type_1.containsMessageType; } })); +// Oneof helpers +var oneof_1 = __nccwpck_require__(78531); +Object.defineProperty(exports, "isOneofGroup", ({ enumerable: true, get: function () { return oneof_1.isOneofGroup; } })); +Object.defineProperty(exports, "setOneofValue", ({ enumerable: true, get: function () { return oneof_1.setOneofValue; } })); +Object.defineProperty(exports, "getOneofValue", ({ enumerable: true, get: function () { return oneof_1.getOneofValue; } })); +Object.defineProperty(exports, "clearOneofValue", ({ enumerable: true, get: function () { return oneof_1.clearOneofValue; } })); +Object.defineProperty(exports, "getSelectedOneofValue", ({ enumerable: true, get: function () { return oneof_1.getSelectedOneofValue; } })); +// Enum object type guard and reflection util, may be interesting to the user. +var enum_object_1 = __nccwpck_require__(20085); +Object.defineProperty(exports, "listEnumValues", ({ enumerable: true, get: function () { return enum_object_1.listEnumValues; } })); +Object.defineProperty(exports, "listEnumNames", ({ enumerable: true, get: function () { return enum_object_1.listEnumNames; } })); +Object.defineProperty(exports, "listEnumNumbers", ({ enumerable: true, get: function () { return enum_object_1.listEnumNumbers; } })); +Object.defineProperty(exports, "isEnumObject", ({ enumerable: true, get: function () { return enum_object_1.isEnumObject; } })); +// lowerCamelCase() is exported for plugin, rpc-runtime and other rpc packages +var lower_camel_case_1 = __nccwpck_require__(34772); +Object.defineProperty(exports, "lowerCamelCase", ({ enumerable: true, get: function () { return lower_camel_case_1.lowerCamelCase; } })); +// assertion functions are exported for plugin, may also be useful to user +var assert_1 = __nccwpck_require__(54253); +Object.defineProperty(exports, "assert", ({ enumerable: true, get: function () { return assert_1.assert; } })); +Object.defineProperty(exports, "assertNever", ({ enumerable: true, get: function () { return assert_1.assertNever; } })); +Object.defineProperty(exports, "assertInt32", ({ enumerable: true, get: function () { return assert_1.assertInt32; } })); +Object.defineProperty(exports, "assertUInt32", ({ enumerable: true, get: function () { return assert_1.assertUInt32; } })); +Object.defineProperty(exports, "assertFloat32", ({ enumerable: true, get: function () { return assert_1.assertFloat32; } })); /***/ }), -/***/ 84114: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/* eslint-disable no-underscore-dangle */ - -const url = __nccwpck_require__(57310); -const { format } = __nccwpck_require__(73837); +/***/ 48139: +/***/ ((__unused_webpack_module, exports) => { -const cloneDeep = __nccwpck_require__(85618); -const { RPError, OPError } = __nccwpck_require__(31151); -const { BaseClient } = __nccwpck_require__(49609); -const { random, codeChallenge } = __nccwpck_require__(65894); -const pick = __nccwpck_require__(70260); -const { resolveResponseType, resolveRedirectUri } = __nccwpck_require__(26633); +"use strict"; -function verified(err, user, info = {}) { - if (err) { - this.error(err); - } else if (!user) { - this.fail(info); - } else { - this.success(user, info); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.mergeJsonOptions = exports.jsonWriteOptions = exports.jsonReadOptions = void 0; +const defaultsWrite = { + emitDefaultValues: false, + enumAsInteger: false, + useProtoFieldName: false, + prettySpaces: 0, +}, defaultsRead = { + ignoreUnknownFields: false, +}; +/** + * Make options for reading JSON data from partial options. + */ +function jsonReadOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; } - +exports.jsonReadOptions = jsonReadOptions; /** - * @name constructor - * @api public + * Make options for writing JSON data from partial options. */ -function OpenIDConnectStrategy({ - client, - params = {}, - passReqToCallback = false, - sessionKey, - usePKCE = true, - extras = {}, -} = {}, verify) { - if (!(client instanceof BaseClient)) { - throw new TypeError('client must be an instance of openid-client Client'); - } - - if (typeof verify !== 'function') { - throw new TypeError('verify callback must be a function'); - } +function jsonWriteOptions(options) { + return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; +} +exports.jsonWriteOptions = jsonWriteOptions; +/** + * Merges JSON write or read options. Later values override earlier values. Type registries are merged. + */ +function mergeJsonOptions(a, b) { + var _a, _b; + let c = Object.assign(Object.assign({}, a), b); + c.typeRegistry = [...((_a = a === null || a === void 0 ? void 0 : a.typeRegistry) !== null && _a !== void 0 ? _a : []), ...((_b = b === null || b === void 0 ? void 0 : b.typeRegistry) !== null && _b !== void 0 ? _b : [])]; + return c; +} +exports.mergeJsonOptions = mergeJsonOptions; - if (!client.issuer || !client.issuer.issuer) { - throw new TypeError('client must have an issuer with an identifier'); - } - this._client = client; - this._issuer = client.issuer; - this._verify = verify; - this._passReqToCallback = passReqToCallback; - this._usePKCE = usePKCE; - this._key = sessionKey || `oidc:${url.parse(this._issuer.issuer).hostname}`; - this._params = cloneDeep(params); - this._extras = cloneDeep(extras); +/***/ }), - if (!this._params.response_type) this._params.response_type = resolveResponseType.call(client); - if (!this._params.redirect_uri) this._params.redirect_uri = resolveRedirectUri.call(client); - if (!this._params.scope) this._params.scope = 'openid'; +/***/ 70661: +/***/ ((__unused_webpack_module, exports) => { - if (this._usePKCE === true) { - const supportedMethods = Array.isArray(this._issuer.code_challenge_methods_supported) - ? this._issuer.code_challenge_methods_supported : false; +"use strict"; - if (supportedMethods && supportedMethods.includes('S256')) { - this._usePKCE = 'S256'; - } else if (supportedMethods && supportedMethods.includes('plain')) { - this._usePKCE = 'plain'; - } else if (supportedMethods) { - throw new TypeError('neither code_challenge_method supported by the client is supported by the issuer'); - } else { - this._usePKCE = 'S256'; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isJsonObject = exports.typeofJsonValue = void 0; +/** + * Get the type of a JSON value. + * Distinguishes between array, null and object. + */ +function typeofJsonValue(value) { + let t = typeof value; + if (t == "object") { + if (Array.isArray(value)) + return "array"; + if (value === null) + return "null"; } - } else if (typeof this._usePKCE === 'string' && !['plain', 'S256'].includes(this._usePKCE)) { - throw new TypeError(`${this._usePKCE} is not valid/implemented PKCE code_challenge_method`); - } - - this.name = url.parse(client.issuer.issuer).hostname; + return t; } +exports.typeofJsonValue = typeofJsonValue; +/** + * Is this a JSON object (instead of an array or null)? + */ +function isJsonObject(value) { + return value !== null && typeof value == "object" && !Array.isArray(value); +} +exports.isJsonObject = isJsonObject; -OpenIDConnectStrategy.prototype.authenticate = function authenticate(req, options) { - (async () => { - const client = this._client; - if (!req.session) { - throw new TypeError('authentication requires session support'); - } - const reqParams = client.callbackParams(req); - const sessionKey = this._key; - - /* start authentication request */ - if (Object.keys(reqParams).length === 0) { - // provide options object with extra authentication parameters - const params = { - state: random(), - ...this._params, - ...options, - }; - if (!params.nonce && params.response_type.includes('id_token')) { - params.nonce = random(); - } +/***/ }), - req.session[sessionKey] = pick(params, 'nonce', 'state', 'max_age', 'response_type'); +/***/ 34772: +/***/ ((__unused_webpack_module, exports) => { - if (this._usePKCE && params.response_type.includes('code')) { - const verifier = random(); - req.session[sessionKey].code_verifier = verifier; +"use strict"; - switch (this._usePKCE) { // eslint-disable-line default-case - case 'S256': - params.code_challenge = codeChallenge(verifier); - params.code_challenge_method = 'S256'; - break; - case 'plain': - params.code_challenge = verifier; - break; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.lowerCamelCase = void 0; +/** + * Converts snake_case to lowerCamelCase. + * + * Should behave like protoc: + * https://github.com/protocolbuffers/protobuf/blob/e8ae137c96444ea313485ed1118c5e43b2099cf1/src/google/protobuf/compiler/java/java_helpers.cc#L118 + */ +function lowerCamelCase(snakeCase) { + let capNext = false; + const sb = []; + for (let i = 0; i < snakeCase.length; i++) { + let next = snakeCase.charAt(i); + if (next == '_') { + capNext = true; + } + else if (/\d/.test(next)) { + sb.push(next); + capNext = true; + } + else if (capNext) { + sb.push(next.toUpperCase()); + capNext = false; + } + else if (i == 0) { + sb.push(next.toLowerCase()); + } + else { + sb.push(next); } - } - - this.redirect(client.authorizationUrl(params)); - return; } - /* end authentication request */ + return sb.join(''); +} +exports.lowerCamelCase = lowerCamelCase; - /* start authentication response */ - const session = req.session[sessionKey]; - if (Object.keys(session || {}).length === 0) { - throw new Error(format('did not find expected authorization request details in session, req.session["%s"] is %j', sessionKey, session)); - } +/***/ }), - const { - state, nonce, max_age: maxAge, code_verifier: codeVerifier, response_type: responseType, - } = session; +/***/ 1682: +/***/ ((__unused_webpack_module, exports) => { - try { - delete req.session[sessionKey]; - } catch (err) {} +"use strict"; - const opts = { - redirect_uri: this._params.redirect_uri, - ...options, - }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MESSAGE_TYPE = void 0; +/** + * The symbol used as a key on message objects to store the message type. + * + * Note that this is an experimental feature - it is here to stay, but + * implementation details may change without notice. + */ +exports.MESSAGE_TYPE = Symbol.for("protobuf-ts/message-type"); - const checks = { - state, - nonce, - max_age: maxAge, - code_verifier: codeVerifier, - response_type: responseType, - }; - const tokenset = await client.callback(opts.redirect_uri, reqParams, checks, this._extras); +/***/ }), - const passReq = this._passReqToCallback; - const loadUserinfo = this._verify.length > (passReq ? 3 : 2) && client.issuer.userinfo_endpoint; +/***/ 63664: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const args = [tokenset, verified.bind(this)]; +"use strict"; - if (loadUserinfo) { - if (!tokenset.access_token) { - throw new RPError({ - message: 'expected access_token to be returned when asking for userinfo in verify callback', - tokenset, - }); - } - const userinfo = await client.userinfo(tokenset); - args.splice(1, 0, userinfo); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MessageType = void 0; +const message_type_contract_1 = __nccwpck_require__(1682); +const reflection_info_1 = __nccwpck_require__(21370); +const reflection_type_check_1 = __nccwpck_require__(20903); +const reflection_json_reader_1 = __nccwpck_require__(229); +const reflection_json_writer_1 = __nccwpck_require__(68980); +const reflection_binary_reader_1 = __nccwpck_require__(91593); +const reflection_binary_writer_1 = __nccwpck_require__(57170); +const reflection_create_1 = __nccwpck_require__(60390); +const reflection_merge_partial_1 = __nccwpck_require__(7869); +const json_typings_1 = __nccwpck_require__(70661); +const json_format_contract_1 = __nccwpck_require__(48139); +const reflection_equals_1 = __nccwpck_require__(39473); +const binary_writer_1 = __nccwpck_require__(44354); +const binary_reader_1 = __nccwpck_require__(65210); +const baseDescriptors = Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})); +/** + * This standard message type provides reflection-based + * operations to work with a message. + */ +class MessageType { + constructor(name, fields, options) { + this.defaultCheckDepth = 16; + this.typeName = name; + this.fields = fields.map(reflection_info_1.normalizeFieldInfo); + this.options = options !== null && options !== void 0 ? options : {}; + this.messagePrototype = Object.create(null, Object.assign(Object.assign({}, baseDescriptors), { [message_type_contract_1.MESSAGE_TYPE]: { value: this } })); + this.refTypeCheck = new reflection_type_check_1.ReflectionTypeCheck(this); + this.refJsonReader = new reflection_json_reader_1.ReflectionJsonReader(this); + this.refJsonWriter = new reflection_json_writer_1.ReflectionJsonWriter(this); + this.refBinReader = new reflection_binary_reader_1.ReflectionBinaryReader(this); + this.refBinWriter = new reflection_binary_writer_1.ReflectionBinaryWriter(this); } - - if (passReq) { - args.unshift(req); + create(value) { + let message = reflection_create_1.reflectionCreate(this); + if (value !== undefined) { + reflection_merge_partial_1.reflectionMergePartial(this, message, value); + } + return message; } - - this._verify(...args); - /* end authentication response */ - })().catch((error) => { - if ( - (error instanceof OPError && error.error !== 'server_error' && !error.error.startsWith('invalid')) - || error instanceof RPError - ) { - this.fail(error); - } else { - this.error(error); + /** + * Clone the message. + * + * Unknown fields are discarded. + */ + clone(message) { + let copy = this.create(); + reflection_merge_partial_1.reflectionMergePartial(this, copy, message); + return copy; } - }); -}; - -module.exports = OpenIDConnectStrategy; + /** + * Determines whether two message of the same type have the same field values. + * Checks for deep equality, traversing repeated fields, oneof groups, maps + * and messages recursively. + * Will also return true if both messages are `undefined`. + */ + equals(a, b) { + return reflection_equals_1.reflectionEquals(this, a, b); + } + /** + * Is the given value assignable to our message type + * and contains no [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? + */ + is(arg, depth = this.defaultCheckDepth) { + return this.refTypeCheck.is(arg, depth, false); + } + /** + * Is the given value assignable to our message type, + * regardless of [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? + */ + isAssignable(arg, depth = this.defaultCheckDepth) { + return this.refTypeCheck.is(arg, depth, true); + } + /** + * Copy partial data into the target message. + */ + mergePartial(target, source) { + reflection_merge_partial_1.reflectionMergePartial(this, target, source); + } + /** + * Create a new message from binary format. + */ + fromBinary(data, options) { + let opt = binary_reader_1.binaryReadOptions(options); + return this.internalBinaryRead(opt.readerFactory(data), data.byteLength, opt); + } + /** + * Read a new message from a JSON value. + */ + fromJson(json, options) { + return this.internalJsonRead(json, json_format_contract_1.jsonReadOptions(options)); + } + /** + * Read a new message from a JSON string. + * This is equivalent to `T.fromJson(JSON.parse(json))`. + */ + fromJsonString(json, options) { + let value = JSON.parse(json); + return this.fromJson(value, options); + } + /** + * Write the message to canonical JSON value. + */ + toJson(message, options) { + return this.internalJsonWrite(message, json_format_contract_1.jsonWriteOptions(options)); + } + /** + * Convert the message to canonical JSON string. + * This is equivalent to `JSON.stringify(T.toJson(t))` + */ + toJsonString(message, options) { + var _a; + let value = this.toJson(message, options); + return JSON.stringify(value, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0); + } + /** + * Write the message to binary format. + */ + toBinary(message, options) { + let opt = binary_writer_1.binaryWriteOptions(options); + return this.internalBinaryWrite(message, opt.writerFactory(), opt).finish(); + } + /** + * This is an internal method. If you just want to read a message from + * JSON, use `fromJson()` or `fromJsonString()`. + * + * Reads JSON value and merges the fields into the target + * according to protobuf rules. If the target is omitted, + * a new instance is created first. + */ + internalJsonRead(json, options, target) { + if (json !== null && typeof json == "object" && !Array.isArray(json)) { + let message = target !== null && target !== void 0 ? target : this.create(); + this.refJsonReader.read(json, message, options); + return message; + } + throw new Error(`Unable to parse message ${this.typeName} from JSON ${json_typings_1.typeofJsonValue(json)}.`); + } + /** + * This is an internal method. If you just want to write a message + * to JSON, use `toJson()` or `toJsonString(). + * + * Writes JSON value and returns it. + */ + internalJsonWrite(message, options) { + return this.refJsonWriter.write(message, options); + } + /** + * This is an internal method. If you just want to write a message + * in binary format, use `toBinary()`. + * + * Serializes the message in binary format and appends it to the given + * writer. Returns passed writer. + */ + internalBinaryWrite(message, writer, options) { + this.refBinWriter.write(message, writer, options); + return writer; + } + /** + * This is an internal method. If you just want to read a message from + * binary data, use `fromBinary()`. + * + * Reads data from binary format and merges the fields into + * the target according to protobuf rules. If the target is + * omitted, a new instance is created first. + */ + internalBinaryRead(reader, length, options, target) { + let message = target !== null && target !== void 0 ? target : this.create(); + this.refBinReader.read(reader, message, options, length); + return message; + } +} +exports.MessageType = MessageType; /***/ }), -/***/ 14974: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const base64url = __nccwpck_require__(23570); -const now = __nccwpck_require__(24393); - -class TokenSet { - /** - * @name constructor - * @api public - */ - constructor(values) { - Object.assign(this, values); - } - - /** - * @name expires_in= - * @api public - */ - set expires_in(value) { // eslint-disable-line camelcase - this.expires_at = now() + Number(value); - } +/***/ 78531: +/***/ ((__unused_webpack_module, exports) => { - /** - * @name expires_in - * @api public - */ - get expires_in() { // eslint-disable-line camelcase - return Math.max.apply(null, [this.expires_at - now(), 0]); - } +"use strict"; - /** - * @name expired - * @api public - */ - expired() { - return this.expires_in === 0; - } - - /** - * @name claims - * @api public - */ - claims() { - if (!this.id_token) { - throw new TypeError('id_token not present in TokenSet'); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getSelectedOneofValue = exports.clearOneofValue = exports.setUnknownOneofValue = exports.setOneofValue = exports.getOneofValue = exports.isOneofGroup = void 0; +/** + * Is the given value a valid oneof group? + * + * We represent protobuf `oneof` as algebraic data types (ADT) in generated + * code. But when working with messages of unknown type, the ADT does not + * help us. + * + * This type guard checks if the given object adheres to the ADT rules, which + * are as follows: + * + * 1) Must be an object. + * + * 2) Must have a "oneofKind" discriminator property. + * + * 3) If "oneofKind" is `undefined`, no member field is selected. The object + * must not have any other properties. + * + * 4) If "oneofKind" is a `string`, the member field with this name is + * selected. + * + * 5) If a member field is selected, the object must have a second property + * with this name. The property must not be `undefined`. + * + * 6) No extra properties are allowed. The object has either one property + * (no selection) or two properties (selection). + * + */ +function isOneofGroup(any) { + if (typeof any != 'object' || any === null || !any.hasOwnProperty('oneofKind')) { + return false; + } + switch (typeof any.oneofKind) { + case "string": + if (any[any.oneofKind] === undefined) + return false; + return Object.keys(any).length == 2; + case "undefined": + return Object.keys(any).length == 1; + default: + return false; } - - return JSON.parse(base64url.decode(this.id_token.split('.')[1])); - } } - -module.exports = TokenSet; +exports.isOneofGroup = isOneofGroup; +/** + * Returns the value of the given field in a oneof group. + */ +function getOneofValue(oneof, kind) { + return oneof[kind]; +} +exports.getOneofValue = getOneofValue; +function setOneofValue(oneof, kind, value) { + if (oneof.oneofKind !== undefined) { + delete oneof[oneof.oneofKind]; + } + oneof.oneofKind = kind; + if (value !== undefined) { + oneof[kind] = value; + } +} +exports.setOneofValue = setOneofValue; +function setUnknownOneofValue(oneof, kind, value) { + if (oneof.oneofKind !== undefined) { + delete oneof[oneof.oneofKind]; + } + oneof.oneofKind = kind; + if (value !== undefined && kind !== undefined) { + oneof[kind] = value; + } +} +exports.setUnknownOneofValue = setUnknownOneofValue; +/** + * Removes the selected field in a oneof group. + * + * Note that the recommended way to modify a oneof group is to set + * a new object: + * + * ```ts + * message.result = { oneofKind: undefined }; + * ``` + */ +function clearOneofValue(oneof) { + if (oneof.oneofKind !== undefined) { + delete oneof[oneof.oneofKind]; + } + oneof.oneofKind = undefined; +} +exports.clearOneofValue = clearOneofValue; +/** + * Returns the selected value of the given oneof group. + * + * Not that the recommended way to access a oneof group is to check + * the "oneofKind" property and let TypeScript narrow down the union + * type for you: + * + * ```ts + * if (message.result.oneofKind === "error") { + * message.result.error; // string + * } + * ``` + * + * In the rare case you just need the value, and do not care about + * which protobuf field is selected, you can use this function + * for convenience. + */ +function getSelectedOneofValue(oneof) { + if (oneof.oneofKind === undefined) { + return undefined; + } + return oneof[oneof.oneofKind]; +} +exports.getSelectedOneofValue = getSelectedOneofValue; /***/ }), -/***/ 67551: -/***/ ((module) => { - -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. +/***/ 47777: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ +"use strict"; -/* global global, define, System, Reflect, Promise */ -var __extends; -var __assign; -var __rest; -var __decorate; -var __param; -var __metadata; -var __awaiter; -var __generator; -var __exportStar; -var __values; -var __read; -var __spread; -var __spreadArrays; -var __await; -var __asyncGenerator; -var __asyncDelegator; -var __asyncValues; -var __makeTemplateObject; -var __importStar; -var __importDefault; -var __classPrivateFieldGet; -var __classPrivateFieldSet; -var __createBinding; -(function (factory) { - var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; - if (typeof define === "function" && define.amd) { - define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PbLong = exports.PbULong = exports.detectBi = void 0; +const goog_varint_1 = __nccwpck_require__(30433); +let BI; +function detectBi() { + const dv = new DataView(new ArrayBuffer(8)); + const ok = globalThis.BigInt !== undefined + && typeof dv.getBigInt64 === "function" + && typeof dv.getBigUint64 === "function" + && typeof dv.setBigInt64 === "function" + && typeof dv.setBigUint64 === "function"; + BI = ok ? { + MIN: BigInt("-9223372036854775808"), + MAX: BigInt("9223372036854775807"), + UMIN: BigInt("0"), + UMAX: BigInt("18446744073709551615"), + C: BigInt, + V: dv, + } : undefined; +} +exports.detectBi = detectBi; +detectBi(); +function assertBi(bi) { + if (!bi) + throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support"); +} +// used to validate from(string) input (when bigint is unavailable) +const RE_DECIMAL_STR = /^-?[0-9]+$/; +// constants for binary math +const TWO_PWR_32_DBL = 0x100000000; +const HALF_2_PWR_32 = 0x080000000; +// base class for PbLong and PbULong provides shared code +class SharedPbLong { + /** + * Create a new instance with the given bits. + */ + constructor(lo, hi) { + this.lo = lo | 0; + this.hi = hi | 0; } - else if ( true && typeof module.exports === "object") { - factory(createExporter(root, createExporter(module.exports))); + /** + * Is this instance equal to 0? + */ + isZero() { + return this.lo == 0 && this.hi == 0; } - else { - factory(createExporter(root)); + /** + * Convert to a native number. + */ + toNumber() { + let result = this.hi * TWO_PWR_32_DBL + (this.lo >>> 0); + if (!Number.isSafeInteger(result)) + throw new Error("cannot convert to safe number"); + return result; } - function createExporter(exports, previous) { - if (exports !== root) { - if (typeof Object.create === "function") { - Object.defineProperty(exports, "__esModule", { value: true }); +} +/** + * 64-bit unsigned integer as two 32-bit values. + * Converts between `string`, `number` and `bigint` representations. + */ +class PbULong extends SharedPbLong { + /** + * Create instance from a `string`, `number` or `bigint`. + */ + static from(value) { + if (BI) + // noinspection FallThroughInSwitchStatementJS + switch (typeof value) { + case "string": + if (value == "0") + return this.ZERO; + if (value == "") + throw new Error('string is no integer'); + value = BI.C(value); + case "number": + if (value === 0) + return this.ZERO; + value = BI.C(value); + case "bigint": + if (!value) + return this.ZERO; + if (value < BI.UMIN) + throw new Error('signed value for ulong'); + if (value > BI.UMAX) + throw new Error('ulong too large'); + BI.V.setBigUint64(0, value, true); + return new PbULong(BI.V.getInt32(0, true), BI.V.getInt32(4, true)); } - else { - exports.__esModule = true; + else + switch (typeof value) { + case "string": + if (value == "0") + return this.ZERO; + value = value.trim(); + if (!RE_DECIMAL_STR.test(value)) + throw new Error('string is no integer'); + let [minus, lo, hi] = goog_varint_1.int64fromString(value); + if (minus) + throw new Error('signed value for ulong'); + return new PbULong(lo, hi); + case "number": + if (value == 0) + return this.ZERO; + if (!Number.isSafeInteger(value)) + throw new Error('number is no integer'); + if (value < 0) + throw new Error('signed value for ulong'); + return new PbULong(value, value / TWO_PWR_32_DBL); } - } - return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; + throw new Error('unknown value ' + typeof value); } -}) -(function (exporter) { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - - __extends = function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - - __assign = Object.assign || function (t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - - __rest = function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - }; - - __decorate = function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - - __param = function (paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } - }; - - __metadata = function (metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); - }; - - __awaiter = function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - - __generator = function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - - __createBinding = function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; - }; - - __exportStar = function (m, exports) { - for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) exports[p] = m[p]; - }; - - __values = function (o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; + /** + * Convert to decimal string. + */ + toString() { + return BI ? this.toBigInt().toString() : goog_varint_1.int64toString(this.lo, this.hi); + } + /** + * Convert to native bigint. + */ + toBigInt() { + assertBi(BI); + BI.V.setInt32(0, this.lo, true); + BI.V.setInt32(4, this.hi, true); + return BI.V.getBigUint64(0, true); + } +} +exports.PbULong = PbULong; +/** + * ulong 0 singleton. + */ +PbULong.ZERO = new PbULong(0, 0); +/** + * 64-bit signed integer as two 32-bit values. + * Converts between `string`, `number` and `bigint` representations. + */ +class PbLong extends SharedPbLong { + /** + * Create instance from a `string`, `number` or `bigint`. + */ + static from(value) { + if (BI) + // noinspection FallThroughInSwitchStatementJS + switch (typeof value) { + case "string": + if (value == "0") + return this.ZERO; + if (value == "") + throw new Error('string is no integer'); + value = BI.C(value); + case "number": + if (value === 0) + return this.ZERO; + value = BI.C(value); + case "bigint": + if (!value) + return this.ZERO; + if (value < BI.MIN) + throw new Error('signed long too small'); + if (value > BI.MAX) + throw new Error('signed long too large'); + BI.V.setBigInt64(0, value, true); + return new PbLong(BI.V.getInt32(0, true), BI.V.getInt32(4, true)); } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - - __read = function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); + else + switch (typeof value) { + case "string": + if (value == "0") + return this.ZERO; + value = value.trim(); + if (!RE_DECIMAL_STR.test(value)) + throw new Error('string is no integer'); + let [minus, lo, hi] = goog_varint_1.int64fromString(value); + if (minus) { + if (hi > HALF_2_PWR_32 || (hi == HALF_2_PWR_32 && lo != 0)) + throw new Error('signed long too small'); + } + else if (hi >= HALF_2_PWR_32) + throw new Error('signed long too large'); + let pbl = new PbLong(lo, hi); + return minus ? pbl.negate() : pbl; + case "number": + if (value == 0) + return this.ZERO; + if (!Number.isSafeInteger(value)) + throw new Error('number is no integer'); + return value > 0 + ? new PbLong(value, value / TWO_PWR_32_DBL) + : new PbLong(-value, -value / TWO_PWR_32_DBL).negate(); } - finally { if (e) throw e.error; } + throw new Error('unknown value ' + typeof value); + } + /** + * Do we have a minus sign? + */ + isNegative() { + return (this.hi & HALF_2_PWR_32) !== 0; + } + /** + * Negate two's complement. + * Invert all the bits and add one to the result. + */ + negate() { + let hi = ~this.hi, lo = this.lo; + if (lo) + lo = ~lo + 1; + else + hi += 1; + return new PbLong(lo, hi); + } + /** + * Convert to decimal string. + */ + toString() { + if (BI) + return this.toBigInt().toString(); + if (this.isNegative()) { + let n = this.negate(); + return '-' + goog_varint_1.int64toString(n.lo, n.hi); } - return ar; - }; - - __spread = function () { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; - }; - - __spreadArrays = function () { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; - }; - - __await = function (v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); - }; - - __asyncGenerator = function (thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } - }; - - __asyncDelegator = function (o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } - }; + return goog_varint_1.int64toString(this.lo, this.hi); + } + /** + * Convert to native bigint. + */ + toBigInt() { + assertBi(BI); + BI.V.setInt32(0, this.lo, true); + BI.V.setInt32(4, this.hi, true); + return BI.V.getBigInt64(0, true); + } +} +exports.PbLong = PbLong; +/** + * long 0 singleton. + */ +PbLong.ZERO = new PbLong(0, 0); - __asyncValues = function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } - }; - __makeTemplateObject = function (cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; - }; +/***/ }), - __importStar = function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; - }; +/***/ 95290: +/***/ ((__unused_webpack_module, exports) => { - __importDefault = function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; +"use strict"; - __classPrivateFieldGet = function (receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); +// Copyright (c) 2016, Daniel Wirtz All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of its author, nor the names of its contributors +// may be used to endorse or promote products derived from this software +// without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.utf8read = void 0; +const fromCharCodes = (chunk) => String.fromCharCode.apply(String, chunk); +/** + * @deprecated This function will no longer be exported with the next major + * release, since protobuf-ts has switch to TextDecoder API. If you need this + * function, please migrate to @protobufjs/utf8. For context, see + * https://github.com/timostamm/protobuf-ts/issues/184 + * + * Reads UTF8 bytes as a string. + * + * See [protobufjs / utf8](https://github.com/protobufjs/protobuf.js/blob/9893e35b854621cce64af4bf6be2cff4fb892796/lib/utf8/index.js#L40) + * + * Copyright (c) 2016, Daniel Wirtz + */ +function utf8read(bytes) { + if (bytes.length < 1) + return ""; + let pos = 0, // position in bytes + parts = [], chunk = [], i = 0, // char offset + t; // temporary + let len = bytes.length; + while (pos < len) { + t = bytes[pos++]; + if (t < 128) + chunk[i++] = t; + else if (t > 191 && t < 224) + chunk[i++] = (t & 31) << 6 | bytes[pos++] & 63; + else if (t > 239 && t < 365) { + t = ((t & 7) << 18 | (bytes[pos++] & 63) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63) - 0x10000; + chunk[i++] = 0xD800 + (t >> 10); + chunk[i++] = 0xDC00 + (t & 1023); } - return privateMap.get(receiver); - }; - - __classPrivateFieldSet = function (receiver, privateMap, value) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); + else + chunk[i++] = (t & 15) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63; + if (i > 8191) { + parts.push(fromCharCodes(chunk)); + i = 0; } - privateMap.set(receiver, value); - return value; - }; - - exporter("__extends", __extends); - exporter("__assign", __assign); - exporter("__rest", __rest); - exporter("__decorate", __decorate); - exporter("__param", __param); - exporter("__metadata", __metadata); - exporter("__awaiter", __awaiter); - exporter("__generator", __generator); - exporter("__exportStar", __exportStar); - exporter("__createBinding", __createBinding); - exporter("__values", __values); - exporter("__read", __read); - exporter("__spread", __spread); - exporter("__spreadArrays", __spreadArrays); - exporter("__await", __await); - exporter("__asyncGenerator", __asyncGenerator); - exporter("__asyncDelegator", __asyncDelegator); - exporter("__asyncValues", __asyncValues); - exporter("__makeTemplateObject", __makeTemplateObject); - exporter("__importStar", __importStar); - exporter("__importDefault", __importDefault); - exporter("__classPrivateFieldGet", __classPrivateFieldGet); - exporter("__classPrivateFieldSet", __classPrivateFieldSet); -}); + } + if (parts.length) { + if (i) + parts.push(fromCharCodes(chunk.slice(0, i))); + return parts.join(""); + } + return fromCharCodes(chunk.slice(0, i)); +} +exports.utf8read = utf8read; /***/ }), -/***/ 40334: -/***/ ((module) => { +/***/ 91593: +/***/ ((__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, { - 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); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ReflectionBinaryReader = void 0; +const binary_format_contract_1 = __nccwpck_require__(84921); +const reflection_info_1 = __nccwpck_require__(21370); +const reflection_long_convert_1 = __nccwpck_require__(24612); +const reflection_scalar_default_1 = __nccwpck_require__(74863); +/** + * Reads proto3 messages in binary format using reflection information. + * + * https://developers.google.com/protocol-buffers/docs/encoding + */ +class ReflectionBinaryReader { + constructor(info) { + this.info = info; + } + prepare() { + var _a; + if (!this.fieldNoToField) { + const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; + this.fieldNoToField = new Map(fieldsInput.map(field => [field.no, field])); + } + } + /** + * Reads a message from binary format into the target message. + * + * Repeated fields are appended. Map entries are added, overwriting + * existing keys. + * + * If a message field is already present, it will be merged with the + * new data. + */ + read(reader, message, options, length) { + this.prepare(); + const end = length === undefined ? reader.len : reader.pos + length; + while (reader.pos < end) { + // read the tag and find the field + const [fieldNo, wireType] = reader.tag(), field = this.fieldNoToField.get(fieldNo); + if (!field) { + let u = options.readUnknownField; + if (u == "throw") + throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.info.typeName}`); + let d = reader.skip(wireType); + if (u !== false) + (u === true ? binary_format_contract_1.UnknownFieldHandler.onRead : u)(this.info.typeName, message, fieldNo, wireType, d); + continue; + } + // target object for the field we are reading + let target = message, repeated = field.repeat, localName = field.localName; + // if field is member of oneof ADT, use ADT as target + if (field.oneof) { + target = target[field.oneof]; + // if other oneof member selected, set new ADT + if (target.oneofKind !== localName) + target = message[field.oneof] = { + oneofKind: localName + }; + } + // we have handled oneof above, we just have read the value into `target[localName]` + switch (field.kind) { + case "scalar": + case "enum": + let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; + let L = field.kind == "scalar" ? field.L : undefined; + if (repeated) { + let arr = target[localName]; // safe to assume presence of array, oneof cannot contain repeated values + if (wireType == binary_format_contract_1.WireType.LengthDelimited && T != reflection_info_1.ScalarType.STRING && T != reflection_info_1.ScalarType.BYTES) { + let e = reader.uint32() + reader.pos; + while (reader.pos < e) + arr.push(this.scalar(reader, T, L)); + } + else + arr.push(this.scalar(reader, T, L)); + } + else + target[localName] = this.scalar(reader, T, L); + break; + case "message": + if (repeated) { + let arr = target[localName]; // safe to assume presence of array, oneof cannot contain repeated values + let msg = field.T().internalBinaryRead(reader, reader.uint32(), options); + arr.push(msg); + } + else + target[localName] = field.T().internalBinaryRead(reader, reader.uint32(), options, target[localName]); + break; + case "map": + let [mapKey, mapVal] = this.mapEntry(field, reader, options); + // safe to assume presence of map object, oneof cannot contain repeated values + target[localName][mapKey] = mapVal; + break; + } + } + } + /** + * Read a map field, expecting key field = 1, value field = 2 + */ + mapEntry(field, reader, options) { + let length = reader.uint32(); + let end = reader.pos + length; + let key = undefined; // javascript only allows number or string for object properties + let val = undefined; + while (reader.pos < end) { + let [fieldNo, wireType] = reader.tag(); + switch (fieldNo) { + case 1: + if (field.K == reflection_info_1.ScalarType.BOOL) + key = reader.bool().toString(); + else + // long types are read as string, number types are okay as number + key = this.scalar(reader, field.K, reflection_info_1.LongType.STRING); + break; + case 2: + switch (field.V.kind) { + case "scalar": + val = this.scalar(reader, field.V.T, field.V.L); + break; + case "enum": + val = reader.int32(); + break; + case "message": + val = field.V.T().internalBinaryRead(reader, reader.uint32(), options); + break; + } + break; + default: + throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) in map entry for ${this.info.typeName}#${field.name}`); + } + } + if (key === undefined) { + let keyRaw = reflection_scalar_default_1.reflectionScalarDefault(field.K); + key = field.K == reflection_info_1.ScalarType.BOOL ? keyRaw.toString() : keyRaw; + } + if (val === undefined) + switch (field.V.kind) { + case "scalar": + val = reflection_scalar_default_1.reflectionScalarDefault(field.V.T, field.V.L); + break; + case "enum": + val = 0; + break; + case "message": + val = field.V.T().create(); + break; + } + return [key, val]; + } + scalar(reader, type, longType) { + switch (type) { + case reflection_info_1.ScalarType.INT32: + return reader.int32(); + case reflection_info_1.ScalarType.STRING: + return reader.string(); + case reflection_info_1.ScalarType.BOOL: + return reader.bool(); + case reflection_info_1.ScalarType.DOUBLE: + return reader.double(); + case reflection_info_1.ScalarType.FLOAT: + return reader.float(); + case reflection_info_1.ScalarType.INT64: + return reflection_long_convert_1.reflectionLongConvert(reader.int64(), longType); + case reflection_info_1.ScalarType.UINT64: + return reflection_long_convert_1.reflectionLongConvert(reader.uint64(), longType); + case reflection_info_1.ScalarType.FIXED64: + return reflection_long_convert_1.reflectionLongConvert(reader.fixed64(), longType); + case reflection_info_1.ScalarType.FIXED32: + return reader.fixed32(); + case reflection_info_1.ScalarType.BYTES: + return reader.bytes(); + case reflection_info_1.ScalarType.UINT32: + return reader.uint32(); + case reflection_info_1.ScalarType.SFIXED32: + return reader.sfixed32(); + case reflection_info_1.ScalarType.SFIXED64: + return reflection_long_convert_1.reflectionLongConvert(reader.sfixed64(), longType); + case reflection_info_1.ScalarType.SINT32: + return reader.sint32(); + case reflection_info_1.ScalarType.SINT64: + return reflection_long_convert_1.reflectionLongConvert(reader.sint64(), longType); + } + } } - -// 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); +exports.ReflectionBinaryReader = ReflectionBinaryReader; /***/ }), -/***/ 76762: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 57170: +/***/ ((__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, { - Octokit: () => Octokit -}); -module.exports = __toCommonJS(dist_src_exports); -var import_universal_user_agent = __nccwpck_require__(45030); -var import_before_after_hook = __nccwpck_require__(83682); -var import_request = __nccwpck_require__(36234); -var import_graphql = __nccwpck_require__(88467); -var import_auth_token = __nccwpck_require__(40334); - -// 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; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ReflectionBinaryWriter = void 0; +const binary_format_contract_1 = __nccwpck_require__(84921); +const reflection_info_1 = __nccwpck_require__(21370); +const assert_1 = __nccwpck_require__(54253); +const pb_long_1 = __nccwpck_require__(47777); +/** + * Writes proto3 messages in binary format using reflection information. + * + * https://developers.google.com/protocol-buffers/docs/encoding + */ +class ReflectionBinaryWriter { + constructor(info) { + this.info = info; } - if (options.previews) { - requestDefaults.mediaType.previews = options.previews; + prepare() { + if (!this.fields) { + const fieldsInput = this.info.fields ? this.info.fields.concat() : []; + this.fields = fieldsInput.sort((a, b) => a.no - b.no); + } } - if (options.timeZone) { - requestDefaults.headers["time-zone"] = options.timeZone; + /** + * Writes the message to binary format. + */ + write(message, writer, options) { + this.prepare(); + for (const field of this.fields) { + let value, // this will be our field value, whether it is member of a oneof or not + emitDefault, // whether we emit the default value (only true for oneof members) + repeated = field.repeat, localName = field.localName; + // handle oneof ADT + if (field.oneof) { + const group = message[field.oneof]; + if (group.oneofKind !== localName) + continue; // if field is not selected, skip + value = group[localName]; + emitDefault = true; + } + else { + value = message[localName]; + emitDefault = false; + } + // we have handled oneof above. we just have to honor `emitDefault`. + switch (field.kind) { + case "scalar": + case "enum": + let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; + if (repeated) { + assert_1.assert(Array.isArray(value)); + if (repeated == reflection_info_1.RepeatType.PACKED) + this.packed(writer, T, field.no, value); + else + for (const item of value) + this.scalar(writer, T, field.no, item, true); + } + else if (value === undefined) + assert_1.assert(field.opt); + else + this.scalar(writer, T, field.no, value, emitDefault || field.opt); + break; + case "message": + if (repeated) { + assert_1.assert(Array.isArray(value)); + for (const item of value) + this.message(writer, options, field.T(), field.no, item); + } + else { + this.message(writer, options, field.T(), field.no, value); + } + break; + case "map": + assert_1.assert(typeof value == 'object' && value !== null); + for (const [key, val] of Object.entries(value)) + this.mapEntry(writer, options, field, key, val); + break; + } + } + let u = options.writeUnknownFields; + if (u !== false) + (u === true ? binary_format_contract_1.UnknownFieldHandler.onWrite : u)(this.info.typeName, message, writer); } - 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; + mapEntry(writer, options, field, key, value) { + writer.tag(field.no, binary_format_contract_1.WireType.LengthDelimited); + writer.fork(); + // javascript only allows number or string for object properties + // we convert from our representation to the protobuf type + let keyValue = key; + switch (field.K) { + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.UINT32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + keyValue = Number.parseInt(key); + break; + case reflection_info_1.ScalarType.BOOL: + assert_1.assert(key == 'true' || key == 'false'); + keyValue = key == 'true'; + break; + } + // write key, expecting key field number = 1 + this.scalar(writer, field.K, 1, keyValue, true); + // write value, expecting value field number = 2 + switch (field.V.kind) { + case 'scalar': + this.scalar(writer, field.V.T, 2, value, true); + break; + case 'enum': + this.scalar(writer, reflection_info_1.ScalarType.INT32, 2, value, true); + break; + case 'message': + this.message(writer, options, field.V.T(), 2, value); + break; + } + writer.join(); } - const classConstructor = this.constructor; - for (let i = 0; i < classConstructor.plugins.length; ++i) { - Object.assign(this, classConstructor.plugins[i](this, options)); + message(writer, options, handler, fieldNo, value) { + if (value === undefined) + return; + handler.internalBinaryWrite(value, writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited).fork(), options); + writer.join(); } - } -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); + /** + * Write a single scalar value. + */ + scalar(writer, type, fieldNo, value, emitDefault) { + let [wireType, method, isDefault] = this.scalarInfo(type, value); + if (!isDefault || emitDefault) { + writer.tag(fieldNo, wireType); + writer[method](value); + } + } + /** + * Write an array of scalar values in packed format. + */ + packed(writer, type, fieldNo, value) { + if (!value.length) + return; + assert_1.assert(type !== reflection_info_1.ScalarType.BYTES && type !== reflection_info_1.ScalarType.STRING); + // write tag + writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited); + // begin length-delimited + writer.fork(); + // write values without tags + let [, method,] = this.scalarInfo(type); + for (let i = 0; i < value.length; i++) + writer[method](value[i]); + // end length delimited + writer.join(); + } + /** + * Get information for writing a scalar value. + * + * Returns tuple: + * [0]: appropriate WireType + * [1]: name of the appropriate method of IBinaryWriter + * [2]: whether the given value is a default value + * + * If argument `value` is omitted, [2] is always false. + */ + scalarInfo(type, value) { + let t = binary_format_contract_1.WireType.Varint; + let m; + let i = value === undefined; + let d = value === 0; + switch (type) { + case reflection_info_1.ScalarType.INT32: + m = "int32"; + break; + case reflection_info_1.ScalarType.STRING: + d = i || !value.length; + t = binary_format_contract_1.WireType.LengthDelimited; + m = "string"; + break; + case reflection_info_1.ScalarType.BOOL: + d = value === false; + m = "bool"; + break; + case reflection_info_1.ScalarType.UINT32: + m = "uint32"; + break; + case reflection_info_1.ScalarType.DOUBLE: + t = binary_format_contract_1.WireType.Bit64; + m = "double"; + break; + case reflection_info_1.ScalarType.FLOAT: + t = binary_format_contract_1.WireType.Bit32; + m = "float"; + break; + case reflection_info_1.ScalarType.INT64: + d = i || pb_long_1.PbLong.from(value).isZero(); + m = "int64"; + break; + case reflection_info_1.ScalarType.UINT64: + d = i || pb_long_1.PbULong.from(value).isZero(); + m = "uint64"; + break; + case reflection_info_1.ScalarType.FIXED64: + d = i || pb_long_1.PbULong.from(value).isZero(); + t = binary_format_contract_1.WireType.Bit64; + m = "fixed64"; + break; + case reflection_info_1.ScalarType.BYTES: + d = i || !value.byteLength; + t = binary_format_contract_1.WireType.LengthDelimited; + m = "bytes"; + break; + case reflection_info_1.ScalarType.FIXED32: + t = binary_format_contract_1.WireType.Bit32; + m = "fixed32"; + break; + case reflection_info_1.ScalarType.SFIXED32: + t = binary_format_contract_1.WireType.Bit32; + m = "sfixed32"; + break; + case reflection_info_1.ScalarType.SFIXED64: + d = i || pb_long_1.PbLong.from(value).isZero(); + t = binary_format_contract_1.WireType.Bit64; + m = "sfixed64"; + break; + case reflection_info_1.ScalarType.SINT32: + m = "sint32"; + break; + case reflection_info_1.ScalarType.SINT64: + d = i || pb_long_1.PbLong.from(value).isZero(); + m = "sint64"; + break; + } + return [t, m, i || d]; + } +} +exports.ReflectionBinaryWriter = ReflectionBinaryWriter; /***/ }), -/***/ 59440: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 67317: +/***/ ((__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, { - endpoint: () => endpoint -}); -module.exports = __toCommonJS(dist_src_exports); - -// pkg/dist-src/defaults.js -var import_universal_user_agent = __nccwpck_require__(45030); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.containsMessageType = void 0; +const message_type_contract_1 = __nccwpck_require__(1682); +/** + * Check if the provided object is a proto message. + * + * Note that this is an experimental feature - it is here to stay, but + * implementation details may change without notice. + */ +function containsMessageType(msg) { + return msg[message_type_contract_1.MESSAGE_TYPE] != null; +} +exports.containsMessageType = containsMessageType; -// 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; - }, {}); -} +/***/ 60390: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// 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); -} +"use strict"; -// 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] }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.reflectionCreate = void 0; +const reflection_scalar_default_1 = __nccwpck_require__(74863); +const message_type_contract_1 = __nccwpck_require__(1682); +/** + * Creates an instance of the generic message, using the field + * information. + */ +function reflectionCreate(type) { + /** + * This ternary can be removed in the next major version. + * The `Object.create()` code path utilizes a new `messagePrototype` + * property on the `IMessageType` which has this same `MESSAGE_TYPE` + * non-enumerable property on it. Doing it this way means that we only + * pay the cost of `Object.defineProperty()` once per `IMessageType` + * class of once per "instance". The falsy code path is only provided + * for backwards compatibility in cases where the runtime library is + * updated without also updating the generated code. + */ + const msg = type.messagePrototype + ? Object.create(type.messagePrototype) + : Object.defineProperty({}, message_type_contract_1.MESSAGE_TYPE, { value: type }); + for (let field of type.fields) { + let name = field.localName; + if (field.opt) + continue; + if (field.oneof) + msg[field.oneof] = { oneofKind: undefined }; + else if (field.repeat) + msg[name] = []; + else + switch (field.kind) { + case "scalar": + msg[name] = reflection_scalar_default_1.reflectionScalarDefault(field.T, field.L); + break; + case "enum": + // we require 0 to be default value for all enums + msg[name] = 0; + break; + case "map": + msg[name] = {}; + break; + } } - }); - return result; + return msg; } +exports.reflectionCreate = reflectionCreate; -// 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("&"); -} +/***/ 39473: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// 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), []); -} +"use strict"; -// 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]; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.reflectionEquals = void 0; +const reflection_info_1 = __nccwpck_require__(21370); +/** + * Determines whether two message of the same type have the same field values. + * Checks for deep equality, traversing repeated fields, oneof groups, maps + * and messages recursively. + * Will also return true if both messages are `undefined`. + */ +function reflectionEquals(info, a, b) { + if (a === b) + return true; + if (!a || !b) + return false; + for (let field of info.fields) { + let localName = field.localName; + let val_a = field.oneof ? a[field.oneof][localName] : a[localName]; + let val_b = field.oneof ? b[field.oneof][localName] : b[localName]; + switch (field.kind) { + case "enum": + case "scalar": + let t = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; + if (!(field.repeat + ? repeatedPrimitiveEq(t, val_a, val_b) + : primitiveEq(t, val_a, val_b))) + return false; + break; + case "map": + if (!(field.V.kind == "message" + ? repeatedMsgEq(field.V.T(), objectValues(val_a), objectValues(val_b)) + : repeatedPrimitiveEq(field.V.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.V.T, objectValues(val_a), objectValues(val_b)))) + return false; + break; + case "message": + let T = field.T(); + if (!(field.repeat + ? repeatedMsgEq(T, val_a, val_b) + : T.equals(val_a, val_b))) + return false; + break; + } } - } - return result; + return true; } - -// 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(""); +exports.reflectionEquals = reflectionEquals; +const objectValues = Object.values; +function primitiveEq(type, a, b) { + if (a === b) + return true; + if (type !== reflection_info_1.ScalarType.BYTES) + return false; + let ba = a; + let bb = b; + if (ba.length !== bb.length) + return false; + for (let i = 0; i < ba.length; i++) + if (ba[i] != bb[i]) + return false; + return true; } -function encodeUnreserved(str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { - return "%" + c.charCodeAt(0).toString(16).toUpperCase(); - }); +function repeatedPrimitiveEq(type, a, b) { + if (a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!primitiveEq(type, a[i], b[i])) + return false; + return true; } -function encodeValue(operator, value, key) { - value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); - if (key) { - return encodeUnreserved(key) + "=" + value; - } else { - return value; - } +function repeatedMsgEq(type, a, b) { + if (a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!type.equals(a[i], b[i])) + return false; + return true; } -function isDefined(value) { - return value !== void 0 && value !== null; + + +/***/ }), + +/***/ 21370: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.readMessageOption = exports.readFieldOption = exports.readFieldOptions = exports.normalizeFieldInfo = exports.RepeatType = exports.LongType = exports.ScalarType = void 0; +const lower_camel_case_1 = __nccwpck_require__(34772); +/** + * Scalar value types. This is a subset of field types declared by protobuf + * enum google.protobuf.FieldDescriptorProto.Type The types GROUP and MESSAGE + * are omitted, but the numerical values are identical. + */ +var ScalarType; +(function (ScalarType) { + // 0 is reserved for errors. + // Order is weird for historical reasons. + ScalarType[ScalarType["DOUBLE"] = 1] = "DOUBLE"; + ScalarType[ScalarType["FLOAT"] = 2] = "FLOAT"; + // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if + // negative values are likely. + ScalarType[ScalarType["INT64"] = 3] = "INT64"; + ScalarType[ScalarType["UINT64"] = 4] = "UINT64"; + // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if + // negative values are likely. + ScalarType[ScalarType["INT32"] = 5] = "INT32"; + ScalarType[ScalarType["FIXED64"] = 6] = "FIXED64"; + ScalarType[ScalarType["FIXED32"] = 7] = "FIXED32"; + ScalarType[ScalarType["BOOL"] = 8] = "BOOL"; + ScalarType[ScalarType["STRING"] = 9] = "STRING"; + // Tag-delimited aggregate. + // Group type is deprecated and not supported in proto3. However, Proto3 + // implementations should still be able to parse the group wire format and + // treat group fields as unknown fields. + // TYPE_GROUP = 10, + // TYPE_MESSAGE = 11, // Length-delimited aggregate. + // New in version 2. + ScalarType[ScalarType["BYTES"] = 12] = "BYTES"; + ScalarType[ScalarType["UINT32"] = 13] = "UINT32"; + // TYPE_ENUM = 14, + ScalarType[ScalarType["SFIXED32"] = 15] = "SFIXED32"; + ScalarType[ScalarType["SFIXED64"] = 16] = "SFIXED64"; + ScalarType[ScalarType["SINT32"] = 17] = "SINT32"; + ScalarType[ScalarType["SINT64"] = 18] = "SINT64"; +})(ScalarType = exports.ScalarType || (exports.ScalarType = {})); +/** + * JavaScript representation of 64 bit integral types. Equivalent to the + * field option "jstype". + * + * By default, protobuf-ts represents 64 bit types as `bigint`. + * + * You can change the default behaviour by enabling the plugin parameter + * `long_type_string`, which will represent 64 bit types as `string`. + * + * Alternatively, you can change the behaviour for individual fields + * with the field option "jstype": + * + * ```protobuf + * uint64 my_field = 1 [jstype = JS_STRING]; + * uint64 other_field = 2 [jstype = JS_NUMBER]; + * ``` + */ +var LongType; +(function (LongType) { + /** + * Use JavaScript `bigint`. + * + * Field option `[jstype = JS_NORMAL]`. + */ + LongType[LongType["BIGINT"] = 0] = "BIGINT"; + /** + * Use JavaScript `string`. + * + * Field option `[jstype = JS_STRING]`. + */ + LongType[LongType["STRING"] = 1] = "STRING"; + /** + * Use JavaScript `number`. + * + * Large values will loose precision. + * + * Field option `[jstype = JS_NUMBER]`. + */ + LongType[LongType["NUMBER"] = 2] = "NUMBER"; +})(LongType = exports.LongType || (exports.LongType = {})); +/** + * Protobuf 2.1.0 introduced packed repeated fields. + * Setting the field option `[packed = true]` enables packing. + * + * In proto3, all repeated fields are packed by default. + * Setting the field option `[packed = false]` disables packing. + * + * Packed repeated fields are encoded with a single tag, + * then a length-delimiter, then the element values. + * + * Unpacked repeated fields are encoded with a tag and + * value for each element. + * + * `bytes` and `string` cannot be packed. + */ +var RepeatType; +(function (RepeatType) { + /** + * The field is not repeated. + */ + RepeatType[RepeatType["NO"] = 0] = "NO"; + /** + * The field is repeated and should be packed. + * Invalid for `bytes` and `string`, they cannot be packed. + */ + RepeatType[RepeatType["PACKED"] = 1] = "PACKED"; + /** + * The field is repeated but should not be packed. + * The only valid repeat type for repeated `bytes` and `string`. + */ + RepeatType[RepeatType["UNPACKED"] = 2] = "UNPACKED"; +})(RepeatType = exports.RepeatType || (exports.RepeatType = {})); +/** + * Turns PartialFieldInfo into FieldInfo. + */ +function normalizeFieldInfo(field) { + var _a, _b, _c, _d; + field.localName = (_a = field.localName) !== null && _a !== void 0 ? _a : lower_camel_case_1.lowerCamelCase(field.name); + field.jsonName = (_b = field.jsonName) !== null && _b !== void 0 ? _b : lower_camel_case_1.lowerCamelCase(field.name); + field.repeat = (_c = field.repeat) !== null && _c !== void 0 ? _c : RepeatType.NO; + field.opt = (_d = field.opt) !== null && _d !== void 0 ? _d : (field.repeat ? false : field.oneof ? false : field.kind == "message"); + return field; } -function isKeyOperator(operator) { - return operator === ";" || operator === "&" || operator === "?"; +exports.normalizeFieldInfo = normalizeFieldInfo; +/** + * Read custom field options from a generated message type. + * + * @deprecated use readFieldOption() + */ +function readFieldOptions(messageType, fieldName, extensionName, extensionType) { + var _a; + const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; + return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : undefined; } -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(""); +exports.readFieldOptions = readFieldOptions; +function readFieldOption(messageType, fieldName, extensionName, extensionType) { + var _a; + const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; + if (!options) { + return undefined; } - } - 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); - } + const optionVal = options[extensionName]; + if (optionVal === undefined) { + return optionVal; } - ); - if (template === "/") { - return template; - } else { - return template.replace(/\/$/, ""); - } + return extensionType ? extensionType.fromJson(optionVal) : optionVal; } - -// 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; - } +exports.readFieldOption = readFieldOption; +function readMessageOption(messageType, extensionName, extensionType) { + const options = messageType.options; + const optionVal = options[extensionName]; + if (optionVal === undefined) { + return optionVal; } - } - 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 - }); + return extensionType ? extensionType.fromJson(optionVal) : optionVal; } - -// pkg/dist-src/index.js -var endpoint = withDefaults(null, DEFAULTS); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +exports.readMessageOption = readMessageOption; /***/ }), -/***/ 88467: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 229: +/***/ ((__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, { - GraphqlResponseError: () => GraphqlResponseError, - graphql: () => graphql2, - withCustomRequest: () => withCustomRequest -}); -module.exports = __toCommonJS(dist_src_exports); -var import_request3 = __nccwpck_require__(36234); -var import_universal_user_agent = __nccwpck_require__(45030); - -// pkg/dist-src/version.js -var VERSION = "7.0.2"; - -// pkg/dist-src/with-defaults.js -var import_request2 = __nccwpck_require__(36234); - -// pkg/dist-src/graphql.js -var import_request = __nccwpck_require__(36234); - -// 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); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ReflectionJsonReader = void 0; +const json_typings_1 = __nccwpck_require__(70661); +const base64_1 = __nccwpck_require__(20196); +const reflection_info_1 = __nccwpck_require__(21370); +const pb_long_1 = __nccwpck_require__(47777); +const assert_1 = __nccwpck_require__(54253); +const reflection_long_convert_1 = __nccwpck_require__(24612); +/** + * Reads proto3 messages in canonical JSON format using reflection information. + * + * https://developers.google.com/protocol-buffers/docs/proto3#json + */ +class ReflectionJsonReader { + constructor(info) { + this.info = info; } - } -}; - -// 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`) - ); + prepare() { + var _a; + if (this.fMap === undefined) { + this.fMap = {}; + const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; + for (const field of fieldsInput) { + this.fMap[field.name] = field; + this.fMap[field.jsonName] = field; + this.fMap[field.localName] = field; + } + } } - 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` - ) - ); + // Cannot parse JSON for #. + assert(condition, fieldName, jsonValue) { + if (!condition) { + let what = json_typings_1.typeofJsonValue(jsonValue); + if (what == "number" || what == "boolean") + what = jsonValue.toString(); + throw new Error(`Cannot parse JSON ${what} for ${this.info.typeName}#${fieldName}`); + } } - } - 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; + /** + * Reads a message from canonical JSON format into the target message. + * + * Repeated fields are appended. Map entries are added, overwriting + * existing keys. + * + * If a message field is already present, it will be merged with the + * new data. + */ + read(input, message, options) { + this.prepare(); + const oneofsHandled = []; + for (const [jsonKey, jsonValue] of Object.entries(input)) { + const field = this.fMap[jsonKey]; + if (!field) { + if (!options.ignoreUnknownFields) + throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${jsonKey}`); + continue; + } + const localName = field.localName; + // handle oneof ADT + let target; // this will be the target for the field value, whether it is member of a oneof or not + if (field.oneof) { + if (jsonValue === null && (field.kind !== 'enum' || field.T()[0] !== 'google.protobuf.NullValue')) { + continue; + } + // since json objects are unordered by specification, it is not possible to take the last of multiple oneofs + if (oneofsHandled.includes(field.oneof)) + throw new Error(`Multiple members of the oneof group "${field.oneof}" of ${this.info.typeName} are present in JSON.`); + oneofsHandled.push(field.oneof); + target = message[field.oneof] = { + oneofKind: localName + }; + } + else { + target = message; + } + // we have handled oneof above. we just have read the value into `target`. + if (field.kind == 'map') { + if (jsonValue === null) { + continue; + } + // check input + this.assert(json_typings_1.isJsonObject(jsonValue), field.name, jsonValue); + // our target to put map entries into + const fieldObj = target[localName]; + // read entries + for (const [jsonObjKey, jsonObjValue] of Object.entries(jsonValue)) { + this.assert(jsonObjValue !== null, field.name + " map value", null); + // read value + let val; + switch (field.V.kind) { + case "message": + val = field.V.T().internalJsonRead(jsonObjValue, options); + break; + case "enum": + val = this.enum(field.V.T(), jsonObjValue, field.name, options.ignoreUnknownFields); + if (val === false) + continue; + break; + case "scalar": + val = this.scalar(jsonObjValue, field.V.T, field.V.L, field.name); + break; + } + this.assert(val !== undefined, field.name + " map value", jsonObjValue); + // read key + let key = jsonObjKey; + if (field.K == reflection_info_1.ScalarType.BOOL) + key = key == "true" ? true : key == "false" ? false : key; + key = this.scalar(key, field.K, reflection_info_1.LongType.STRING, field.name).toString(); + fieldObj[key] = val; + } + } + else if (field.repeat) { + if (jsonValue === null) + continue; + // check input + this.assert(Array.isArray(jsonValue), field.name, jsonValue); + // our target to put array entries into + const fieldArr = target[localName]; + // read array entries + for (const jsonItem of jsonValue) { + this.assert(jsonItem !== null, field.name, null); + let val; + switch (field.kind) { + case "message": + val = field.T().internalJsonRead(jsonItem, options); + break; + case "enum": + val = this.enum(field.T(), jsonItem, field.name, options.ignoreUnknownFields); + if (val === false) + continue; + break; + case "scalar": + val = this.scalar(jsonItem, field.T, field.L, field.name); + break; + } + this.assert(val !== undefined, field.name, jsonValue); + fieldArr.push(val); + } + } + else { + switch (field.kind) { + case "message": + if (jsonValue === null && field.T().typeName != 'google.protobuf.Value') { + this.assert(field.oneof === undefined, field.name + " (oneof member)", null); + continue; + } + target[localName] = field.T().internalJsonRead(jsonValue, options, target[localName]); + break; + case "enum": + let val = this.enum(field.T(), jsonValue, field.name, options.ignoreUnknownFields); + if (val === false) + continue; + target[localName] = val; + break; + case "scalar": + target[localName] = this.scalar(jsonValue, field.T, field.L, field.name); + break; + } + } + } } - if (!result.variables) { - result.variables = {}; + /** + * Returns `false` for unrecognized string representations. + * + * google.protobuf.NullValue accepts only JSON `null` (or the old `"NULL_VALUE"`). + */ + enum(type, json, fieldName, ignoreUnknownFields) { + if (type[0] == 'google.protobuf.NullValue') + assert_1.assert(json === null || json === "NULL_VALUE", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type[0]} only accepts null.`); + if (json === null) + // we require 0 to be default value for all enums + return 0; + switch (typeof json) { + case "number": + assert_1.assert(Number.isInteger(json), `Unable to parse field ${this.info.typeName}#${fieldName}, enum can only be integral number, got ${json}.`); + return json; + case "string": + let localEnumName = json; + if (type[2] && json.substring(0, type[2].length) === type[2]) + // lookup without the shared prefix + localEnumName = json.substring(type[2].length); + let enumNumber = type[1][localEnumName]; + if (typeof enumNumber === 'undefined' && ignoreUnknownFields) { + return false; + } + assert_1.assert(typeof enumNumber == "number", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type[0]} has no value for "${json}".`); + return enumNumber; + } + assert_1.assert(false, `Unable to parse field ${this.info.typeName}#${fieldName}, cannot parse enum value from ${typeof json}".`); } - 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 - ); + scalar(json, type, longType, fieldName) { + let e; + try { + switch (type) { + // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". + // Either numbers or strings are accepted. Exponent notation is also accepted. + case reflection_info_1.ScalarType.DOUBLE: + case reflection_info_1.ScalarType.FLOAT: + if (json === null) + return .0; + if (json === "NaN") + return Number.NaN; + if (json === "Infinity") + return Number.POSITIVE_INFINITY; + if (json === "-Infinity") + return Number.NEGATIVE_INFINITY; + if (json === "") { + e = "empty string"; + break; + } + if (typeof json == "string" && json.trim().length !== json.length) { + e = "extra whitespace"; + break; + } + if (typeof json != "string" && typeof json != "number") { + break; + } + let float = Number(json); + if (Number.isNaN(float)) { + e = "not a number"; + break; + } + if (!Number.isFinite(float)) { + // infinity and -infinity are handled by string representation above, so this is an error + e = "too large or small"; + break; + } + if (type == reflection_info_1.ScalarType.FLOAT) + assert_1.assertFloat32(float); + return float; + // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + case reflection_info_1.ScalarType.UINT32: + if (json === null) + return 0; + let int32; + if (typeof json == "number") + int32 = json; + else if (json === "") + e = "empty string"; + else if (typeof json == "string") { + if (json.trim().length !== json.length) + e = "extra whitespace"; + else + int32 = Number(json); + } + if (int32 === undefined) + break; + if (type == reflection_info_1.ScalarType.UINT32) + assert_1.assertUInt32(int32); + else + assert_1.assertInt32(int32); + return int32; + // int64, fixed64, uint64: JSON value will be a decimal string. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + if (json === null) + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); + if (typeof json != "number" && typeof json != "string") + break; + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.from(json), longType); + case reflection_info_1.ScalarType.FIXED64: + case reflection_info_1.ScalarType.UINT64: + if (json === null) + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); + if (typeof json != "number" && typeof json != "string") + break; + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.from(json), longType); + // bool: + case reflection_info_1.ScalarType.BOOL: + if (json === null) + return false; + if (typeof json !== "boolean") + break; + return json; + // string: + case reflection_info_1.ScalarType.STRING: + if (json === null) + return ""; + if (typeof json !== "string") { + e = "extra whitespace"; + break; + } + try { + encodeURIComponent(json); + } + catch (e) { + e = "invalid UTF8"; + break; + } + return json; + // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. + // Either standard or URL-safe base64 encoding with/without paddings are accepted. + case reflection_info_1.ScalarType.BYTES: + if (json === null || json === "") + return new Uint8Array(0); + if (typeof json !== 'string') + break; + return base64_1.base64decode(json); + } + } + catch (error) { + e = error.message; + } + this.assert(false, fieldName + (e ? " - " + e : ""), json); } - return response.data.data; - }); } +exports.ReflectionJsonReader = ReflectionJsonReader; -// 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" - }); +/***/ }), + +/***/ 68980: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ReflectionJsonWriter = void 0; +const base64_1 = __nccwpck_require__(20196); +const pb_long_1 = __nccwpck_require__(47777); +const reflection_info_1 = __nccwpck_require__(21370); +const assert_1 = __nccwpck_require__(54253); +/** + * Writes proto3 messages in canonical JSON format using reflection + * information. + * + * https://developers.google.com/protocol-buffers/docs/proto3#json + */ +class ReflectionJsonWriter { + constructor(info) { + var _a; + this.fields = (_a = info.fields) !== null && _a !== void 0 ? _a : []; + } + /** + * Converts the message to a JSON object, based on the field descriptors. + */ + write(message, options) { + const json = {}, source = message; + for (const field of this.fields) { + // field is not part of a oneof, simply write as is + if (!field.oneof) { + let jsonValue = this.field(field, source[field.localName], options); + if (jsonValue !== undefined) + json[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue; + continue; + } + // field is part of a oneof + const group = source[field.oneof]; + if (group.oneofKind !== field.localName) + continue; // not selected, skip + const opt = field.kind == 'scalar' || field.kind == 'enum' + ? Object.assign(Object.assign({}, options), { emitDefaultValues: true }) : options; + let jsonValue = this.field(field, group[field.localName], opt); + assert_1.assert(jsonValue !== undefined); + json[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue; + } + return json; + } + field(field, value, options) { + let jsonValue = undefined; + if (field.kind == 'map') { + assert_1.assert(typeof value == "object" && value !== null); + const jsonObj = {}; + switch (field.V.kind) { + case "scalar": + for (const [entryKey, entryValue] of Object.entries(value)) { + const val = this.scalar(field.V.T, entryValue, field.name, false, true); + assert_1.assert(val !== undefined); + jsonObj[entryKey.toString()] = val; // JSON standard allows only (double quoted) string as property key + } + break; + case "message": + const messageType = field.V.T(); + for (const [entryKey, entryValue] of Object.entries(value)) { + const val = this.message(messageType, entryValue, field.name, options); + assert_1.assert(val !== undefined); + jsonObj[entryKey.toString()] = val; // JSON standard allows only (double quoted) string as property key + } + break; + case "enum": + const enumInfo = field.V.T(); + for (const [entryKey, entryValue] of Object.entries(value)) { + assert_1.assert(entryValue === undefined || typeof entryValue == 'number'); + const val = this.enum(enumInfo, entryValue, field.name, false, true, options.enumAsInteger); + assert_1.assert(val !== undefined); + jsonObj[entryKey.toString()] = val; // JSON standard allows only (double quoted) string as property key + } + break; + } + if (options.emitDefaultValues || Object.keys(jsonObj).length > 0) + jsonValue = jsonObj; + } + else if (field.repeat) { + assert_1.assert(Array.isArray(value)); + const jsonArr = []; + switch (field.kind) { + case "scalar": + for (let i = 0; i < value.length; i++) { + const val = this.scalar(field.T, value[i], field.name, field.opt, true); + assert_1.assert(val !== undefined); + jsonArr.push(val); + } + break; + case "enum": + const enumInfo = field.T(); + for (let i = 0; i < value.length; i++) { + assert_1.assert(value[i] === undefined || typeof value[i] == 'number'); + const val = this.enum(enumInfo, value[i], field.name, field.opt, true, options.enumAsInteger); + assert_1.assert(val !== undefined); + jsonArr.push(val); + } + break; + case "message": + const messageType = field.T(); + for (let i = 0; i < value.length; i++) { + const val = this.message(messageType, value[i], field.name, options); + assert_1.assert(val !== undefined); + jsonArr.push(val); + } + break; + } + // add converted array to json output + if (options.emitDefaultValues || jsonArr.length > 0 || options.emitDefaultValues) + jsonValue = jsonArr; + } + else { + switch (field.kind) { + case "scalar": + jsonValue = this.scalar(field.T, value, field.name, field.opt, options.emitDefaultValues); + break; + case "enum": + jsonValue = this.enum(field.T(), value, field.name, field.opt, options.emitDefaultValues, options.enumAsInteger); + break; + case "message": + jsonValue = this.message(field.T(), value, field.name, options); + break; + } + } + return jsonValue; + } + /** + * Returns `null` as the default for google.protobuf.NullValue. + */ + enum(type, value, fieldName, optional, emitDefaultValues, enumAsInteger) { + if (type[0] == 'google.protobuf.NullValue') + return !emitDefaultValues && !optional ? undefined : null; + if (value === undefined) { + assert_1.assert(optional); + return undefined; + } + if (value === 0 && !emitDefaultValues && !optional) + // we require 0 to be default value for all enums + return undefined; + assert_1.assert(typeof value == 'number'); + assert_1.assert(Number.isInteger(value)); + if (enumAsInteger || !type[1].hasOwnProperty(value)) + // if we don't now the enum value, just return the number + return value; + if (type[2]) + // restore the dropped prefix + return type[2] + type[1][value]; + return type[1][value]; + } + message(type, value, fieldName, options) { + if (value === undefined) + return options.emitDefaultValues ? null : undefined; + return type.internalJsonWrite(value, options); + } + scalar(type, value, fieldName, optional, emitDefaultValues) { + if (value === undefined) { + assert_1.assert(optional); + return undefined; + } + const ed = emitDefaultValues || optional; + // noinspection FallThroughInSwitchStatementJS + switch (type) { + // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + if (value === 0) + return ed ? 0 : undefined; + assert_1.assertInt32(value); + return value; + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.UINT32: + if (value === 0) + return ed ? 0 : undefined; + assert_1.assertUInt32(value); + return value; + // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". + // Either numbers or strings are accepted. Exponent notation is also accepted. + case reflection_info_1.ScalarType.FLOAT: + assert_1.assertFloat32(value); + case reflection_info_1.ScalarType.DOUBLE: + if (value === 0) + return ed ? 0 : undefined; + assert_1.assert(typeof value == 'number'); + if (Number.isNaN(value)) + return 'NaN'; + if (value === Number.POSITIVE_INFINITY) + return 'Infinity'; + if (value === Number.NEGATIVE_INFINITY) + return '-Infinity'; + return value; + // string: + case reflection_info_1.ScalarType.STRING: + if (value === "") + return ed ? '' : undefined; + assert_1.assert(typeof value == 'string'); + return value; + // bool: + case reflection_info_1.ScalarType.BOOL: + if (value === false) + return ed ? false : undefined; + assert_1.assert(typeof value == 'boolean'); + return value; + // JSON value will be a decimal string. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.UINT64: + case reflection_info_1.ScalarType.FIXED64: + assert_1.assert(typeof value == 'number' || typeof value == 'string' || typeof value == 'bigint'); + let ulong = pb_long_1.PbULong.from(value); + if (ulong.isZero() && !ed) + return undefined; + return ulong.toString(); + // JSON value will be a decimal string. Either numbers or strings are accepted. + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + assert_1.assert(typeof value == 'number' || typeof value == 'string' || typeof value == 'bigint'); + let long = pb_long_1.PbLong.from(value); + if (long.isZero() && !ed) + return undefined; + return long.toString(); + // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. + // Either standard or URL-safe base64 encoding with/without paddings are accepted. + case reflection_info_1.ScalarType.BYTES: + assert_1.assert(value instanceof Uint8Array); + if (!value.byteLength) + return ed ? "" : undefined; + return base64_1.base64encode(value); + } + } } -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +exports.ReflectionJsonWriter = ReflectionJsonWriter; /***/ }), -/***/ 64193: -/***/ ((module) => { +/***/ 24612: +/***/ ((__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); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.reflectionLongConvert = void 0; +const reflection_info_1 = __nccwpck_require__(21370); +/** + * Utility method to convert a PbLong or PbUlong to a JavaScript + * representation during runtime. + * + * Works with generated field information, `undefined` is equivalent + * to `STRING`. + */ +function reflectionLongConvert(long, type) { + switch (type) { + case reflection_info_1.LongType.BIGINT: + return long.toBigInt(); + case reflection_info_1.LongType.NUMBER: + return long.toNumber(); + default: + // case undefined: + // case LongType.STRING: + return long.toString(); + } +} +exports.reflectionLongConvert = reflectionLongConvert; -// 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.1.5"; +/***/ }), -// 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; -} +/***/ 7869: +/***/ ((__unused_webpack_module, exports) => { -// 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: [] +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.reflectionMergePartial = void 0; +/** + * Copy partial data into the target message. + * + * If a singular scalar or enum field is present in the source, it + * replaces the field in the target. + * + * If a singular message field is present in the source, it is merged + * with the target field by calling mergePartial() of the responsible + * message type. + * + * If a repeated field is present in the source, its values replace + * all values in the target array, removing extraneous values. + * Repeated message fields are copied, not merged. + * + * If a map field is present in the source, entries are added to the + * target map, replacing entries with the same key. Entries that only + * exist in the target remain. Entries with message values are copied, + * not merged. + * + * Note that this function differs from protobuf merge semantics, + * which appends repeated fields. + */ +function reflectionMergePartial(info, target, source) { + let fieldValue, // the field value we are working with + input = source, output; // where we want our field value to go + for (let field of info.fields) { + let name = field.localName; + if (field.oneof) { + const group = input[field.oneof]; // this is the oneof`s group in the source + if ((group === null || group === void 0 ? void 0 : group.oneofKind) == undefined) { // the user is free to omit + continue; // we skip this field, and all other members too + } + fieldValue = group[name]; // our value comes from the the oneof group of the source + output = target[field.oneof]; // and our output is the oneof group of the target + output.oneofKind = group.oneofKind; // always update discriminator + if (fieldValue == undefined) { + delete output[name]; // remove any existing value + continue; // skip further work on field } - }; } - } - }) - }; + else { + fieldValue = input[name]; // we are using the source directly + output = target; // we want our field value to go directly into the target + if (fieldValue == undefined) { + continue; // skip further work on field, existing value is used as is + } + } + if (field.repeat) + output[name].length = fieldValue.length; // resize target array to match source array + // now we just work with `fieldValue` and `output` to merge the value + switch (field.kind) { + case "scalar": + case "enum": + if (field.repeat) + for (let i = 0; i < fieldValue.length; i++) + output[name][i] = fieldValue[i]; // not a reference type + else + output[name] = fieldValue; // not a reference type + break; + case "message": + let T = field.T(); + if (field.repeat) + for (let i = 0; i < fieldValue.length; i++) + output[name][i] = T.create(fieldValue[i]); + else if (output[name] === undefined) + output[name] = T.create(fieldValue); // nothing to merge with + else + T.mergePartial(output[name], fieldValue); + break; + case "map": + // Map and repeated fields are simply overwritten, not appended or merged + switch (field.V.kind) { + case "scalar": + case "enum": + Object.assign(output[name], fieldValue); // elements are not reference types + break; + case "message": + let T = field.V.T(); + for (let k of Object.keys(fieldValue)) + output[name][k] = T.create(fieldValue[k]); + break; + } + break; + } + } } +exports.reflectionMergePartial = reflectionMergePartial; -// 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; + +/***/ }), + +/***/ 74863: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.reflectionScalarDefault = void 0; +const reflection_info_1 = __nccwpck_require__(21370); +const reflection_long_convert_1 = __nccwpck_require__(24612); +const pb_long_1 = __nccwpck_require__(47777); +/** + * Creates the default value for a scalar type. + */ +function reflectionScalarDefault(type, longType = reflection_info_1.LongType.STRING) { + switch (type) { + case reflection_info_1.ScalarType.BOOL: + return false; + case reflection_info_1.ScalarType.UINT64: + case reflection_info_1.ScalarType.FIXED64: + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); + case reflection_info_1.ScalarType.DOUBLE: + case reflection_info_1.ScalarType.FLOAT: + return 0.0; + case reflection_info_1.ScalarType.BYTES: + return new Uint8Array(0); + case reflection_info_1.ScalarType.STRING: + return ""; + default: + // case ScalarType.INT32: + // case ScalarType.UINT32: + // case ScalarType.SINT32: + // case ScalarType.FIXED32: + // case ScalarType.SFIXED32: + return 0; } - return gather(octokit, results, iterator2, mapFn); - }); } +exports.reflectionScalarDefault = reflectionScalarDefault; -// 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}/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; - } +/***/ 20903: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ReflectionTypeCheck = void 0; +const reflection_info_1 = __nccwpck_require__(21370); +const oneof_1 = __nccwpck_require__(78531); +// noinspection JSMethodCanBeStatic +class ReflectionTypeCheck { + constructor(info) { + var _a; + this.fields = (_a = info.fields) !== null && _a !== void 0 ? _a : []; + } + prepare() { + if (this.data) + return; + const req = [], known = [], oneofs = []; + for (let field of this.fields) { + if (field.oneof) { + if (!oneofs.includes(field.oneof)) { + oneofs.push(field.oneof); + req.push(field.oneof); + known.push(field.oneof); + } + } + else { + known.push(field.localName); + switch (field.kind) { + case "scalar": + case "enum": + if (!field.opt || field.repeat) + req.push(field.localName); + break; + case "message": + if (field.repeat) + req.push(field.localName); + break; + case "map": + req.push(field.localName); + break; + } + } + } + this.data = { req, known, oneofs: Object.values(oneofs) }; + } + /** + * Is the argument a valid message as specified by the + * reflection information? + * + * Checks all field types recursively. The `depth` + * specifies how deep into the structure the check will be. + * + * With a depth of 0, only the presence of fields + * is checked. + * + * With a depth of 1 or more, the field types are checked. + * + * With a depth of 2 or more, the members of map, repeated + * and message fields are checked. + * + * Message fields will be checked recursively with depth - 1. + * + * The number of map entries / repeated values being checked + * is < depth. + */ + is(message, depth, allowExcessProperties = false) { + if (depth < 0) + return true; + if (message === null || message === undefined || typeof message != 'object') + return false; + this.prepare(); + let keys = Object.keys(message), data = this.data; + // if a required field is missing in arg, this cannot be a T + if (keys.length < data.req.length || data.req.some(n => !keys.includes(n))) + return false; + if (!allowExcessProperties) { + // if the arg contains a key we dont know, this is not a literal T + if (keys.some(k => !data.known.includes(k))) + return false; + } + // "With a depth of 0, only the presence and absence of fields is checked." + // "With a depth of 1 or more, the field types are checked." + if (depth < 1) { + return true; + } + // check oneof group + for (const name of data.oneofs) { + const group = message[name]; + if (!oneof_1.isOneofGroup(group)) + return false; + if (group.oneofKind === undefined) + continue; + const field = this.fields.find(f => f.localName === group.oneofKind); + if (!field) + return false; // we found no field, but have a kind, something is wrong + if (!this.field(group[group.oneofKind], field, allowExcessProperties, depth)) + return false; + } + // check types + for (const field of this.fields) { + if (field.oneof !== undefined) + continue; + if (!this.field(message[field.localName], field, allowExcessProperties, depth)) + return false; + } + return true; + } + field(arg, field, allowExcessProperties, depth) { + let repeated = field.repeat; + switch (field.kind) { + case "scalar": + if (arg === undefined) + return field.opt; + if (repeated) + return this.scalars(arg, field.T, depth, field.L); + return this.scalar(arg, field.T, field.L); + case "enum": + if (arg === undefined) + return field.opt; + if (repeated) + return this.scalars(arg, reflection_info_1.ScalarType.INT32, depth); + return this.scalar(arg, reflection_info_1.ScalarType.INT32); + case "message": + if (arg === undefined) + return true; + if (repeated) + return this.messages(arg, field.T(), allowExcessProperties, depth); + return this.message(arg, field.T(), allowExcessProperties, depth); + case "map": + if (typeof arg != 'object' || arg === null) + return false; + if (depth < 2) + return true; + if (!this.mapKeys(arg, field.K, depth)) + return false; + switch (field.V.kind) { + case "scalar": + return this.scalars(Object.values(arg), field.V.T, depth, field.V.L); + case "enum": + return this.scalars(Object.values(arg), reflection_info_1.ScalarType.INT32, depth); + case "message": + return this.messages(Object.values(arg), field.V.T(), allowExcessProperties, depth); + } + break; + } + return true; + } + message(arg, type, allowExcessProperties, depth) { + if (allowExcessProperties) { + return type.isAssignable(arg, depth); + } + return type.is(arg, depth); + } + messages(arg, type, allowExcessProperties, depth) { + if (!Array.isArray(arg)) + return false; + if (depth < 2) + return true; + if (allowExcessProperties) { + for (let i = 0; i < arg.length && i < depth; i++) + if (!type.isAssignable(arg[i], depth - 1)) + return false; + } + else { + for (let i = 0; i < arg.length && i < depth; i++) + if (!type.is(arg[i], depth - 1)) + return false; + } + return true; + } + scalar(arg, type, longType) { + let argType = typeof arg; + switch (type) { + case reflection_info_1.ScalarType.UINT64: + case reflection_info_1.ScalarType.FIXED64: + case reflection_info_1.ScalarType.INT64: + case reflection_info_1.ScalarType.SFIXED64: + case reflection_info_1.ScalarType.SINT64: + switch (longType) { + case reflection_info_1.LongType.BIGINT: + return argType == "bigint"; + case reflection_info_1.LongType.NUMBER: + return argType == "number" && !isNaN(arg); + default: + return argType == "string"; + } + case reflection_info_1.ScalarType.BOOL: + return argType == 'boolean'; + case reflection_info_1.ScalarType.STRING: + return argType == 'string'; + case reflection_info_1.ScalarType.BYTES: + return arg instanceof Uint8Array; + case reflection_info_1.ScalarType.DOUBLE: + case reflection_info_1.ScalarType.FLOAT: + return argType == 'number' && !isNaN(arg); + default: + // case ScalarType.UINT32: + // case ScalarType.FIXED32: + // case ScalarType.INT32: + // case ScalarType.SINT32: + // case ScalarType.SFIXED32: + return argType == 'number' && Number.isInteger(arg); + } + } + scalars(arg, type, depth, longType) { + if (!Array.isArray(arg)) + return false; + if (depth < 2) + return true; + if (Array.isArray(arg)) + for (let i = 0; i < arg.length && i < depth; i++) + if (!this.scalar(arg[i], type, longType)) + return false; + return true; + } + mapKeys(map, type, depth) { + let keys = Object.keys(map); + switch (type) { + case reflection_info_1.ScalarType.INT32: + case reflection_info_1.ScalarType.FIXED32: + case reflection_info_1.ScalarType.SFIXED32: + case reflection_info_1.ScalarType.SINT32: + case reflection_info_1.ScalarType.UINT32: + return this.scalars(keys.slice(0, depth).map(k => parseInt(k)), type, depth); + case reflection_info_1.ScalarType.BOOL: + return this.scalars(keys.slice(0, depth).map(k => k == 'true' ? true : k == 'false' ? false : k), type, depth); + default: + return this.scalars(keys, type, depth, reflection_info_1.LongType.STRING); + } + } } +exports.ReflectionTypeCheck = ReflectionTypeCheck; -// pkg/dist-src/index.js -function paginateRest(octokit) { - return { - paginate: Object.assign(paginate.bind(null, octokit), { - iterator: iterator.bind(null, octokit) - }) - }; + +/***/ }), + +/***/ 7678: +/***/ ((module, exports) => { + +"use strict"; + +/// +/// +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +const typedArrayTypeNames = [ + 'Int8Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Int16Array', + 'Uint16Array', + 'Int32Array', + 'Uint32Array', + 'Float32Array', + 'Float64Array', + 'BigInt64Array', + 'BigUint64Array' +]; +function isTypedArrayName(name) { + return typedArrayTypeNames.includes(name); } -paginateRest.VERSION = VERSION; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +const objectTypeNames = [ + 'Function', + 'Generator', + 'AsyncGenerator', + 'GeneratorFunction', + 'AsyncGeneratorFunction', + 'AsyncFunction', + 'Observable', + 'Array', + 'Buffer', + 'Blob', + 'Object', + 'RegExp', + 'Date', + 'Error', + 'Map', + 'Set', + 'WeakMap', + 'WeakSet', + 'ArrayBuffer', + 'SharedArrayBuffer', + 'DataView', + 'Promise', + 'URL', + 'FormData', + 'URLSearchParams', + 'HTMLElement', + ...typedArrayTypeNames +]; +function isObjectTypeName(name) { + return objectTypeNames.includes(name); +} +const primitiveTypeNames = [ + 'null', + 'undefined', + 'string', + 'number', + 'bigint', + 'boolean', + 'symbol' +]; +function isPrimitiveTypeName(name) { + return primitiveTypeNames.includes(name); +} +// eslint-disable-next-line @typescript-eslint/ban-types +function isOfType(type) { + return (value) => typeof value === type; +} +const { toString } = Object.prototype; +const getObjectType = (value) => { + const objectTypeName = toString.call(value).slice(8, -1); + if (/HTML\w+Element/.test(objectTypeName) && is.domElement(value)) { + return 'HTMLElement'; + } + if (isObjectTypeName(objectTypeName)) { + return objectTypeName; + } + return undefined; +}; +const isObjectOfType = (type) => (value) => getObjectType(value) === type; +function is(value) { + if (value === null) { + return 'null'; + } + switch (typeof value) { + case 'undefined': + return 'undefined'; + case 'string': + return 'string'; + case 'number': + return 'number'; + case 'boolean': + return 'boolean'; + case 'function': + return 'Function'; + case 'bigint': + return 'bigint'; + case 'symbol': + return 'symbol'; + default: + } + if (is.observable(value)) { + return 'Observable'; + } + if (is.array(value)) { + return 'Array'; + } + if (is.buffer(value)) { + return 'Buffer'; + } + const tagType = getObjectType(value); + if (tagType) { + return tagType; + } + if (value instanceof String || value instanceof Boolean || value instanceof Number) { + throw new TypeError('Please don\'t use object wrappers for primitive types'); + } + return 'Object'; +} +is.undefined = isOfType('undefined'); +is.string = isOfType('string'); +const isNumberType = isOfType('number'); +is.number = (value) => isNumberType(value) && !is.nan(value); +is.bigint = isOfType('bigint'); +// eslint-disable-next-line @typescript-eslint/ban-types +is.function_ = isOfType('function'); +is.null_ = (value) => value === null; +is.class_ = (value) => is.function_(value) && value.toString().startsWith('class '); +is.boolean = (value) => value === true || value === false; +is.symbol = isOfType('symbol'); +is.numericString = (value) => is.string(value) && !is.emptyStringOrWhitespace(value) && !Number.isNaN(Number(value)); +is.array = (value, assertion) => { + if (!Array.isArray(value)) { + return false; + } + if (!is.function_(assertion)) { + return true; + } + return value.every(assertion); +}; +is.buffer = (value) => { var _a, _b, _c, _d; return (_d = (_c = (_b = (_a = value) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.isBuffer) === null || _c === void 0 ? void 0 : _c.call(_b, value)) !== null && _d !== void 0 ? _d : false; }; +is.blob = (value) => isObjectOfType('Blob')(value); +is.nullOrUndefined = (value) => is.null_(value) || is.undefined(value); +is.object = (value) => !is.null_(value) && (typeof value === 'object' || is.function_(value)); +is.iterable = (value) => { var _a; return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a[Symbol.iterator]); }; +is.asyncIterable = (value) => { var _a; return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a[Symbol.asyncIterator]); }; +is.generator = (value) => { var _a, _b; return is.iterable(value) && is.function_((_a = value) === null || _a === void 0 ? void 0 : _a.next) && is.function_((_b = value) === null || _b === void 0 ? void 0 : _b.throw); }; +is.asyncGenerator = (value) => is.asyncIterable(value) && is.function_(value.next) && is.function_(value.throw); +is.nativePromise = (value) => isObjectOfType('Promise')(value); +const hasPromiseAPI = (value) => { + var _a, _b; + return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a.then) && + is.function_((_b = value) === null || _b === void 0 ? void 0 : _b.catch); +}; +is.promise = (value) => is.nativePromise(value) || hasPromiseAPI(value); +is.generatorFunction = isObjectOfType('GeneratorFunction'); +is.asyncGeneratorFunction = (value) => getObjectType(value) === 'AsyncGeneratorFunction'; +is.asyncFunction = (value) => getObjectType(value) === 'AsyncFunction'; +// eslint-disable-next-line no-prototype-builtins, @typescript-eslint/ban-types +is.boundFunction = (value) => is.function_(value) && !value.hasOwnProperty('prototype'); +is.regExp = isObjectOfType('RegExp'); +is.date = isObjectOfType('Date'); +is.error = isObjectOfType('Error'); +is.map = (value) => isObjectOfType('Map')(value); +is.set = (value) => isObjectOfType('Set')(value); +is.weakMap = (value) => isObjectOfType('WeakMap')(value); +is.weakSet = (value) => isObjectOfType('WeakSet')(value); +is.int8Array = isObjectOfType('Int8Array'); +is.uint8Array = isObjectOfType('Uint8Array'); +is.uint8ClampedArray = isObjectOfType('Uint8ClampedArray'); +is.int16Array = isObjectOfType('Int16Array'); +is.uint16Array = isObjectOfType('Uint16Array'); +is.int32Array = isObjectOfType('Int32Array'); +is.uint32Array = isObjectOfType('Uint32Array'); +is.float32Array = isObjectOfType('Float32Array'); +is.float64Array = isObjectOfType('Float64Array'); +is.bigInt64Array = isObjectOfType('BigInt64Array'); +is.bigUint64Array = isObjectOfType('BigUint64Array'); +is.arrayBuffer = isObjectOfType('ArrayBuffer'); +is.sharedArrayBuffer = isObjectOfType('SharedArrayBuffer'); +is.dataView = isObjectOfType('DataView'); +is.enumCase = (value, targetEnum) => Object.values(targetEnum).includes(value); +is.directInstanceOf = (instance, class_) => Object.getPrototypeOf(instance) === class_.prototype; +is.urlInstance = (value) => isObjectOfType('URL')(value); +is.urlString = (value) => { + if (!is.string(value)) { + return false; + } + try { + new URL(value); // eslint-disable-line no-new + return true; + } + catch (_a) { + return false; + } +}; +// Example: `is.truthy = (value: unknown): value is (not false | not 0 | not '' | not undefined | not null) => Boolean(value);` +is.truthy = (value) => Boolean(value); +// Example: `is.falsy = (value: unknown): value is (not true | 0 | '' | undefined | null) => Boolean(value);` +is.falsy = (value) => !value; +is.nan = (value) => Number.isNaN(value); +is.primitive = (value) => is.null_(value) || isPrimitiveTypeName(typeof value); +is.integer = (value) => Number.isInteger(value); +is.safeInteger = (value) => Number.isSafeInteger(value); +is.plainObject = (value) => { + // From: https://github.com/sindresorhus/is-plain-obj/blob/main/index.js + if (toString.call(value) !== '[object Object]') { + return false; + } + const prototype = Object.getPrototypeOf(value); + return prototype === null || prototype === Object.getPrototypeOf({}); +}; +is.typedArray = (value) => isTypedArrayName(getObjectType(value)); +const isValidLength = (value) => is.safeInteger(value) && value >= 0; +is.arrayLike = (value) => !is.nullOrUndefined(value) && !is.function_(value) && isValidLength(value.length); +is.inRange = (value, range) => { + if (is.number(range)) { + return value >= Math.min(0, range) && value <= Math.max(range, 0); + } + if (is.array(range) && range.length === 2) { + return value >= Math.min(...range) && value <= Math.max(...range); + } + throw new TypeError(`Invalid range: ${JSON.stringify(range)}`); +}; +const NODE_TYPE_ELEMENT = 1; +const DOM_PROPERTIES_TO_CHECK = [ + 'innerHTML', + 'ownerDocument', + 'style', + 'attributes', + 'nodeValue' +]; +is.domElement = (value) => { + return is.object(value) && + value.nodeType === NODE_TYPE_ELEMENT && + is.string(value.nodeName) && + !is.plainObject(value) && + DOM_PROPERTIES_TO_CHECK.every(property => property in value); +}; +is.observable = (value) => { + var _a, _b, _c, _d; + if (!value) { + return false; + } + // eslint-disable-next-line no-use-extend-native/no-use-extend-native + if (value === ((_b = (_a = value)[Symbol.observable]) === null || _b === void 0 ? void 0 : _b.call(_a))) { + return true; + } + if (value === ((_d = (_c = value)['@@observable']) === null || _d === void 0 ? void 0 : _d.call(_c))) { + return true; + } + return false; +}; +is.nodeStream = (value) => is.object(value) && is.function_(value.pipe) && !is.observable(value); +is.infinite = (value) => value === Infinity || value === -Infinity; +const isAbsoluteMod2 = (remainder) => (value) => is.integer(value) && Math.abs(value % 2) === remainder; +is.evenInteger = isAbsoluteMod2(0); +is.oddInteger = isAbsoluteMod2(1); +is.emptyArray = (value) => is.array(value) && value.length === 0; +is.nonEmptyArray = (value) => is.array(value) && value.length > 0; +is.emptyString = (value) => is.string(value) && value.length === 0; +const isWhiteSpaceString = (value) => is.string(value) && !/\S/.test(value); +is.emptyStringOrWhitespace = (value) => is.emptyString(value) || isWhiteSpaceString(value); +// TODO: Use `not ''` when the `not` operator is available. +is.nonEmptyString = (value) => is.string(value) && value.length > 0; +// TODO: Use `not ''` when the `not` operator is available. +is.nonEmptyStringAndNotWhitespace = (value) => is.string(value) && !is.emptyStringOrWhitespace(value); +is.emptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length === 0; +// TODO: Use `not` operator here to remove `Map` and `Set` from type guard: +// - https://github.com/Microsoft/TypeScript/pull/29317 +is.nonEmptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length > 0; +is.emptySet = (value) => is.set(value) && value.size === 0; +is.nonEmptySet = (value) => is.set(value) && value.size > 0; +is.emptyMap = (value) => is.map(value) && value.size === 0; +is.nonEmptyMap = (value) => is.map(value) && value.size > 0; +// `PropertyKey` is any value that can be used as an object key (string, number, or symbol) +is.propertyKey = (value) => is.any([is.string, is.number, is.symbol], value); +is.formData = (value) => isObjectOfType('FormData')(value); +is.urlSearchParams = (value) => isObjectOfType('URLSearchParams')(value); +const predicateOnArray = (method, predicate, values) => { + if (!is.function_(predicate)) { + throw new TypeError(`Invalid predicate: ${JSON.stringify(predicate)}`); + } + if (values.length === 0) { + throw new TypeError('Invalid number of values'); + } + return method.call(values, predicate); +}; +is.any = (predicate, ...values) => { + const predicates = is.array(predicate) ? predicate : [predicate]; + return predicates.some(singlePredicate => predicateOnArray(Array.prototype.some, singlePredicate, values)); +}; +is.all = (predicate, ...values) => predicateOnArray(Array.prototype.every, predicate, values); +const assertType = (condition, description, value, options = {}) => { + if (!condition) { + const { multipleValues } = options; + const valuesMessage = multipleValues ? + `received values of types ${[ + ...new Set(value.map(singleValue => `\`${is(singleValue)}\``)) + ].join(', ')}` : + `received value of type \`${is(value)}\``; + throw new TypeError(`Expected value which is \`${description}\`, ${valuesMessage}.`); + } +}; +exports.assert = { + // Unknowns. + undefined: (value) => assertType(is.undefined(value), 'undefined', value), + string: (value) => assertType(is.string(value), 'string', value), + number: (value) => assertType(is.number(value), 'number', value), + bigint: (value) => assertType(is.bigint(value), 'bigint', value), + // eslint-disable-next-line @typescript-eslint/ban-types + function_: (value) => assertType(is.function_(value), 'Function', value), + null_: (value) => assertType(is.null_(value), 'null', value), + class_: (value) => assertType(is.class_(value), "Class" /* class_ */, value), + boolean: (value) => assertType(is.boolean(value), 'boolean', value), + symbol: (value) => assertType(is.symbol(value), 'symbol', value), + numericString: (value) => assertType(is.numericString(value), "string with a number" /* numericString */, value), + array: (value, assertion) => { + const assert = assertType; + assert(is.array(value), 'Array', value); + if (assertion) { + value.forEach(assertion); + } + }, + buffer: (value) => assertType(is.buffer(value), 'Buffer', value), + blob: (value) => assertType(is.blob(value), 'Blob', value), + nullOrUndefined: (value) => assertType(is.nullOrUndefined(value), "null or undefined" /* nullOrUndefined */, value), + object: (value) => assertType(is.object(value), 'Object', value), + iterable: (value) => assertType(is.iterable(value), "Iterable" /* iterable */, value), + asyncIterable: (value) => assertType(is.asyncIterable(value), "AsyncIterable" /* asyncIterable */, value), + generator: (value) => assertType(is.generator(value), 'Generator', value), + asyncGenerator: (value) => assertType(is.asyncGenerator(value), 'AsyncGenerator', value), + nativePromise: (value) => assertType(is.nativePromise(value), "native Promise" /* nativePromise */, value), + promise: (value) => assertType(is.promise(value), 'Promise', value), + generatorFunction: (value) => assertType(is.generatorFunction(value), 'GeneratorFunction', value), + asyncGeneratorFunction: (value) => assertType(is.asyncGeneratorFunction(value), 'AsyncGeneratorFunction', value), + // eslint-disable-next-line @typescript-eslint/ban-types + asyncFunction: (value) => assertType(is.asyncFunction(value), 'AsyncFunction', value), + // eslint-disable-next-line @typescript-eslint/ban-types + boundFunction: (value) => assertType(is.boundFunction(value), 'Function', value), + regExp: (value) => assertType(is.regExp(value), 'RegExp', value), + date: (value) => assertType(is.date(value), 'Date', value), + error: (value) => assertType(is.error(value), 'Error', value), + map: (value) => assertType(is.map(value), 'Map', value), + set: (value) => assertType(is.set(value), 'Set', value), + weakMap: (value) => assertType(is.weakMap(value), 'WeakMap', value), + weakSet: (value) => assertType(is.weakSet(value), 'WeakSet', value), + int8Array: (value) => assertType(is.int8Array(value), 'Int8Array', value), + uint8Array: (value) => assertType(is.uint8Array(value), 'Uint8Array', value), + uint8ClampedArray: (value) => assertType(is.uint8ClampedArray(value), 'Uint8ClampedArray', value), + int16Array: (value) => assertType(is.int16Array(value), 'Int16Array', value), + uint16Array: (value) => assertType(is.uint16Array(value), 'Uint16Array', value), + int32Array: (value) => assertType(is.int32Array(value), 'Int32Array', value), + uint32Array: (value) => assertType(is.uint32Array(value), 'Uint32Array', value), + float32Array: (value) => assertType(is.float32Array(value), 'Float32Array', value), + float64Array: (value) => assertType(is.float64Array(value), 'Float64Array', value), + bigInt64Array: (value) => assertType(is.bigInt64Array(value), 'BigInt64Array', value), + bigUint64Array: (value) => assertType(is.bigUint64Array(value), 'BigUint64Array', value), + arrayBuffer: (value) => assertType(is.arrayBuffer(value), 'ArrayBuffer', value), + sharedArrayBuffer: (value) => assertType(is.sharedArrayBuffer(value), 'SharedArrayBuffer', value), + dataView: (value) => assertType(is.dataView(value), 'DataView', value), + enumCase: (value, targetEnum) => assertType(is.enumCase(value, targetEnum), 'EnumCase', value), + urlInstance: (value) => assertType(is.urlInstance(value), 'URL', value), + urlString: (value) => assertType(is.urlString(value), "string with a URL" /* urlString */, value), + truthy: (value) => assertType(is.truthy(value), "truthy" /* truthy */, value), + falsy: (value) => assertType(is.falsy(value), "falsy" /* falsy */, value), + nan: (value) => assertType(is.nan(value), "NaN" /* nan */, value), + primitive: (value) => assertType(is.primitive(value), "primitive" /* primitive */, value), + integer: (value) => assertType(is.integer(value), "integer" /* integer */, value), + safeInteger: (value) => assertType(is.safeInteger(value), "integer" /* safeInteger */, value), + plainObject: (value) => assertType(is.plainObject(value), "plain object" /* plainObject */, value), + typedArray: (value) => assertType(is.typedArray(value), "TypedArray" /* typedArray */, value), + arrayLike: (value) => assertType(is.arrayLike(value), "array-like" /* arrayLike */, value), + domElement: (value) => assertType(is.domElement(value), "HTMLElement" /* domElement */, value), + observable: (value) => assertType(is.observable(value), 'Observable', value), + nodeStream: (value) => assertType(is.nodeStream(value), "Node.js Stream" /* nodeStream */, value), + infinite: (value) => assertType(is.infinite(value), "infinite number" /* infinite */, value), + emptyArray: (value) => assertType(is.emptyArray(value), "empty array" /* emptyArray */, value), + nonEmptyArray: (value) => assertType(is.nonEmptyArray(value), "non-empty array" /* nonEmptyArray */, value), + emptyString: (value) => assertType(is.emptyString(value), "empty string" /* emptyString */, value), + emptyStringOrWhitespace: (value) => assertType(is.emptyStringOrWhitespace(value), "empty string or whitespace" /* emptyStringOrWhitespace */, value), + nonEmptyString: (value) => assertType(is.nonEmptyString(value), "non-empty string" /* nonEmptyString */, value), + nonEmptyStringAndNotWhitespace: (value) => assertType(is.nonEmptyStringAndNotWhitespace(value), "non-empty string and not whitespace" /* nonEmptyStringAndNotWhitespace */, value), + emptyObject: (value) => assertType(is.emptyObject(value), "empty object" /* emptyObject */, value), + nonEmptyObject: (value) => assertType(is.nonEmptyObject(value), "non-empty object" /* nonEmptyObject */, value), + emptySet: (value) => assertType(is.emptySet(value), "empty set" /* emptySet */, value), + nonEmptySet: (value) => assertType(is.nonEmptySet(value), "non-empty set" /* nonEmptySet */, value), + emptyMap: (value) => assertType(is.emptyMap(value), "empty map" /* emptyMap */, value), + nonEmptyMap: (value) => assertType(is.nonEmptyMap(value), "non-empty map" /* nonEmptyMap */, value), + propertyKey: (value) => assertType(is.propertyKey(value), 'PropertyKey', value), + formData: (value) => assertType(is.formData(value), 'FormData', value), + urlSearchParams: (value) => assertType(is.urlSearchParams(value), 'URLSearchParams', value), + // Numbers. + evenInteger: (value) => assertType(is.evenInteger(value), "even integer" /* evenInteger */, value), + oddInteger: (value) => assertType(is.oddInteger(value), "odd integer" /* oddInteger */, value), + // Two arguments. + directInstanceOf: (instance, class_) => assertType(is.directInstanceOf(instance, class_), "T" /* directInstanceOf */, instance), + inRange: (value, range) => assertType(is.inRange(value, range), "in range" /* inRange */, value), + // Variadic functions. + any: (predicate, ...values) => { + return assertType(is.any(predicate, ...values), "predicate returns truthy for any value" /* any */, values, { multipleValues: true }); + }, + all: (predicate, ...values) => assertType(is.all(predicate, ...values), "predicate returns truthy for all values" /* all */, values, { multipleValues: true }) +}; +// Some few keywords are reserved, but we'll populate them for Node.js users +// See https://github.com/Microsoft/TypeScript/issues/2536 +Object.defineProperties(is, { + class: { + value: is.class_ + }, + function: { + value: is.function_ + }, + null: { + value: is.null_ + } +}); +Object.defineProperties(exports.assert, { + class: { + value: exports.assert.class_ + }, + function: { + value: exports.assert.function_ + }, + null: { + value: exports.assert.null_ + } +}); +exports["default"] = is; +// For CommonJS default export support +module.exports = is; +module.exports["default"] = is; +module.exports.assert = exports.assert; /***/ }), -/***/ 83044: -/***/ ((module) => { +/***/ 53098: +/***/ ((__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 utilConfigProvider = __nccwpck_require__(39840); +var utilMiddleware = __nccwpck_require__(50308); +var utilEndpoints = __nccwpck_require__(29446); + +const ENV_USE_DUALSTACK_ENDPOINT = "AWS_USE_DUALSTACK_ENDPOINT"; +const CONFIG_USE_DUALSTACK_ENDPOINT = "use_dualstack_endpoint"; +const DEFAULT_USE_DUALSTACK_ENDPOINT = false; +const NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => utilConfigProvider.booleanSelector(env, ENV_USE_DUALSTACK_ENDPOINT, utilConfigProvider.SelectorType.ENV), + configFileSelector: (profile) => utilConfigProvider.booleanSelector(profile, CONFIG_USE_DUALSTACK_ENDPOINT, utilConfigProvider.SelectorType.CONFIG), + default: false, }; -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; + +const ENV_USE_FIPS_ENDPOINT = "AWS_USE_FIPS_ENDPOINT"; +const CONFIG_USE_FIPS_ENDPOINT = "use_fips_endpoint"; +const DEFAULT_USE_FIPS_ENDPOINT = false; +const NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => utilConfigProvider.booleanSelector(env, ENV_USE_FIPS_ENDPOINT, utilConfigProvider.SelectorType.ENV), + configFileSelector: (profile) => utilConfigProvider.booleanSelector(profile, CONFIG_USE_FIPS_ENDPOINT, utilConfigProvider.SelectorType.CONFIG), + default: false, }; -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); +const resolveCustomEndpointsConfig = (input) => { + const { tls, endpoint, urlParser, useDualstackEndpoint } = input; + return Object.assign(input, { + tls: tls ?? true, + endpoint: utilMiddleware.normalizeProvider(typeof endpoint === "string" ? urlParser(endpoint) : endpoint), + isCustomEndpoint: true, + useDualstackEndpoint: utilMiddleware.normalizeProvider(useDualstackEndpoint ?? false), + }); +}; -// pkg/dist-src/version.js -var VERSION = "10.3.0"; +const getEndpointFromRegion = async (input) => { + const { tls = true } = input; + const region = await input.region(); + const dnsHostRegex = new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/); + if (!dnsHostRegex.test(region)) { + throw new Error("Invalid region in client config"); + } + const useDualstackEndpoint = await input.useDualstackEndpoint(); + const useFipsEndpoint = await input.useFipsEndpoint(); + const { hostname } = (await input.regionInfoProvider(region, { useDualstackEndpoint, useFipsEndpoint })) ?? {}; + if (!hostname) { + throw new Error("Cannot resolve hostname from client config"); + } + return input.urlParser(`${tls ? "https:" : "http:"}//${hostname}`); +}; + +const resolveEndpointsConfig = (input) => { + const useDualstackEndpoint = utilMiddleware.normalizeProvider(input.useDualstackEndpoint ?? false); + const { endpoint, useFipsEndpoint, urlParser, tls } = input; + return Object.assign(input, { + tls: tls ?? true, + endpoint: endpoint + ? utilMiddleware.normalizeProvider(typeof endpoint === "string" ? urlParser(endpoint) : endpoint) + : () => getEndpointFromRegion({ ...input, useDualstackEndpoint, useFipsEndpoint }), + isCustomEndpoint: !!endpoint, + useDualstackEndpoint, + }); +}; -// 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); - - -/***/ }), - -/***/ 10537: -/***/ ((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__(58932); -var import_once = __toESM(__nccwpck_require__(1223)); -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( - / .*$/, - " [REDACTED]" - ) - }); - } - requestCopy.url = requestCopy.url.replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]").replace(/\baccess_token=\w+/g, "access_token=[REDACTED]"); - this.request = requestCopy; - Object.defineProperty(this, "code", { - get() { - logOnceCode( - new import_deprecation.Deprecation( - "[@octokit/request-error] `error.code` is deprecated, use `error.status`." - ) - ); - return statusCode; - } - }); - Object.defineProperty(this, "headers", { - get() { - logOnceHeaders( - new import_deprecation.Deprecation( - "[@octokit/request-error] `error.headers` is deprecated, use `error.response.headers`." - ) - ); - return headers || {}; - } - }); - } -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 36234: -/***/ ((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, { - request: () => request -}); -module.exports = __toCommonJS(dist_src_exports); -var import_endpoint = __nccwpck_require__(59440); -var import_universal_user_agent = __nccwpck_require__(45030); - -// 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__(10537); - -// 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); - - -/***/ }), - -/***/ 57171: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.ContextAPI = void 0; -const NoopContextManager_1 = __nccwpck_require__(54118); -const global_utils_1 = __nccwpck_require__(85135); -const diag_1 = __nccwpck_require__(11877); -const API_NAME = 'context'; -const NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager(); -/** - * Singleton object which represents the entry point to the OpenTelemetry Context API - */ -class ContextAPI { - /** Empty private constructor prevents end users from constructing a new instance of the API */ - constructor() { } - /** Get the singleton instance of the Context API */ - static getInstance() { - if (!this._instance) { - this._instance = new ContextAPI(); - } - return this._instance; - } - /** - * Set the current context manager. - * - * @returns true if the context manager was successfully registered, else false - */ - setGlobalContextManager(contextManager) { - return (0, global_utils_1.registerGlobal)(API_NAME, contextManager, diag_1.DiagAPI.instance()); - } - /** - * Get the currently active context - */ - active() { - return this._getContextManager().active(); - } - /** - * Execute a function with an active context - * - * @param context context to be active during function execution - * @param fn function to execute in a context - * @param thisArg optional receiver to be used for calling fn - * @param args optional arguments forwarded to fn - */ - with(context, fn, thisArg, ...args) { - return this._getContextManager().with(context, fn, thisArg, ...args); - } - /** - * Bind a context to a target function or event emitter - * - * @param context context to bind to the event emitter or function. Defaults to the currently active context - * @param target function or event emitter to bind - */ - bind(context, target) { - return this._getContextManager().bind(context, target); - } - _getContextManager() { - return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_CONTEXT_MANAGER; - } - /** Disable and remove the global context manager */ - disable() { - this._getContextManager().disable(); - (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); - } -} -exports.ContextAPI = ContextAPI; -//# sourceMappingURL=context.js.map - -/***/ }), - -/***/ 11877: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.DiagAPI = void 0; -const ComponentLogger_1 = __nccwpck_require__(17978); -const logLevelLogger_1 = __nccwpck_require__(99639); -const types_1 = __nccwpck_require__(78077); -const global_utils_1 = __nccwpck_require__(85135); -const API_NAME = 'diag'; -/** - * Singleton object which represents the entry point to the OpenTelemetry internal - * diagnostic API - */ -class DiagAPI { - /** - * Private internal constructor - * @private - */ - constructor() { - function _logProxy(funcName) { - return function (...args) { - const logger = (0, global_utils_1.getGlobal)('diag'); - // shortcut if logger not set - if (!logger) - return; - return logger[funcName](...args); - }; - } - // Using self local variable for minification purposes as 'this' cannot be minified - const self = this; - // DiagAPI specific functions - const setLogger = (logger, optionsOrLogLevel = { logLevel: types_1.DiagLogLevel.INFO }) => { - var _a, _b, _c; - if (logger === self) { - // There isn't much we can do here. - // Logging to the console might break the user application. - // Try to log to self. If a logger was previously registered it will receive the log. - const err = new Error('Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'); - self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message); - return false; - } - if (typeof optionsOrLogLevel === 'number') { - optionsOrLogLevel = { - logLevel: optionsOrLogLevel, - }; - } - const oldLogger = (0, global_utils_1.getGlobal)('diag'); - const newLogger = (0, logLevelLogger_1.createLogLevelDiagLogger)((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : types_1.DiagLogLevel.INFO, logger); - // There already is an logger registered. We'll let it know before overwriting it. - if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { - const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ''; - oldLogger.warn(`Current logger will be overwritten from ${stack}`); - newLogger.warn(`Current logger will overwrite one already registered from ${stack}`); - } - return (0, global_utils_1.registerGlobal)('diag', newLogger, self, true); - }; - self.setLogger = setLogger; - self.disable = () => { - (0, global_utils_1.unregisterGlobal)(API_NAME, self); - }; - self.createComponentLogger = (options) => { - return new ComponentLogger_1.DiagComponentLogger(options); - }; - self.verbose = _logProxy('verbose'); - self.debug = _logProxy('debug'); - self.info = _logProxy('info'); - self.warn = _logProxy('warn'); - self.error = _logProxy('error'); - } - /** Get the singleton instance of the DiagAPI API */ - static instance() { - if (!this._instance) { - this._instance = new DiagAPI(); - } - return this._instance; - } -} -exports.DiagAPI = DiagAPI; -//# sourceMappingURL=diag.js.map - -/***/ }), - -/***/ 17696: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.MetricsAPI = void 0; -const NoopMeterProvider_1 = __nccwpck_require__(72647); -const global_utils_1 = __nccwpck_require__(85135); -const diag_1 = __nccwpck_require__(11877); -const API_NAME = 'metrics'; -/** - * Singleton object which represents the entry point to the OpenTelemetry Metrics API - */ -class MetricsAPI { - /** Empty private constructor prevents end users from constructing a new instance of the API */ - constructor() { } - /** Get the singleton instance of the Metrics API */ - static getInstance() { - if (!this._instance) { - this._instance = new MetricsAPI(); - } - return this._instance; - } - /** - * Set the current global meter provider. - * Returns true if the meter provider was successfully registered, else false. - */ - setGlobalMeterProvider(provider) { - return (0, global_utils_1.registerGlobal)(API_NAME, provider, diag_1.DiagAPI.instance()); - } - /** - * Returns the global meter provider. - */ - getMeterProvider() { - return (0, global_utils_1.getGlobal)(API_NAME) || NoopMeterProvider_1.NOOP_METER_PROVIDER; - } - /** - * Returns a meter from the global meter provider. - */ - getMeter(name, version, options) { - return this.getMeterProvider().getMeter(name, version, options); - } - /** Remove the global meter provider */ - disable() { - (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); - } -} -exports.MetricsAPI = MetricsAPI; -//# sourceMappingURL=metrics.js.map - -/***/ }), - -/***/ 89909: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.PropagationAPI = void 0; -const global_utils_1 = __nccwpck_require__(85135); -const NoopTextMapPropagator_1 = __nccwpck_require__(72368); -const TextMapPropagator_1 = __nccwpck_require__(80865); -const context_helpers_1 = __nccwpck_require__(37682); -const utils_1 = __nccwpck_require__(28136); -const diag_1 = __nccwpck_require__(11877); -const API_NAME = 'propagation'; -const NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator(); -/** - * Singleton object which represents the entry point to the OpenTelemetry Propagation API - */ -class PropagationAPI { - /** Empty private constructor prevents end users from constructing a new instance of the API */ - constructor() { - this.createBaggage = utils_1.createBaggage; - this.getBaggage = context_helpers_1.getBaggage; - this.getActiveBaggage = context_helpers_1.getActiveBaggage; - this.setBaggage = context_helpers_1.setBaggage; - this.deleteBaggage = context_helpers_1.deleteBaggage; - } - /** Get the singleton instance of the Propagator API */ - static getInstance() { - if (!this._instance) { - this._instance = new PropagationAPI(); - } - return this._instance; - } - /** - * Set the current propagator. - * - * @returns true if the propagator was successfully registered, else false - */ - setGlobalPropagator(propagator) { - return (0, global_utils_1.registerGlobal)(API_NAME, propagator, diag_1.DiagAPI.instance()); - } - /** - * Inject context into a carrier to be propagated inter-process - * - * @param context Context carrying tracing data to inject - * @param carrier carrier to inject context into - * @param setter Function used to set values on the carrier - */ - inject(context, carrier, setter = TextMapPropagator_1.defaultTextMapSetter) { - return this._getGlobalPropagator().inject(context, carrier, setter); - } - /** - * Extract context from a carrier - * - * @param context Context which the newly created context will inherit from - * @param carrier Carrier to extract context from - * @param getter Function used to extract keys from a carrier - */ - extract(context, carrier, getter = TextMapPropagator_1.defaultTextMapGetter) { - return this._getGlobalPropagator().extract(context, carrier, getter); - } - /** - * Return a list of all fields which may be used by the propagator. - */ - fields() { - return this._getGlobalPropagator().fields(); - } - /** Remove the global propagator */ - disable() { - (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); - } - _getGlobalPropagator() { - return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR; - } -} -exports.PropagationAPI = PropagationAPI; -//# sourceMappingURL=propagation.js.map - -/***/ }), - -/***/ 81539: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.TraceAPI = void 0; -const global_utils_1 = __nccwpck_require__(85135); -const ProxyTracerProvider_1 = __nccwpck_require__(2285); -const spancontext_utils_1 = __nccwpck_require__(49745); -const context_utils_1 = __nccwpck_require__(23326); -const diag_1 = __nccwpck_require__(11877); -const API_NAME = 'trace'; -/** - * Singleton object which represents the entry point to the OpenTelemetry Tracing API - */ -class TraceAPI { - /** Empty private constructor prevents end users from constructing a new instance of the API */ - constructor() { - this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); - this.wrapSpanContext = spancontext_utils_1.wrapSpanContext; - this.isSpanContextValid = spancontext_utils_1.isSpanContextValid; - this.deleteSpan = context_utils_1.deleteSpan; - this.getSpan = context_utils_1.getSpan; - this.getActiveSpan = context_utils_1.getActiveSpan; - this.getSpanContext = context_utils_1.getSpanContext; - this.setSpan = context_utils_1.setSpan; - this.setSpanContext = context_utils_1.setSpanContext; - } - /** Get the singleton instance of the Trace API */ - static getInstance() { - if (!this._instance) { - this._instance = new TraceAPI(); - } - return this._instance; - } - /** - * Set the current global tracer. - * - * @returns true if the tracer provider was successfully registered, else false - */ - setGlobalTracerProvider(provider) { - const success = (0, global_utils_1.registerGlobal)(API_NAME, this._proxyTracerProvider, diag_1.DiagAPI.instance()); - if (success) { - this._proxyTracerProvider.setDelegate(provider); - } - return success; - } - /** - * Returns the global tracer provider. - */ - getTracerProvider() { - return (0, global_utils_1.getGlobal)(API_NAME) || this._proxyTracerProvider; - } - /** - * Returns a tracer from the global tracer provider. - */ - getTracer(name, version) { - return this.getTracerProvider().getTracer(name, version); - } - /** Remove the global tracer provider */ - disable() { - (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); - this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); - } -} -exports.TraceAPI = TraceAPI; -//# sourceMappingURL=trace.js.map - -/***/ }), - -/***/ 37682: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.deleteBaggage = exports.setBaggage = exports.getActiveBaggage = exports.getBaggage = void 0; -const context_1 = __nccwpck_require__(57171); -const context_2 = __nccwpck_require__(78242); -/** - * Baggage key - */ -const BAGGAGE_KEY = (0, context_2.createContextKey)('OpenTelemetry Baggage Key'); -/** - * Retrieve the current baggage from the given context - * - * @param {Context} Context that manage all context values - * @returns {Baggage} Extracted baggage from the context - */ -function getBaggage(context) { - return context.getValue(BAGGAGE_KEY) || undefined; -} -exports.getBaggage = getBaggage; -/** - * Retrieve the current baggage from the active/current context - * - * @returns {Baggage} Extracted baggage from the context - */ -function getActiveBaggage() { - return getBaggage(context_1.ContextAPI.getInstance().active()); -} -exports.getActiveBaggage = getActiveBaggage; -/** - * Store a baggage in the given context - * - * @param {Context} Context that manage all context values - * @param {Baggage} baggage that will be set in the actual context - */ -function setBaggage(context, baggage) { - return context.setValue(BAGGAGE_KEY, baggage); -} -exports.setBaggage = setBaggage; -/** - * Delete the baggage stored in the given context - * - * @param {Context} Context that manage all context values - */ -function deleteBaggage(context) { - return context.deleteValue(BAGGAGE_KEY); -} -exports.deleteBaggage = deleteBaggage; -//# sourceMappingURL=context-helpers.js.map - -/***/ }), - -/***/ 84811: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.BaggageImpl = void 0; -class BaggageImpl { - constructor(entries) { - this._entries = entries ? new Map(entries) : new Map(); - } - getEntry(key) { - const entry = this._entries.get(key); - if (!entry) { - return undefined; - } - return Object.assign({}, entry); - } - getAllEntries() { - return Array.from(this._entries.entries()).map(([k, v]) => [k, v]); - } - setEntry(key, entry) { - const newBaggage = new BaggageImpl(this._entries); - newBaggage._entries.set(key, entry); - return newBaggage; - } - removeEntry(key) { - const newBaggage = new BaggageImpl(this._entries); - newBaggage._entries.delete(key); - return newBaggage; - } - removeEntries(...keys) { - const newBaggage = new BaggageImpl(this._entries); - for (const key of keys) { - newBaggage._entries.delete(key); - } - return newBaggage; - } - clear() { - return new BaggageImpl(); - } -} -exports.BaggageImpl = BaggageImpl; -//# sourceMappingURL=baggage-impl.js.map - -/***/ }), - -/***/ 23542: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.baggageEntryMetadataSymbol = void 0; -/** - * Symbol used to make BaggageEntryMetadata an opaque type - */ -exports.baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata'); -//# sourceMappingURL=symbol.js.map - -/***/ }), - -/***/ 28136: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.baggageEntryMetadataFromString = exports.createBaggage = void 0; -const diag_1 = __nccwpck_require__(11877); -const baggage_impl_1 = __nccwpck_require__(84811); -const symbol_1 = __nccwpck_require__(23542); -const diag = diag_1.DiagAPI.instance(); -/** - * Create a new Baggage with optional entries - * - * @param entries An array of baggage entries the new baggage should contain - */ -function createBaggage(entries = {}) { - return new baggage_impl_1.BaggageImpl(new Map(Object.entries(entries))); -} -exports.createBaggage = createBaggage; -/** - * Create a serializable BaggageEntryMetadata object from a string. - * - * @param str string metadata. Format is currently not defined by the spec and has no special meaning. - * - */ -function baggageEntryMetadataFromString(str) { - if (typeof str !== 'string') { - diag.error(`Cannot create baggage metadata from unknown type: ${typeof str}`); - str = ''; - } - return { - __TYPE__: symbol_1.baggageEntryMetadataSymbol, - toString() { - return str; - }, - }; -} -exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString; -//# sourceMappingURL=utils.js.map - -/***/ }), - -/***/ 7393: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.context = void 0; -// Split module-level variable definition into separate files to allow -// tree-shaking on each api instance. -const context_1 = __nccwpck_require__(57171); -/** Entrypoint for context API */ -exports.context = context_1.ContextAPI.getInstance(); -//# sourceMappingURL=context-api.js.map - -/***/ }), - -/***/ 54118: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.NoopContextManager = void 0; -const context_1 = __nccwpck_require__(78242); -class NoopContextManager { - active() { - return context_1.ROOT_CONTEXT; - } - with(_context, fn, thisArg, ...args) { - return fn.call(thisArg, ...args); - } - bind(_context, target) { - return target; - } - enable() { - return this; - } - disable() { - return this; - } -} -exports.NoopContextManager = NoopContextManager; -//# sourceMappingURL=NoopContextManager.js.map - -/***/ }), - -/***/ 78242: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.ROOT_CONTEXT = exports.createContextKey = void 0; -/** Get a key to uniquely identify a context value */ -function createContextKey(description) { - // The specification states that for the same input, multiple calls should - // return different keys. Due to the nature of the JS dependency management - // system, this creates problems where multiple versions of some package - // could hold different keys for the same property. - // - // Therefore, we use Symbol.for which returns the same key for the same input. - return Symbol.for(description); -} -exports.createContextKey = createContextKey; -class BaseContext { - /** - * Construct a new context which inherits values from an optional parent context. - * - * @param parentContext a context from which to inherit values - */ - constructor(parentContext) { - // for minification - const self = this; - self._currentContext = parentContext ? new Map(parentContext) : new Map(); - self.getValue = (key) => self._currentContext.get(key); - self.setValue = (key, value) => { - const context = new BaseContext(self._currentContext); - context._currentContext.set(key, value); - return context; - }; - self.deleteValue = (key) => { - const context = new BaseContext(self._currentContext); - context._currentContext.delete(key); - return context; - }; - } -} -/** The root context is used as the default parent context when there is no active context */ -exports.ROOT_CONTEXT = new BaseContext(); -//# sourceMappingURL=context.js.map - -/***/ }), - -/***/ 39721: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.diag = void 0; -// Split module-level variable definition into separate files to allow -// tree-shaking on each api instance. -const diag_1 = __nccwpck_require__(11877); -/** - * Entrypoint for Diag API. - * Defines Diagnostic handler used for internal diagnostic logging operations. - * The default provides a Noop DiagLogger implementation which may be changed via the - * diag.setLogger(logger: DiagLogger) function. - */ -exports.diag = diag_1.DiagAPI.instance(); -//# sourceMappingURL=diag-api.js.map - -/***/ }), - -/***/ 17978: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.DiagComponentLogger = void 0; -const global_utils_1 = __nccwpck_require__(85135); -/** - * Component Logger which is meant to be used as part of any component which - * will add automatically additional namespace in front of the log message. - * It will then forward all message to global diag logger - * @example - * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' }); - * cLogger.debug('test'); - * // @opentelemetry/instrumentation-http test - */ -class DiagComponentLogger { - constructor(props) { - this._namespace = props.namespace || 'DiagComponentLogger'; - } - debug(...args) { - return logProxy('debug', this._namespace, args); - } - error(...args) { - return logProxy('error', this._namespace, args); - } - info(...args) { - return logProxy('info', this._namespace, args); - } - warn(...args) { - return logProxy('warn', this._namespace, args); - } - verbose(...args) { - return logProxy('verbose', this._namespace, args); - } -} -exports.DiagComponentLogger = DiagComponentLogger; -function logProxy(funcName, namespace, args) { - const logger = (0, global_utils_1.getGlobal)('diag'); - // shortcut if logger not set - if (!logger) { - return; - } - args.unshift(namespace); - return logger[funcName](...args); -} -//# sourceMappingURL=ComponentLogger.js.map - -/***/ }), - -/***/ 3041: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.DiagConsoleLogger = void 0; -const consoleMap = [ - { n: 'error', c: 'error' }, - { n: 'warn', c: 'warn' }, - { n: 'info', c: 'info' }, - { n: 'debug', c: 'debug' }, - { n: 'verbose', c: 'trace' }, -]; -/** - * A simple Immutable Console based diagnostic logger which will output any messages to the Console. - * If you want to limit the amount of logging to a specific level or lower use the - * {@link createLogLevelDiagLogger} - */ -class DiagConsoleLogger { - constructor() { - function _consoleFunc(funcName) { - return function (...args) { - if (console) { - // Some environments only expose the console when the F12 developer console is open - // eslint-disable-next-line no-console - let theFunc = console[funcName]; - if (typeof theFunc !== 'function') { - // Not all environments support all functions - // eslint-disable-next-line no-console - theFunc = console.log; - } - // One last final check - if (typeof theFunc === 'function') { - return theFunc.apply(console, args); - } - } - }; - } - for (let i = 0; i < consoleMap.length; i++) { - this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c); - } - } -} -exports.DiagConsoleLogger = DiagConsoleLogger; -//# sourceMappingURL=consoleLogger.js.map - -/***/ }), - -/***/ 99639: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.createLogLevelDiagLogger = void 0; -const types_1 = __nccwpck_require__(78077); -function createLogLevelDiagLogger(maxLevel, logger) { - if (maxLevel < types_1.DiagLogLevel.NONE) { - maxLevel = types_1.DiagLogLevel.NONE; - } - else if (maxLevel > types_1.DiagLogLevel.ALL) { - maxLevel = types_1.DiagLogLevel.ALL; - } - // In case the logger is null or undefined - logger = logger || {}; - function _filterFunc(funcName, theLevel) { - const theFunc = logger[funcName]; - if (typeof theFunc === 'function' && maxLevel >= theLevel) { - return theFunc.bind(logger); - } - return function () { }; - } - return { - error: _filterFunc('error', types_1.DiagLogLevel.ERROR), - warn: _filterFunc('warn', types_1.DiagLogLevel.WARN), - info: _filterFunc('info', types_1.DiagLogLevel.INFO), - debug: _filterFunc('debug', types_1.DiagLogLevel.DEBUG), - verbose: _filterFunc('verbose', types_1.DiagLogLevel.VERBOSE), - }; -} -exports.createLogLevelDiagLogger = createLogLevelDiagLogger; -//# sourceMappingURL=logLevelLogger.js.map - -/***/ }), - -/***/ 78077: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.DiagLogLevel = void 0; -/** - * Defines the available internal logging levels for the diagnostic logger, the numeric values - * of the levels are defined to match the original values from the initial LogLevel to avoid - * compatibility/migration issues for any implementation that assume the numeric ordering. - */ -var DiagLogLevel; -(function (DiagLogLevel) { - /** Diagnostic Logging level setting to disable all logging (except and forced logs) */ - DiagLogLevel[DiagLogLevel["NONE"] = 0] = "NONE"; - /** Identifies an error scenario */ - DiagLogLevel[DiagLogLevel["ERROR"] = 30] = "ERROR"; - /** Identifies a warning scenario */ - DiagLogLevel[DiagLogLevel["WARN"] = 50] = "WARN"; - /** General informational log message */ - DiagLogLevel[DiagLogLevel["INFO"] = 60] = "INFO"; - /** General debug log message */ - DiagLogLevel[DiagLogLevel["DEBUG"] = 70] = "DEBUG"; - /** - * Detailed trace level logging should only be used for development, should only be set - * in a development environment. - */ - DiagLogLevel[DiagLogLevel["VERBOSE"] = 80] = "VERBOSE"; - /** Used to set the logging level to include all logging */ - DiagLogLevel[DiagLogLevel["ALL"] = 9999] = "ALL"; -})(DiagLogLevel = exports.DiagLogLevel || (exports.DiagLogLevel = {})); -//# sourceMappingURL=types.js.map - -/***/ }), - -/***/ 65163: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.trace = exports.propagation = exports.metrics = exports.diag = exports.context = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.createTraceState = exports.TraceFlags = exports.SpanStatusCode = exports.SpanKind = exports.SamplingDecision = exports.ProxyTracerProvider = exports.ProxyTracer = exports.defaultTextMapSetter = exports.defaultTextMapGetter = exports.ValueType = exports.createNoopMeter = exports.DiagLogLevel = exports.DiagConsoleLogger = exports.ROOT_CONTEXT = exports.createContextKey = exports.baggageEntryMetadataFromString = void 0; -var utils_1 = __nccwpck_require__(28136); -Object.defineProperty(exports, "baggageEntryMetadataFromString", ({ enumerable: true, get: function () { return utils_1.baggageEntryMetadataFromString; } })); -// Context APIs -var context_1 = __nccwpck_require__(78242); -Object.defineProperty(exports, "createContextKey", ({ enumerable: true, get: function () { return context_1.createContextKey; } })); -Object.defineProperty(exports, "ROOT_CONTEXT", ({ enumerable: true, get: function () { return context_1.ROOT_CONTEXT; } })); -// Diag APIs -var consoleLogger_1 = __nccwpck_require__(3041); -Object.defineProperty(exports, "DiagConsoleLogger", ({ enumerable: true, get: function () { return consoleLogger_1.DiagConsoleLogger; } })); -var types_1 = __nccwpck_require__(78077); -Object.defineProperty(exports, "DiagLogLevel", ({ enumerable: true, get: function () { return types_1.DiagLogLevel; } })); -// Metrics APIs -var NoopMeter_1 = __nccwpck_require__(4837); -Object.defineProperty(exports, "createNoopMeter", ({ enumerable: true, get: function () { return NoopMeter_1.createNoopMeter; } })); -var Metric_1 = __nccwpck_require__(89999); -Object.defineProperty(exports, "ValueType", ({ enumerable: true, get: function () { return Metric_1.ValueType; } })); -// Propagation APIs -var TextMapPropagator_1 = __nccwpck_require__(80865); -Object.defineProperty(exports, "defaultTextMapGetter", ({ enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapGetter; } })); -Object.defineProperty(exports, "defaultTextMapSetter", ({ enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapSetter; } })); -var ProxyTracer_1 = __nccwpck_require__(43503); -Object.defineProperty(exports, "ProxyTracer", ({ enumerable: true, get: function () { return ProxyTracer_1.ProxyTracer; } })); -var ProxyTracerProvider_1 = __nccwpck_require__(2285); -Object.defineProperty(exports, "ProxyTracerProvider", ({ enumerable: true, get: function () { return ProxyTracerProvider_1.ProxyTracerProvider; } })); -var SamplingResult_1 = __nccwpck_require__(33209); -Object.defineProperty(exports, "SamplingDecision", ({ enumerable: true, get: function () { return SamplingResult_1.SamplingDecision; } })); -var span_kind_1 = __nccwpck_require__(31424); -Object.defineProperty(exports, "SpanKind", ({ enumerable: true, get: function () { return span_kind_1.SpanKind; } })); -var status_1 = __nccwpck_require__(48845); -Object.defineProperty(exports, "SpanStatusCode", ({ enumerable: true, get: function () { return status_1.SpanStatusCode; } })); -var trace_flags_1 = __nccwpck_require__(26905); -Object.defineProperty(exports, "TraceFlags", ({ enumerable: true, get: function () { return trace_flags_1.TraceFlags; } })); -var utils_2 = __nccwpck_require__(32615); -Object.defineProperty(exports, "createTraceState", ({ enumerable: true, get: function () { return utils_2.createTraceState; } })); -var spancontext_utils_1 = __nccwpck_require__(49745); -Object.defineProperty(exports, "isSpanContextValid", ({ enumerable: true, get: function () { return spancontext_utils_1.isSpanContextValid; } })); -Object.defineProperty(exports, "isValidTraceId", ({ enumerable: true, get: function () { return spancontext_utils_1.isValidTraceId; } })); -Object.defineProperty(exports, "isValidSpanId", ({ enumerable: true, get: function () { return spancontext_utils_1.isValidSpanId; } })); -var invalid_span_constants_1 = __nccwpck_require__(91760); -Object.defineProperty(exports, "INVALID_SPANID", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPANID; } })); -Object.defineProperty(exports, "INVALID_TRACEID", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_TRACEID; } })); -Object.defineProperty(exports, "INVALID_SPAN_CONTEXT", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPAN_CONTEXT; } })); -// Split module-level variable definition into separate files to allow -// tree-shaking on each api instance. -const context_api_1 = __nccwpck_require__(7393); -Object.defineProperty(exports, "context", ({ enumerable: true, get: function () { return context_api_1.context; } })); -const diag_api_1 = __nccwpck_require__(39721); -Object.defineProperty(exports, "diag", ({ enumerable: true, get: function () { return diag_api_1.diag; } })); -const metrics_api_1 = __nccwpck_require__(72601); -Object.defineProperty(exports, "metrics", ({ enumerable: true, get: function () { return metrics_api_1.metrics; } })); -const propagation_api_1 = __nccwpck_require__(17591); -Object.defineProperty(exports, "propagation", ({ enumerable: true, get: function () { return propagation_api_1.propagation; } })); -const trace_api_1 = __nccwpck_require__(98989); -Object.defineProperty(exports, "trace", ({ enumerable: true, get: function () { return trace_api_1.trace; } })); -// Default export. -exports["default"] = { - context: context_api_1.context, - diag: diag_api_1.diag, - metrics: metrics_api_1.metrics, - propagation: propagation_api_1.propagation, - trace: trace_api_1.trace, -}; -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 85135: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.unregisterGlobal = exports.getGlobal = exports.registerGlobal = void 0; -const platform_1 = __nccwpck_require__(99957); -const version_1 = __nccwpck_require__(98996); -const semver_1 = __nccwpck_require__(81522); -const major = version_1.VERSION.split('.')[0]; -const GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`); -const _global = platform_1._globalThis; -function registerGlobal(type, instance, diag, allowOverride = false) { - var _a; - const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { - version: version_1.VERSION, - }); - if (!allowOverride && api[type]) { - // already registered an API of this type - const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`); - diag.error(err.stack || err.message); - return false; - } - if (api.version !== version_1.VERSION) { - // All registered APIs must be of the same version exactly - const err = new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${version_1.VERSION}`); - diag.error(err.stack || err.message); - return false; - } - api[type] = instance; - diag.debug(`@opentelemetry/api: Registered a global for ${type} v${version_1.VERSION}.`); - return true; -} -exports.registerGlobal = registerGlobal; -function getGlobal(type) { - var _a, _b; - const globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version; - if (!globalVersion || !(0, semver_1.isCompatible)(globalVersion)) { - return; - } - return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type]; -} -exports.getGlobal = getGlobal; -function unregisterGlobal(type, diag) { - diag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${version_1.VERSION}.`); - const api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; - if (api) { - delete api[type]; - } -} -exports.unregisterGlobal = unregisterGlobal; -//# sourceMappingURL=global-utils.js.map - -/***/ }), - -/***/ 81522: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.isCompatible = exports._makeCompatibilityCheck = void 0; -const version_1 = __nccwpck_require__(98996); -const re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; -/** - * Create a function to test an API version to see if it is compatible with the provided ownVersion. - * - * The returned function has the following semantics: - * - Exact match is always compatible - * - Major versions must match exactly - * - 1.x package cannot use global 2.x package - * - 2.x package cannot use global 1.x package - * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API - * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects - * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3 - * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor - * - Patch and build tag differences are not considered at this time - * - * @param ownVersion version which should be checked against - */ -function _makeCompatibilityCheck(ownVersion) { - const acceptedVersions = new Set([ownVersion]); - const rejectedVersions = new Set(); - const myVersionMatch = ownVersion.match(re); - if (!myVersionMatch) { - // we cannot guarantee compatibility so we always return noop - return () => false; - } - const ownVersionParsed = { - major: +myVersionMatch[1], - minor: +myVersionMatch[2], - patch: +myVersionMatch[3], - prerelease: myVersionMatch[4], - }; - // if ownVersion has a prerelease tag, versions must match exactly - if (ownVersionParsed.prerelease != null) { - return function isExactmatch(globalVersion) { - return globalVersion === ownVersion; - }; - } - function _reject(v) { - rejectedVersions.add(v); - return false; - } - function _accept(v) { - acceptedVersions.add(v); - return true; - } - return function isCompatible(globalVersion) { - if (acceptedVersions.has(globalVersion)) { - return true; - } - if (rejectedVersions.has(globalVersion)) { - return false; - } - const globalVersionMatch = globalVersion.match(re); - if (!globalVersionMatch) { - // cannot parse other version - // we cannot guarantee compatibility so we always noop - return _reject(globalVersion); - } - const globalVersionParsed = { - major: +globalVersionMatch[1], - minor: +globalVersionMatch[2], - patch: +globalVersionMatch[3], - prerelease: globalVersionMatch[4], - }; - // if globalVersion has a prerelease tag, versions must match exactly - if (globalVersionParsed.prerelease != null) { - return _reject(globalVersion); - } - // major versions must match - if (ownVersionParsed.major !== globalVersionParsed.major) { - return _reject(globalVersion); - } - if (ownVersionParsed.major === 0) { - if (ownVersionParsed.minor === globalVersionParsed.minor && - ownVersionParsed.patch <= globalVersionParsed.patch) { - return _accept(globalVersion); - } - return _reject(globalVersion); - } - if (ownVersionParsed.minor <= globalVersionParsed.minor) { - return _accept(globalVersion); - } - return _reject(globalVersion); - }; -} -exports._makeCompatibilityCheck = _makeCompatibilityCheck; -/** - * Test an API version to see if it is compatible with this API. - * - * - Exact match is always compatible - * - Major versions must match exactly - * - 1.x package cannot use global 2.x package - * - 2.x package cannot use global 1.x package - * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API - * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects - * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3 - * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor - * - Patch and build tag differences are not considered at this time - * - * @param version version of the API requesting an instance of the global API - */ -exports.isCompatible = _makeCompatibilityCheck(version_1.VERSION); -//# sourceMappingURL=semver.js.map - -/***/ }), - -/***/ 72601: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.metrics = void 0; -// Split module-level variable definition into separate files to allow -// tree-shaking on each api instance. -const metrics_1 = __nccwpck_require__(17696); -/** Entrypoint for metrics API */ -exports.metrics = metrics_1.MetricsAPI.getInstance(); -//# sourceMappingURL=metrics-api.js.map - -/***/ }), - -/***/ 89999: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.ValueType = void 0; -/** The Type of value. It describes how the data is reported. */ -var ValueType; -(function (ValueType) { - ValueType[ValueType["INT"] = 0] = "INT"; - ValueType[ValueType["DOUBLE"] = 1] = "DOUBLE"; -})(ValueType = exports.ValueType || (exports.ValueType = {})); -//# sourceMappingURL=Metric.js.map - -/***/ }), - -/***/ 4837: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.createNoopMeter = exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = exports.NOOP_OBSERVABLE_GAUGE_METRIC = exports.NOOP_OBSERVABLE_COUNTER_METRIC = exports.NOOP_UP_DOWN_COUNTER_METRIC = exports.NOOP_HISTOGRAM_METRIC = exports.NOOP_COUNTER_METRIC = exports.NOOP_METER = exports.NoopObservableUpDownCounterMetric = exports.NoopObservableGaugeMetric = exports.NoopObservableCounterMetric = exports.NoopObservableMetric = exports.NoopHistogramMetric = exports.NoopUpDownCounterMetric = exports.NoopCounterMetric = exports.NoopMetric = exports.NoopMeter = void 0; -/** - * NoopMeter is a noop implementation of the {@link Meter} interface. It reuses - * constant NoopMetrics for all of its methods. - */ -class NoopMeter { - constructor() { } - /** - * @see {@link Meter.createHistogram} - */ - createHistogram(_name, _options) { - return exports.NOOP_HISTOGRAM_METRIC; - } - /** - * @see {@link Meter.createCounter} - */ - createCounter(_name, _options) { - return exports.NOOP_COUNTER_METRIC; - } - /** - * @see {@link Meter.createUpDownCounter} - */ - createUpDownCounter(_name, _options) { - return exports.NOOP_UP_DOWN_COUNTER_METRIC; - } - /** - * @see {@link Meter.createObservableGauge} - */ - createObservableGauge(_name, _options) { - return exports.NOOP_OBSERVABLE_GAUGE_METRIC; - } - /** - * @see {@link Meter.createObservableCounter} - */ - createObservableCounter(_name, _options) { - return exports.NOOP_OBSERVABLE_COUNTER_METRIC; - } - /** - * @see {@link Meter.createObservableUpDownCounter} - */ - createObservableUpDownCounter(_name, _options) { - return exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC; - } - /** - * @see {@link Meter.addBatchObservableCallback} - */ - addBatchObservableCallback(_callback, _observables) { } - /** - * @see {@link Meter.removeBatchObservableCallback} - */ - removeBatchObservableCallback(_callback) { } -} -exports.NoopMeter = NoopMeter; -class NoopMetric { -} -exports.NoopMetric = NoopMetric; -class NoopCounterMetric extends NoopMetric { - add(_value, _attributes) { } -} -exports.NoopCounterMetric = NoopCounterMetric; -class NoopUpDownCounterMetric extends NoopMetric { - add(_value, _attributes) { } -} -exports.NoopUpDownCounterMetric = NoopUpDownCounterMetric; -class NoopHistogramMetric extends NoopMetric { - record(_value, _attributes) { } -} -exports.NoopHistogramMetric = NoopHistogramMetric; -class NoopObservableMetric { - addCallback(_callback) { } - removeCallback(_callback) { } -} -exports.NoopObservableMetric = NoopObservableMetric; -class NoopObservableCounterMetric extends NoopObservableMetric { -} -exports.NoopObservableCounterMetric = NoopObservableCounterMetric; -class NoopObservableGaugeMetric extends NoopObservableMetric { -} -exports.NoopObservableGaugeMetric = NoopObservableGaugeMetric; -class NoopObservableUpDownCounterMetric extends NoopObservableMetric { -} -exports.NoopObservableUpDownCounterMetric = NoopObservableUpDownCounterMetric; -exports.NOOP_METER = new NoopMeter(); -// Synchronous instruments -exports.NOOP_COUNTER_METRIC = new NoopCounterMetric(); -exports.NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric(); -exports.NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric(); -// Asynchronous instruments -exports.NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric(); -exports.NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric(); -exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric(); -/** - * Create a no-op Meter - */ -function createNoopMeter() { - return exports.NOOP_METER; -} -exports.createNoopMeter = createNoopMeter; -//# sourceMappingURL=NoopMeter.js.map - -/***/ }), - -/***/ 72647: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.NOOP_METER_PROVIDER = exports.NoopMeterProvider = void 0; -const NoopMeter_1 = __nccwpck_require__(4837); -/** - * An implementation of the {@link MeterProvider} which returns an impotent Meter - * for all calls to `getMeter` - */ -class NoopMeterProvider { - getMeter(_name, _version, _options) { - return NoopMeter_1.NOOP_METER; - } -} -exports.NoopMeterProvider = NoopMeterProvider; -exports.NOOP_METER_PROVIDER = new NoopMeterProvider(); -//# sourceMappingURL=NoopMeterProvider.js.map - -/***/ }), - -/***/ 99957: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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 __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (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 })); -__exportStar(__nccwpck_require__(87200), exports); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 89406: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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._globalThis = void 0; -/** only globals that common to node and browsers are allowed */ -// eslint-disable-next-line node/no-unsupported-features/es-builtins -exports._globalThis = typeof globalThis === 'object' ? globalThis : global; -//# sourceMappingURL=globalThis.js.map - -/***/ }), - -/***/ 87200: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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 __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (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 })); -__exportStar(__nccwpck_require__(89406), exports); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 17591: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.propagation = void 0; -// Split module-level variable definition into separate files to allow -// tree-shaking on each api instance. -const propagation_1 = __nccwpck_require__(89909); -/** Entrypoint for propagation API */ -exports.propagation = propagation_1.PropagationAPI.getInstance(); -//# sourceMappingURL=propagation-api.js.map - -/***/ }), - -/***/ 72368: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.NoopTextMapPropagator = void 0; -/** - * No-op implementations of {@link TextMapPropagator}. - */ -class NoopTextMapPropagator { - /** Noop inject function does nothing */ - inject(_context, _carrier) { } - /** Noop extract function does nothing and returns the input context */ - extract(context, _carrier) { - return context; - } - fields() { - return []; - } -} -exports.NoopTextMapPropagator = NoopTextMapPropagator; -//# sourceMappingURL=NoopTextMapPropagator.js.map - -/***/ }), - -/***/ 80865: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.defaultTextMapSetter = exports.defaultTextMapGetter = void 0; -exports.defaultTextMapGetter = { - get(carrier, key) { - if (carrier == null) { - return undefined; - } - return carrier[key]; - }, - keys(carrier) { - if (carrier == null) { - return []; - } - return Object.keys(carrier); - }, -}; -exports.defaultTextMapSetter = { - set(carrier, key, value) { - if (carrier == null) { - return; - } - carrier[key] = value; - }, -}; -//# sourceMappingURL=TextMapPropagator.js.map - -/***/ }), - -/***/ 98989: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.trace = void 0; -// Split module-level variable definition into separate files to allow -// tree-shaking on each api instance. -const trace_1 = __nccwpck_require__(81539); -/** Entrypoint for trace API */ -exports.trace = trace_1.TraceAPI.getInstance(); -//# sourceMappingURL=trace-api.js.map - -/***/ }), - -/***/ 81462: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.NonRecordingSpan = void 0; -const invalid_span_constants_1 = __nccwpck_require__(91760); -/** - * The NonRecordingSpan is the default {@link Span} that is used when no Span - * implementation is available. All operations are no-op including context - * propagation. - */ -class NonRecordingSpan { - constructor(_spanContext = invalid_span_constants_1.INVALID_SPAN_CONTEXT) { - this._spanContext = _spanContext; - } - // Returns a SpanContext. - spanContext() { - return this._spanContext; - } - // By default does nothing - setAttribute(_key, _value) { - return this; - } - // By default does nothing - setAttributes(_attributes) { - return this; - } - // By default does nothing - addEvent(_name, _attributes) { - return this; - } - // By default does nothing - setStatus(_status) { - return this; - } - // By default does nothing - updateName(_name) { - return this; - } - // By default does nothing - end(_endTime) { } - // isRecording always returns false for NonRecordingSpan. - isRecording() { - return false; - } - // By default does nothing - recordException(_exception, _time) { } -} -exports.NonRecordingSpan = NonRecordingSpan; -//# sourceMappingURL=NonRecordingSpan.js.map - -/***/ }), - -/***/ 17606: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.NoopTracer = void 0; -const context_1 = __nccwpck_require__(57171); -const context_utils_1 = __nccwpck_require__(23326); -const NonRecordingSpan_1 = __nccwpck_require__(81462); -const spancontext_utils_1 = __nccwpck_require__(49745); -const contextApi = context_1.ContextAPI.getInstance(); -/** - * No-op implementations of {@link Tracer}. - */ -class NoopTracer { - // startSpan starts a noop span. - startSpan(name, options, context = contextApi.active()) { - const root = Boolean(options === null || options === void 0 ? void 0 : options.root); - if (root) { - return new NonRecordingSpan_1.NonRecordingSpan(); - } - const parentFromContext = context && (0, context_utils_1.getSpanContext)(context); - if (isSpanContext(parentFromContext) && - (0, spancontext_utils_1.isSpanContextValid)(parentFromContext)) { - return new NonRecordingSpan_1.NonRecordingSpan(parentFromContext); - } - else { - return new NonRecordingSpan_1.NonRecordingSpan(); - } - } - startActiveSpan(name, arg2, arg3, arg4) { - let opts; - let ctx; - let fn; - if (arguments.length < 2) { - return; - } - else if (arguments.length === 2) { - fn = arg2; - } - else if (arguments.length === 3) { - opts = arg2; - fn = arg3; - } - else { - opts = arg2; - ctx = arg3; - fn = arg4; - } - const parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active(); - const span = this.startSpan(name, opts, parentContext); - const contextWithSpanSet = (0, context_utils_1.setSpan)(parentContext, span); - return contextApi.with(contextWithSpanSet, fn, undefined, span); - } -} -exports.NoopTracer = NoopTracer; -function isSpanContext(spanContext) { - return (typeof spanContext === 'object' && - typeof spanContext['spanId'] === 'string' && - typeof spanContext['traceId'] === 'string' && - typeof spanContext['traceFlags'] === 'number'); -} -//# sourceMappingURL=NoopTracer.js.map - -/***/ }), - -/***/ 23259: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.NoopTracerProvider = void 0; -const NoopTracer_1 = __nccwpck_require__(17606); -/** - * An implementation of the {@link TracerProvider} which returns an impotent - * Tracer for all calls to `getTracer`. - * - * All operations are no-op. - */ -class NoopTracerProvider { - getTracer(_name, _version, _options) { - return new NoopTracer_1.NoopTracer(); - } -} -exports.NoopTracerProvider = NoopTracerProvider; -//# sourceMappingURL=NoopTracerProvider.js.map - -/***/ }), - -/***/ 43503: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.ProxyTracer = void 0; -const NoopTracer_1 = __nccwpck_require__(17606); -const NOOP_TRACER = new NoopTracer_1.NoopTracer(); -/** - * Proxy tracer provided by the proxy tracer provider - */ -class ProxyTracer { - constructor(_provider, name, version, options) { - this._provider = _provider; - this.name = name; - this.version = version; - this.options = options; - } - startSpan(name, options, context) { - return this._getTracer().startSpan(name, options, context); - } - startActiveSpan(_name, _options, _context, _fn) { - const tracer = this._getTracer(); - return Reflect.apply(tracer.startActiveSpan, tracer, arguments); - } - /** - * Try to get a tracer from the proxy tracer provider. - * If the proxy tracer provider has no delegate, return a noop tracer. - */ - _getTracer() { - if (this._delegate) { - return this._delegate; - } - const tracer = this._provider.getDelegateTracer(this.name, this.version, this.options); - if (!tracer) { - return NOOP_TRACER; - } - this._delegate = tracer; - return this._delegate; - } -} -exports.ProxyTracer = ProxyTracer; -//# sourceMappingURL=ProxyTracer.js.map - -/***/ }), - -/***/ 2285: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.ProxyTracerProvider = void 0; -const ProxyTracer_1 = __nccwpck_require__(43503); -const NoopTracerProvider_1 = __nccwpck_require__(23259); -const NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider(); -/** - * Tracer provider which provides {@link ProxyTracer}s. - * - * Before a delegate is set, tracers provided are NoOp. - * When a delegate is set, traces are provided from the delegate. - * When a delegate is set after tracers have already been provided, - * all tracers already provided will use the provided delegate implementation. - */ -class ProxyTracerProvider { - /** - * Get a {@link ProxyTracer} - */ - getTracer(name, version, options) { - var _a; - return ((_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer_1.ProxyTracer(this, name, version, options)); - } - getDelegate() { - var _a; - return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER; - } - /** - * Set the delegate tracer provider - */ - setDelegate(delegate) { - this._delegate = delegate; - } - getDelegateTracer(name, version, options) { - var _a; - return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options); - } -} -exports.ProxyTracerProvider = ProxyTracerProvider; -//# sourceMappingURL=ProxyTracerProvider.js.map - -/***/ }), - -/***/ 33209: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.SamplingDecision = void 0; -/** - * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead. - * A sampling decision that determines how a {@link Span} will be recorded - * and collected. - */ -var SamplingDecision; -(function (SamplingDecision) { - /** - * `Span.isRecording() === false`, span will not be recorded and all events - * and attributes will be dropped. - */ - SamplingDecision[SamplingDecision["NOT_RECORD"] = 0] = "NOT_RECORD"; - /** - * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags} - * MUST NOT be set. - */ - SamplingDecision[SamplingDecision["RECORD"] = 1] = "RECORD"; - /** - * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags} - * MUST be set. - */ - SamplingDecision[SamplingDecision["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED"; -})(SamplingDecision = exports.SamplingDecision || (exports.SamplingDecision = {})); -//# sourceMappingURL=SamplingResult.js.map - -/***/ }), - -/***/ 23326: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.getSpanContext = exports.setSpanContext = exports.deleteSpan = exports.setSpan = exports.getActiveSpan = exports.getSpan = void 0; -const context_1 = __nccwpck_require__(78242); -const NonRecordingSpan_1 = __nccwpck_require__(81462); -const context_2 = __nccwpck_require__(57171); -/** - * span key - */ -const SPAN_KEY = (0, context_1.createContextKey)('OpenTelemetry Context Key SPAN'); -/** - * Return the span if one exists - * - * @param context context to get span from - */ -function getSpan(context) { - return context.getValue(SPAN_KEY) || undefined; -} -exports.getSpan = getSpan; -/** - * Gets the span from the current context, if one exists. - */ -function getActiveSpan() { - return getSpan(context_2.ContextAPI.getInstance().active()); -} -exports.getActiveSpan = getActiveSpan; -/** - * Set the span on a context - * - * @param context context to use as parent - * @param span span to set active - */ -function setSpan(context, span) { - return context.setValue(SPAN_KEY, span); -} -exports.setSpan = setSpan; -/** - * Remove current span stored in the context - * - * @param context context to delete span from - */ -function deleteSpan(context) { - return context.deleteValue(SPAN_KEY); -} -exports.deleteSpan = deleteSpan; -/** - * Wrap span context in a NoopSpan and set as span in a new - * context - * - * @param context context to set active span on - * @param spanContext span context to be wrapped - */ -function setSpanContext(context, spanContext) { - return setSpan(context, new NonRecordingSpan_1.NonRecordingSpan(spanContext)); -} -exports.setSpanContext = setSpanContext; -/** - * Get the span context of the span if it exists. - * - * @param context context to get values from - */ -function getSpanContext(context) { - var _a; - return (_a = getSpan(context)) === null || _a === void 0 ? void 0 : _a.spanContext(); -} -exports.getSpanContext = getSpanContext; -//# sourceMappingURL=context-utils.js.map - -/***/ }), - -/***/ 62110: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.TraceStateImpl = void 0; -const tracestate_validators_1 = __nccwpck_require__(54864); -const MAX_TRACE_STATE_ITEMS = 32; -const MAX_TRACE_STATE_LEN = 512; -const LIST_MEMBERS_SEPARATOR = ','; -const LIST_MEMBER_KEY_VALUE_SPLITTER = '='; -/** - * TraceState must be a class and not a simple object type because of the spec - * requirement (https://www.w3.org/TR/trace-context/#tracestate-field). - * - * Here is the list of allowed mutations: - * - New key-value pair should be added into the beginning of the list - * - The value of any key can be updated. Modified keys MUST be moved to the - * beginning of the list. - */ -class TraceStateImpl { - constructor(rawTraceState) { - this._internalState = new Map(); - if (rawTraceState) - this._parse(rawTraceState); - } - set(key, value) { - // TODO: Benchmark the different approaches(map vs list) and - // use the faster one. - const traceState = this._clone(); - if (traceState._internalState.has(key)) { - traceState._internalState.delete(key); - } - traceState._internalState.set(key, value); - return traceState; - } - unset(key) { - const traceState = this._clone(); - traceState._internalState.delete(key); - return traceState; - } - get(key) { - return this._internalState.get(key); - } - serialize() { - return this._keys() - .reduce((agg, key) => { - agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key)); - return agg; - }, []) - .join(LIST_MEMBERS_SEPARATOR); - } - _parse(rawTraceState) { - if (rawTraceState.length > MAX_TRACE_STATE_LEN) - return; - this._internalState = rawTraceState - .split(LIST_MEMBERS_SEPARATOR) - .reverse() // Store in reverse so new keys (.set(...)) will be placed at the beginning - .reduce((agg, part) => { - const listMember = part.trim(); // Optional Whitespace (OWS) handling - const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER); - if (i !== -1) { - const key = listMember.slice(0, i); - const value = listMember.slice(i + 1, part.length); - if ((0, tracestate_validators_1.validateKey)(key) && (0, tracestate_validators_1.validateValue)(value)) { - agg.set(key, value); - } - else { - // TODO: Consider to add warning log - } - } - return agg; - }, new Map()); - // Because of the reverse() requirement, trunc must be done after map is created - if (this._internalState.size > MAX_TRACE_STATE_ITEMS) { - this._internalState = new Map(Array.from(this._internalState.entries()) - .reverse() // Use reverse same as original tracestate parse chain - .slice(0, MAX_TRACE_STATE_ITEMS)); - } - } - _keys() { - return Array.from(this._internalState.keys()).reverse(); - } - _clone() { - const traceState = new TraceStateImpl(); - traceState._internalState = new Map(this._internalState); - return traceState; - } -} -exports.TraceStateImpl = TraceStateImpl; -//# sourceMappingURL=tracestate-impl.js.map - -/***/ }), - -/***/ 54864: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.validateValue = exports.validateKey = void 0; -const VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]'; -const VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`; -const VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`; -const VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`); -const VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/; -const INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/; -/** - * Key is opaque string up to 256 characters printable. It MUST begin with a - * lowercase letter, and can only contain lowercase letters a-z, digits 0-9, - * underscores _, dashes -, asterisks *, and forward slashes /. - * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the - * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key. - * see https://www.w3.org/TR/trace-context/#key - */ -function validateKey(key) { - return VALID_KEY_REGEX.test(key); -} -exports.validateKey = validateKey; -/** - * Value is opaque string up to 256 characters printable ASCII RFC0020 - * characters (i.e., the range 0x20 to 0x7E) except comma , and =. - */ -function validateValue(value) { - return (VALID_VALUE_BASE_REGEX.test(value) && - !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)); -} -exports.validateValue = validateValue; -//# sourceMappingURL=tracestate-validators.js.map - -/***/ }), - -/***/ 32615: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.createTraceState = void 0; -const tracestate_impl_1 = __nccwpck_require__(62110); -function createTraceState(rawTraceState) { - return new tracestate_impl_1.TraceStateImpl(rawTraceState); -} -exports.createTraceState = createTraceState; -//# sourceMappingURL=utils.js.map - -/***/ }), - -/***/ 91760: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = void 0; -const trace_flags_1 = __nccwpck_require__(26905); -exports.INVALID_SPANID = '0000000000000000'; -exports.INVALID_TRACEID = '00000000000000000000000000000000'; -exports.INVALID_SPAN_CONTEXT = { - traceId: exports.INVALID_TRACEID, - spanId: exports.INVALID_SPANID, - traceFlags: trace_flags_1.TraceFlags.NONE, -}; -//# sourceMappingURL=invalid-span-constants.js.map - -/***/ }), - -/***/ 31424: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SpanKind = void 0; -/* - * Copyright The OpenTelemetry 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 - * - * https://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 SpanKind; -(function (SpanKind) { - /** Default value. Indicates that the span is used internally. */ - SpanKind[SpanKind["INTERNAL"] = 0] = "INTERNAL"; - /** - * Indicates that the span covers server-side handling of an RPC or other - * remote request. - */ - SpanKind[SpanKind["SERVER"] = 1] = "SERVER"; - /** - * Indicates that the span covers the client-side wrapper around an RPC or - * other remote request. - */ - SpanKind[SpanKind["CLIENT"] = 2] = "CLIENT"; - /** - * Indicates that the span describes producer sending a message to a - * broker. Unlike client and server, there is no direct critical path latency - * relationship between producer and consumer spans. - */ - SpanKind[SpanKind["PRODUCER"] = 3] = "PRODUCER"; - /** - * Indicates that the span describes consumer receiving a message from a - * broker. Unlike client and server, there is no direct critical path latency - * relationship between producer and consumer spans. - */ - SpanKind[SpanKind["CONSUMER"] = 4] = "CONSUMER"; -})(SpanKind = exports.SpanKind || (exports.SpanKind = {})); -//# sourceMappingURL=span_kind.js.map - -/***/ }), - -/***/ 49745: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.wrapSpanContext = exports.isSpanContextValid = exports.isValidSpanId = exports.isValidTraceId = void 0; -/* - * Copyright The OpenTelemetry 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 - * - * https://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 invalid_span_constants_1 = __nccwpck_require__(91760); -const NonRecordingSpan_1 = __nccwpck_require__(81462); -const VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i; -const VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; -function isValidTraceId(traceId) { - return VALID_TRACEID_REGEX.test(traceId) && traceId !== invalid_span_constants_1.INVALID_TRACEID; -} -exports.isValidTraceId = isValidTraceId; -function isValidSpanId(spanId) { - return VALID_SPANID_REGEX.test(spanId) && spanId !== invalid_span_constants_1.INVALID_SPANID; -} -exports.isValidSpanId = isValidSpanId; -/** - * Returns true if this {@link SpanContext} is valid. - * @return true if this {@link SpanContext} is valid. - */ -function isSpanContextValid(spanContext) { - return (isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId)); -} -exports.isSpanContextValid = isSpanContextValid; -/** - * Wrap the given {@link SpanContext} in a new non-recording {@link Span} - * - * @param spanContext span context to be wrapped - * @returns a new non-recording {@link Span} with the provided context - */ -function wrapSpanContext(spanContext) { - return new NonRecordingSpan_1.NonRecordingSpan(spanContext); -} -exports.wrapSpanContext = wrapSpanContext; -//# sourceMappingURL=spancontext-utils.js.map - -/***/ }), - -/***/ 48845: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SpanStatusCode = void 0; -/** - * An enumeration of status codes. - */ -var SpanStatusCode; -(function (SpanStatusCode) { - /** - * The default status. - */ - SpanStatusCode[SpanStatusCode["UNSET"] = 0] = "UNSET"; - /** - * The operation has been validated by an Application developer or - * Operator to have completed successfully. - */ - SpanStatusCode[SpanStatusCode["OK"] = 1] = "OK"; - /** - * The operation contains an error. - */ - SpanStatusCode[SpanStatusCode["ERROR"] = 2] = "ERROR"; -})(SpanStatusCode = exports.SpanStatusCode || (exports.SpanStatusCode = {})); -//# sourceMappingURL=status.js.map - -/***/ }), - -/***/ 26905: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.TraceFlags = void 0; -/* - * Copyright The OpenTelemetry 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 - * - * https://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 TraceFlags; -(function (TraceFlags) { - /** Represents no flag set. */ - TraceFlags[TraceFlags["NONE"] = 0] = "NONE"; - /** Bit to represent whether trace is sampled in trace flags. */ - TraceFlags[TraceFlags["SAMPLED"] = 1] = "SAMPLED"; -})(TraceFlags = exports.TraceFlags || (exports.TraceFlags = {})); -//# sourceMappingURL=trace_flags.js.map - -/***/ }), - -/***/ 98996: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright The OpenTelemetry 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 - * - * https://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.VERSION = void 0; -// this is autogenerated file, see scripts/version-update.js -exports.VERSION = '1.4.1'; -//# sourceMappingURL=version.js.map - -/***/ }), - -/***/ 39436: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { define } = __nccwpck_require__(93998) -const base = __nccwpck_require__(33318) -const constants = __nccwpck_require__(90998) -const decoders = __nccwpck_require__(5017) -const encoders = __nccwpck_require__(2246) - -module.exports = { - base, - constants, - decoders, - define, - encoders -} - - -/***/ }), - -/***/ 93998: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { inherits } = __nccwpck_require__(73837) -const encoders = __nccwpck_require__(2246) -const decoders = __nccwpck_require__(5017) - -module.exports.define = function define (name, body) { - return new Entity(name, body) -} - -function Entity (name, body) { - this.name = name - this.body = body - - this.decoders = {} - this.encoders = {} -} - -Entity.prototype._createNamed = function createNamed (Base) { - const name = this.name - - function Generated (entity) { - this._initNamed(entity, name) - } - inherits(Generated, Base) - Generated.prototype._initNamed = function _initNamed (entity, name) { - Base.call(this, entity, name) - } - - return new Generated(this) -} - -Entity.prototype._getDecoder = function _getDecoder (enc) { - enc = enc || 'der' - // Lazily create decoder - if (!Object.prototype.hasOwnProperty.call(this.decoders, enc)) { this.decoders[enc] = this._createNamed(decoders[enc]) } - return this.decoders[enc] -} - -Entity.prototype.decode = function decode (data, enc, options) { - return this._getDecoder(enc).decode(data, options) -} - -Entity.prototype._getEncoder = function _getEncoder (enc) { - enc = enc || 'der' - // Lazily create encoder - if (!Object.prototype.hasOwnProperty.call(this.encoders, enc)) { this.encoders[enc] = this._createNamed(encoders[enc]) } - return this.encoders[enc] -} - -Entity.prototype.encode = function encode (data, enc, /* internal */ reporter) { - return this._getEncoder(enc).encode(data, reporter) -} - - -/***/ }), - -/***/ 28424: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { inherits } = __nccwpck_require__(73837) - -const { Reporter } = __nccwpck_require__(93026) - -function DecoderBuffer (base, options) { - Reporter.call(this, options) - if (!Buffer.isBuffer(base)) { - this.error('Input not Buffer') - return - } - - this.base = base - this.offset = 0 - this.length = base.length -} -inherits(DecoderBuffer, Reporter) - -DecoderBuffer.isDecoderBuffer = function isDecoderBuffer (data) { - if (data instanceof DecoderBuffer) { - return true - } - - // Or accept compatible API - const isCompatible = typeof data === 'object' && - Buffer.isBuffer(data.base) && - data.constructor.name === 'DecoderBuffer' && - typeof data.offset === 'number' && - typeof data.length === 'number' && - typeof data.save === 'function' && - typeof data.restore === 'function' && - typeof data.isEmpty === 'function' && - typeof data.readUInt8 === 'function' && - typeof data.skip === 'function' && - typeof data.raw === 'function' - - return isCompatible -} - -DecoderBuffer.prototype.save = function save () { - return { offset: this.offset, reporter: Reporter.prototype.save.call(this) } -} - -DecoderBuffer.prototype.restore = function restore (save) { - // Return skipped data - const res = new DecoderBuffer(this.base) - res.offset = save.offset - res.length = this.offset - - this.offset = save.offset - Reporter.prototype.restore.call(this, save.reporter) - - return res -} - -DecoderBuffer.prototype.isEmpty = function isEmpty () { - return this.offset === this.length -} - -DecoderBuffer.prototype.readUInt8 = function readUInt8 (fail) { - if (this.offset + 1 <= this.length) { return this.base.readUInt8(this.offset++, true) } else { return this.error(fail || 'DecoderBuffer overrun') } -} - -DecoderBuffer.prototype.skip = function skip (bytes, fail) { - if (!(this.offset + bytes <= this.length)) { return this.error(fail || 'DecoderBuffer overrun') } - - const res = new DecoderBuffer(this.base) - - // Share reporter state - res._reporterState = this._reporterState - - res.offset = this.offset - res.length = this.offset + bytes - this.offset += bytes - return res -} - -DecoderBuffer.prototype.raw = function raw (save) { - return this.base.slice(save ? save.offset : this.offset, this.length) -} - -function EncoderBuffer (value, reporter) { - if (Array.isArray(value)) { - this.length = 0 - this.value = value.map(function (item) { - if (!EncoderBuffer.isEncoderBuffer(item)) { item = new EncoderBuffer(item, reporter) } - this.length += item.length - return item - }, this) - } else if (typeof value === 'number') { - if (!(value >= 0 && value <= 0xff)) { return reporter.error('non-byte EncoderBuffer value') } - this.value = value - this.length = 1 - } else if (typeof value === 'string') { - this.value = value - this.length = Buffer.byteLength(value) - } else if (Buffer.isBuffer(value)) { - this.value = value - this.length = value.length - } else { - return reporter.error(`Unsupported type: ${typeof value}`) - } -} - -EncoderBuffer.isEncoderBuffer = function isEncoderBuffer (data) { - if (data instanceof EncoderBuffer) { - return true - } - - // Or accept compatible API - const isCompatible = typeof data === 'object' && - data.constructor.name === 'EncoderBuffer' && - typeof data.length === 'number' && - typeof data.join === 'function' - - return isCompatible -} - -EncoderBuffer.prototype.join = function join (out, offset) { - if (!out) { out = Buffer.alloc(this.length) } - if (!offset) { offset = 0 } - - if (this.length === 0) { return out } - - if (Array.isArray(this.value)) { - this.value.forEach(function (item) { - item.join(out, offset) - offset += item.length - }) - } else { - if (typeof this.value === 'number') { out[offset] = this.value } else if (typeof this.value === 'string') { out.write(this.value, offset) } else if (Buffer.isBuffer(this.value)) { this.value.copy(out, offset) } - offset += this.length - } - - return out -} - -module.exports = { - DecoderBuffer, - EncoderBuffer -} - - -/***/ }), - -/***/ 33318: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { Reporter } = __nccwpck_require__(93026) -const { DecoderBuffer, EncoderBuffer } = __nccwpck_require__(28424) -const Node = __nccwpck_require__(48674) - -module.exports = { - DecoderBuffer, - EncoderBuffer, - Node, - Reporter -} - - -/***/ }), - -/***/ 48674: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { strict: assert } = __nccwpck_require__(39491) - -const { Reporter } = __nccwpck_require__(93026) -const { DecoderBuffer, EncoderBuffer } = __nccwpck_require__(28424) - -// Supported tags -const tags = [ - 'seq', 'seqof', 'set', 'setof', 'objid', 'bool', - 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc', - 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str', - 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr' -] - -// Public methods list -const methods = [ - 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', - 'any', 'contains' -].concat(tags) - -// Overrided methods list -const overrided = [ - '_peekTag', '_decodeTag', '_use', - '_decodeStr', '_decodeObjid', '_decodeTime', - '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', - - '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', - '_encodeNull', '_encodeInt', '_encodeBool' -] - -function Node (enc, parent, name) { - const state = {} - this._baseState = state - - state.name = name - state.enc = enc - - state.parent = parent || null - state.children = null - - // State - state.tag = null - state.args = null - state.reverseArgs = null - state.choice = null - state.optional = false - state.any = false - state.obj = false - state.use = null - state.useDecoder = null - state.key = null - state.default = null - state.explicit = null - state.implicit = null - state.contains = null - - // Should create new instance on each method - if (!state.parent) { - state.children = [] - this._wrap() - } -} - -const stateProps = [ - 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', - 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', - 'implicit', 'contains' -] - -Node.prototype.clone = function clone () { - const state = this._baseState - const cstate = {} - stateProps.forEach(function (prop) { - cstate[prop] = state[prop] - }) - const res = new this.constructor(cstate.parent) - res._baseState = cstate - return res -} - -Node.prototype._wrap = function wrap () { - const state = this._baseState - methods.forEach(function (method) { - this[method] = function _wrappedMethod () { - const clone = new this.constructor(this) - state.children.push(clone) - return clone[method].apply(clone, arguments) - } - }, this) -} - -Node.prototype._init = function init (body) { - const state = this._baseState - - assert(state.parent === null) - body.call(this) - - // Filter children - state.children = state.children.filter(function (child) { - return child._baseState.parent === this - }, this) - assert.equal(state.children.length, 1, 'Root node can have only one child') -} - -Node.prototype._useArgs = function useArgs (args) { - const state = this._baseState - - // Filter children and args - const children = args.filter(function (arg) { - return arg instanceof this.constructor - }, this) - args = args.filter(function (arg) { - return !(arg instanceof this.constructor) - }, this) - - if (children.length !== 0) { - assert(state.children === null) - state.children = children - - // Replace parent to maintain backward link - children.forEach(function (child) { - child._baseState.parent = this - }, this) - } - if (args.length !== 0) { - assert(state.args === null) - state.args = args - state.reverseArgs = args.map(function (arg) { - if (typeof arg !== 'object' || arg.constructor !== Object) { return arg } - - const res = {} - Object.keys(arg).forEach(function (key) { - if (key == (key | 0)) { key |= 0 } // eslint-disable-line eqeqeq - const value = arg[key] - res[value] = key - }) - return res - }) - } -} - -// -// Overrided methods -// - -overrided.forEach(function (method) { - Node.prototype[method] = function _overrided () { - const state = this._baseState - throw new Error(`${method} not implemented for encoding: ${state.enc}`) - } -}) - -// -// Public methods -// - -tags.forEach(function (tag) { - Node.prototype[tag] = function _tagMethod () { - const state = this._baseState - const args = Array.prototype.slice.call(arguments) - - assert(state.tag === null) - state.tag = tag - - this._useArgs(args) - - return this - } -}) - -Node.prototype.use = function use (item) { - assert(item) - const state = this._baseState - - assert(state.use === null) - state.use = item - - return this -} - -Node.prototype.optional = function optional () { - const state = this._baseState - - state.optional = true - - return this -} - -Node.prototype.def = function def (val) { - const state = this._baseState - - assert(state.default === null) - state.default = val - state.optional = true - - return this -} - -Node.prototype.explicit = function explicit (num) { - const state = this._baseState - - assert(state.explicit === null && state.implicit === null) - state.explicit = num - - return this -} - -Node.prototype.implicit = function implicit (num) { - const state = this._baseState - - assert(state.explicit === null && state.implicit === null) - state.implicit = num - - return this -} - -Node.prototype.obj = function obj () { - const state = this._baseState - const args = Array.prototype.slice.call(arguments) - - state.obj = true - - if (args.length !== 0) { this._useArgs(args) } - - return this -} - -Node.prototype.key = function key (newKey) { - const state = this._baseState - - assert(state.key === null) - state.key = newKey - - return this -} - -Node.prototype.any = function any () { - const state = this._baseState - - state.any = true - - return this -} - -Node.prototype.choice = function choice (obj) { - const state = this._baseState - - assert(state.choice === null) - state.choice = obj - this._useArgs(Object.keys(obj).map(function (key) { - return obj[key] - })) - - return this -} - -Node.prototype.contains = function contains (item) { - const state = this._baseState - - assert(state.use === null) - state.contains = item - - return this -} - -// -// Decoding -// - -Node.prototype._decode = function decode (input, options) { - const state = this._baseState - - // Decode root node - if (state.parent === null) { return input.wrapResult(state.children[0]._decode(input, options)) } - - let result = state.default - let present = true - - let prevKey = null - if (state.key !== null) { prevKey = input.enterKey(state.key) } - - // Check if tag is there - if (state.optional) { - let tag = null - if (state.explicit !== null) { tag = state.explicit } else if (state.implicit !== null) { tag = state.implicit } else if (state.tag !== null) { tag = state.tag } - - if (tag === null && !state.any) { - // Trial and Error - const save = input.save() - try { - if (state.choice === null) { this._decodeGeneric(state.tag, input, options) } else { this._decodeChoice(input, options) } - present = true - } catch (e) { - present = false - } - input.restore(save) - } else { - present = this._peekTag(input, tag, state.any) - - if (input.isError(present)) { return present } - } - } - - // Push object on stack - let prevObj - if (state.obj && present) { prevObj = input.enterObject() } - - if (present) { - // Unwrap explicit values - if (state.explicit !== null) { - const explicit = this._decodeTag(input, state.explicit) - if (input.isError(explicit)) { return explicit } - input = explicit - } - - const start = input.offset - - // Unwrap implicit and normal values - if (state.use === null && state.choice === null) { - let save - if (state.any) { save = input.save() } - const body = this._decodeTag( - input, - state.implicit !== null ? state.implicit : state.tag, - state.any - ) - if (input.isError(body)) { return body } - - if (state.any) { result = input.raw(save) } else { input = body } - } - - if (options && options.track && state.tag !== null) { options.track(input.path(), start, input.length, 'tagged') } - - if (options && options.track && state.tag !== null) { options.track(input.path(), input.offset, input.length, 'content') } - - // Select proper method for tag - if (state.any) { - // no-op - } else if (state.choice === null) { - result = this._decodeGeneric(state.tag, input, options) - } else { - result = this._decodeChoice(input, options) - } - - if (input.isError(result)) { return result } - - // Decode children - if (!state.any && state.choice === null && state.children !== null) { - state.children.forEach(function decodeChildren (child) { - // NOTE: We are ignoring errors here, to let parser continue with other - // parts of encoded data - child._decode(input, options) - }) - } - - // Decode contained/encoded by schema, only in bit or octet strings - if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) { - const data = new DecoderBuffer(result) - result = this._getUse(state.contains, input._reporterState.obj) - ._decode(data, options) - } - } - - // Pop object - if (state.obj && present) { result = input.leaveObject(prevObj) } - - // Set key - if (state.key !== null && (result !== null || present === true)) { input.leaveKey(prevKey, state.key, result) } else if (prevKey !== null) { input.exitKey(prevKey) } - - return result -} - -Node.prototype._decodeGeneric = function decodeGeneric (tag, input, options) { - const state = this._baseState - - if (tag === 'seq' || tag === 'set') { return null } - if (tag === 'seqof' || tag === 'setof') { return this._decodeList(input, tag, state.args[0], options) } else if (/str$/.test(tag)) { return this._decodeStr(input, tag, options) } else if (tag === 'objid' && state.args) { return this._decodeObjid(input, state.args[0], state.args[1], options) } else if (tag === 'objid') { return this._decodeObjid(input, null, null, options) } else if (tag === 'gentime' || tag === 'utctime') { return this._decodeTime(input, tag, options) } else if (tag === 'null_') { return this._decodeNull(input, options) } else if (tag === 'bool') { return this._decodeBool(input, options) } else if (tag === 'objDesc') { return this._decodeStr(input, tag, options) } else if (tag === 'int' || tag === 'enum') { return this._decodeInt(input, state.args && state.args[0], options) } - - if (state.use !== null) { - return this._getUse(state.use, input._reporterState.obj) - ._decode(input, options) - } else { - return input.error(`unknown tag: ${tag}`) - } -} - -Node.prototype._getUse = function _getUse (entity, obj) { - const state = this._baseState - // Create altered use decoder if implicit is set - state.useDecoder = this._use(entity, obj) - assert(state.useDecoder._baseState.parent === null) - state.useDecoder = state.useDecoder._baseState.children[0] - if (state.implicit !== state.useDecoder._baseState.implicit) { - state.useDecoder = state.useDecoder.clone() - state.useDecoder._baseState.implicit = state.implicit - } - return state.useDecoder -} - -Node.prototype._decodeChoice = function decodeChoice (input, options) { - const state = this._baseState - let result = null - let match = false - - Object.keys(state.choice).some(function (key) { - const save = input.save() - const node = state.choice[key] - try { - const value = node._decode(input, options) - if (input.isError(value)) { return false } - - result = { type: key, value: value } - match = true - } catch (e) { - input.restore(save) - return false - } - return true - }, this) - - if (!match) { return input.error('Choice not matched') } - - return result -} - -// -// Encoding -// - -Node.prototype._createEncoderBuffer = function createEncoderBuffer (data) { - return new EncoderBuffer(data, this.reporter) -} - -Node.prototype._encode = function encode (data, reporter, parent) { - const state = this._baseState - if (state.default !== null && state.default === data) { return } - - const result = this._encodeValue(data, reporter, parent) - if (result === undefined) { return } - - if (this._skipDefault(result, reporter, parent)) { return } - - return result -} - -Node.prototype._encodeValue = function encode (data, reporter, parent) { - const state = this._baseState - - // Decode root node - if (state.parent === null) { return state.children[0]._encode(data, reporter || new Reporter()) } - - let result = null - - // Set reporter to share it with a child class - this.reporter = reporter - - // Check if data is there - if (state.optional && data === undefined) { - if (state.default !== null) { data = state.default } else { return } - } - - // Encode children first - let content = null - let primitive = false - if (state.any) { - // Anything that was given is translated to buffer - result = this._createEncoderBuffer(data) - } else if (state.choice) { - result = this._encodeChoice(data, reporter) - } else if (state.contains) { - content = this._getUse(state.contains, parent)._encode(data, reporter) - primitive = true - } else if (state.children) { - content = state.children.map(function (child) { - if (child._baseState.tag === 'null_') { return child._encode(null, reporter, data) } - - if (child._baseState.key === null) { return reporter.error('Child should have a key') } - const prevKey = reporter.enterKey(child._baseState.key) - - if (typeof data !== 'object') { return reporter.error('Child expected, but input is not object') } - - const res = child._encode(data[child._baseState.key], reporter, data) - reporter.leaveKey(prevKey) - - return res - }, this).filter(function (child) { - return child - }) - content = this._createEncoderBuffer(content) - } else { - if (state.tag === 'seqof' || state.tag === 'setof') { - if (!(state.args && state.args.length === 1)) { return reporter.error(`Too many args for: ${state.tag}`) } - - if (!Array.isArray(data)) { return reporter.error('seqof/setof, but data is not Array') } - - const child = this.clone() - child._baseState.implicit = null - content = this._createEncoderBuffer(data.map(function (item) { - const state = this._baseState - - return this._getUse(state.args[0], data)._encode(item, reporter) - }, child)) - } else if (state.use !== null) { - result = this._getUse(state.use, parent)._encode(data, reporter) - } else { - content = this._encodePrimitive(state.tag, data) - primitive = true - } - } - - // Encode data itself - if (!state.any && state.choice === null) { - const tag = state.implicit !== null ? state.implicit : state.tag - const cls = state.implicit === null ? 'universal' : 'context' - - if (tag === null) { - if (state.use === null) { reporter.error('Tag could be omitted only for .use()') } - } else { - if (state.use === null) { result = this._encodeComposite(tag, primitive, cls, content) } - } - } - - // Wrap in explicit - if (state.explicit !== null) { result = this._encodeComposite(state.explicit, false, 'context', result) } - - return result -} - -Node.prototype._encodeChoice = function encodeChoice (data, reporter) { - const state = this._baseState - - const node = state.choice[data.type] - if (!node) { - assert( - false, - `${data.type} not found in ${JSON.stringify(Object.keys(state.choice))}` - ) - } - return node._encode(data.value, reporter) -} - -Node.prototype._encodePrimitive = function encodePrimitive (tag, data) { - const state = this._baseState - - if (/str$/.test(tag)) { return this._encodeStr(data, tag) } else if (tag === 'objid' && state.args) { return this._encodeObjid(data, state.reverseArgs[0], state.args[1]) } else if (tag === 'objid') { return this._encodeObjid(data, null, null) } else if (tag === 'gentime' || tag === 'utctime') { return this._encodeTime(data, tag) } else if (tag === 'null_') { return this._encodeNull() } else if (tag === 'int' || tag === 'enum') { return this._encodeInt(data, state.args && state.reverseArgs[0]) } else if (tag === 'bool') { return this._encodeBool(data) } else if (tag === 'objDesc') { return this._encodeStr(data, tag) } else { throw new Error(`Unsupported tag: ${tag}`) } -} - -Node.prototype._isNumstr = function isNumstr (str) { - return /^[0-9 ]*$/.test(str) -} - -Node.prototype._isPrintstr = function isPrintstr (str) { - return /^[A-Za-z0-9 '()+,-./:=?]*$/.test(str) -} - -module.exports = Node - - -/***/ }), - -/***/ 93026: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -const { inherits } = __nccwpck_require__(73837) - -function Reporter (options) { - this._reporterState = { - obj: null, - path: [], - options: options || {}, - errors: [] - } -} - -Reporter.prototype.isError = function isError (obj) { - return obj instanceof ReporterError -} - -Reporter.prototype.save = function save () { - const state = this._reporterState - - return { obj: state.obj, pathLen: state.path.length } -} - -Reporter.prototype.restore = function restore (data) { - const state = this._reporterState - - state.obj = data.obj - state.path = state.path.slice(0, data.pathLen) -} - -Reporter.prototype.enterKey = function enterKey (key) { - return this._reporterState.path.push(key) -} - -Reporter.prototype.exitKey = function exitKey (index) { - const state = this._reporterState - - state.path = state.path.slice(0, index - 1) -} - -Reporter.prototype.leaveKey = function leaveKey (index, key, value) { - const state = this._reporterState - - this.exitKey(index) - if (state.obj !== null) { state.obj[key] = value } -} - -Reporter.prototype.path = function path () { - return this._reporterState.path.join('/') -} - -Reporter.prototype.enterObject = function enterObject () { - const state = this._reporterState - - const prev = state.obj - state.obj = {} - return prev -} - -Reporter.prototype.leaveObject = function leaveObject (prev) { - const state = this._reporterState - - const now = state.obj - state.obj = prev - return now -} - -Reporter.prototype.error = function error (msg) { - let err - const state = this._reporterState - - const inherited = msg instanceof ReporterError - if (inherited) { - err = msg - } else { - err = new ReporterError(state.path.map(function (elem) { - return `[${JSON.stringify(elem)}]` - }).join(''), msg.message || msg, msg.stack) - } - - if (!state.options.partial) { throw err } - - if (!inherited) { state.errors.push(err) } - - return err -} - -Reporter.prototype.wrapResult = function wrapResult (result) { - const state = this._reporterState - if (!state.options.partial) { return result } - - return { - result: this.isError(result) ? null : result, - errors: state.errors - } -} - -function ReporterError (path, msg) { - this.path = path - this.rethrow(msg) -} -inherits(ReporterError, Error) - -ReporterError.prototype.rethrow = function rethrow (msg) { - this.message = `${msg} at: ${this.path || '(shallow)'}` - if (Error.captureStackTrace) { Error.captureStackTrace(this, ReporterError) } - - if (!this.stack) { - try { - // IE only adds stack when thrown - throw new Error(this.message) - } catch (e) { - this.stack = e.stack - } - } - return this -} - -exports.Reporter = Reporter - - -/***/ }), - -/***/ 96018: -/***/ ((__unused_webpack_module, exports) => { - -// Helper -function reverse (map) { - const res = {} - - Object.keys(map).forEach(function (key) { - // Convert key to integer if it is stringified - if ((key | 0) == key) { key = key | 0 } // eslint-disable-line eqeqeq - - const value = map[key] - res[value] = key - }) - - return res -} - -exports.tagClass = { - 0: 'universal', - 1: 'application', - 2: 'context', - 3: 'private' -} -exports.tagClassByName = reverse(exports.tagClass) - -exports.tag = { - 0x00: 'end', - 0x01: 'bool', - 0x02: 'int', - 0x03: 'bitstr', - 0x04: 'octstr', - 0x05: 'null_', - 0x06: 'objid', - 0x07: 'objDesc', - 0x08: 'external', - 0x09: 'real', - 0x0a: 'enum', - 0x0b: 'embed', - 0x0c: 'utf8str', - 0x0d: 'relativeOid', - 0x10: 'seq', - 0x11: 'set', - 0x12: 'numstr', - 0x13: 'printstr', - 0x14: 't61str', - 0x15: 'videostr', - 0x16: 'ia5str', - 0x17: 'utctime', - 0x18: 'gentime', - 0x19: 'graphstr', - 0x1a: 'iso646str', - 0x1b: 'genstr', - 0x1c: 'unistr', - 0x1d: 'charstr', - 0x1e: 'bmpstr' -} -exports.tagByName = reverse(exports.tag) - - -/***/ }), - -/***/ 90998: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = { - der: __nccwpck_require__(96018) -} - - -/***/ }), - -/***/ 44798: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/* global BigInt */ -const { inherits } = __nccwpck_require__(73837) - -const { DecoderBuffer } = __nccwpck_require__(28424) -const Node = __nccwpck_require__(48674) - -// Import DER constants -const der = __nccwpck_require__(96018) - -function DERDecoder (entity) { - this.enc = 'der' - this.name = entity.name - this.entity = entity - - // Construct base tree - this.tree = new DERNode() - this.tree._init(entity.body) -} - -DERDecoder.prototype.decode = function decode (data, options) { - if (!DecoderBuffer.isDecoderBuffer(data)) { - data = new DecoderBuffer(data, options) - } - - return this.tree._decode(data, options) -} - -// Tree methods - -function DERNode (parent) { - Node.call(this, 'der', parent) -} -inherits(DERNode, Node) - -DERNode.prototype._peekTag = function peekTag (buffer, tag, any) { - if (buffer.isEmpty()) { return false } - - const state = buffer.save() - const decodedTag = derDecodeTag(buffer, `Failed to peek tag: "${tag}"`) - if (buffer.isError(decodedTag)) { return decodedTag } - - buffer.restore(state) - - return decodedTag.tag === tag || decodedTag.tagStr === tag || (decodedTag.tagStr + 'of') === tag || any -} - -DERNode.prototype._decodeTag = function decodeTag (buffer, tag, any) { - const decodedTag = derDecodeTag(buffer, - `Failed to decode tag of "${tag}"`) - if (buffer.isError(decodedTag)) { return decodedTag } - - let len = derDecodeLen(buffer, - decodedTag.primitive, - `Failed to get length of "${tag}"`) - - // Failure - if (buffer.isError(len)) { return len } - - if (!any && - decodedTag.tag !== tag && - decodedTag.tagStr !== tag && - decodedTag.tagStr + 'of' !== tag) { - return buffer.error(`Failed to match tag: "${tag}"`) - } - - if (decodedTag.primitive || len !== null) { return buffer.skip(len, `Failed to match body of: "${tag}"`) } - - // Indefinite length... find END tag - const state = buffer.save() - const res = this._skipUntilEnd( - buffer, - `Failed to skip indefinite length body: "${this.tag}"`) - if (buffer.isError(res)) { return res } - - len = buffer.offset - state.offset - buffer.restore(state) - return buffer.skip(len, `Failed to match body of: "${tag}"`) -} - -DERNode.prototype._skipUntilEnd = function skipUntilEnd (buffer, fail) { - for (;;) { - const tag = derDecodeTag(buffer, fail) - if (buffer.isError(tag)) { return tag } - const len = derDecodeLen(buffer, tag.primitive, fail) - if (buffer.isError(len)) { return len } - - let res - if (tag.primitive || len !== null) { res = buffer.skip(len) } else { res = this._skipUntilEnd(buffer, fail) } - - // Failure - if (buffer.isError(res)) { return res } - - if (tag.tagStr === 'end') { break } - } -} - -DERNode.prototype._decodeList = function decodeList (buffer, tag, decoder, - options) { - const result = [] - while (!buffer.isEmpty()) { - const possibleEnd = this._peekTag(buffer, 'end') - if (buffer.isError(possibleEnd)) { return possibleEnd } - - const res = decoder.decode(buffer, 'der', options) - if (buffer.isError(res) && possibleEnd) { break } - result.push(res) - } - return result -} - -DERNode.prototype._decodeStr = function decodeStr (buffer, tag) { - if (tag === 'bitstr') { - const unused = buffer.readUInt8() - if (buffer.isError(unused)) { return unused } - return { unused: unused, data: buffer.raw() } - } else if (tag === 'bmpstr') { - const raw = buffer.raw() - if (raw.length % 2 === 1) { return buffer.error('Decoding of string type: bmpstr length mismatch') } - - let str = '' - for (let i = 0; i < raw.length / 2; i++) { - str += String.fromCharCode(raw.readUInt16BE(i * 2)) - } - return str - } else if (tag === 'numstr') { - const numstr = buffer.raw().toString('ascii') - if (!this._isNumstr(numstr)) { - return buffer.error('Decoding of string type: numstr unsupported characters') - } - return numstr - } else if (tag === 'octstr') { - return buffer.raw() - } else if (tag === 'objDesc') { - return buffer.raw() - } else if (tag === 'printstr') { - const printstr = buffer.raw().toString('ascii') - if (!this._isPrintstr(printstr)) { - return buffer.error('Decoding of string type: printstr unsupported characters') - } - return printstr - } else if (/str$/.test(tag)) { - return buffer.raw().toString() - } else { - return buffer.error(`Decoding of string type: ${tag} unsupported`) - } -} +const REGION_ENV_NAME = "AWS_REGION"; +const REGION_INI_NAME = "region"; +const NODE_REGION_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => env[REGION_ENV_NAME], + configFileSelector: (profile) => profile[REGION_INI_NAME], + default: () => { + throw new Error("Region is missing"); + }, +}; +const NODE_REGION_CONFIG_FILE_OPTIONS = { + preferredFile: "credentials", +}; -DERNode.prototype._decodeObjid = function decodeObjid (buffer, values, relative) { - let result - const identifiers = [] - let ident = 0 - let subident = 0 - while (!buffer.isEmpty()) { - subident = buffer.readUInt8() - ident <<= 7 - ident |= subident & 0x7f - if ((subident & 0x80) === 0) { - identifiers.push(ident) - ident = 0 +const validRegions = new Set(); +const checkRegion = (region, check = utilEndpoints.isValidHostLabel) => { + if (!validRegions.has(region) && !check(region)) { + if (region === "*") { + console.warn(`@smithy/config-resolver WARN - Please use the caller region instead of "*". See "sigv4a" in https://github.com/aws/aws-sdk-js-v3/blob/main/supplemental-docs/CLIENTS.md.`); + } + else { + throw new Error(`Region not accepted: region="${region}" is not a valid hostname component.`); + } } - } - if (subident & 0x80) { identifiers.push(ident) } - - const first = (identifiers[0] / 40) | 0 - const second = identifiers[0] % 40 - - if (relative) { result = identifiers } else { result = [first, second].concat(identifiers.slice(1)) } - - if (values) { - let tmp = values[result.join(' ')] - if (tmp === undefined) { tmp = values[result.join('.')] } - if (tmp !== undefined) { result = tmp } - } - - return result -} - -DERNode.prototype._decodeTime = function decodeTime (buffer, tag) { - const str = buffer.raw().toString() - - let year - let mon - let day - let hour - let min - let sec - if (tag === 'gentime') { - year = str.slice(0, 4) | 0 - mon = str.slice(4, 6) | 0 - day = str.slice(6, 8) | 0 - hour = str.slice(8, 10) | 0 - min = str.slice(10, 12) | 0 - sec = str.slice(12, 14) | 0 - } else if (tag === 'utctime') { - year = str.slice(0, 2) | 0 - mon = str.slice(2, 4) | 0 - day = str.slice(4, 6) | 0 - hour = str.slice(6, 8) | 0 - min = str.slice(8, 10) | 0 - sec = str.slice(10, 12) | 0 - if (year < 70) { year = 2000 + year } else { year = 1900 + year } - } else { - return buffer.error(`Decoding ${tag} time is not supported yet`) - } - - return Date.UTC(year, mon - 1, day, hour, min, sec, 0) -} - -DERNode.prototype._decodeNull = function decodeNull () { - return null -} - -DERNode.prototype._decodeBool = function decodeBool (buffer) { - const res = buffer.readUInt8() - if (buffer.isError(res)) { return res } else { return res !== 0 } -} - -DERNode.prototype._decodeInt = function decodeInt (buffer, values) { - // Bigint, return as it is (assume big endian) - const raw = buffer.raw() - let res = BigInt(`0x${raw.toString('hex')}`) - - if (values) { - res = values[res.toString(10)] || res - } - - return res -} - -DERNode.prototype._use = function use (entity, obj) { - if (typeof entity === 'function') { entity = entity(obj) } - return entity._getDecoder('der').tree -} - -// Utility methods - -function derDecodeTag (buf, fail) { - let tag = buf.readUInt8(fail) - if (buf.isError(tag)) { return tag } - - const cls = der.tagClass[tag >> 6] - const primitive = (tag & 0x20) === 0 - - // Multi-octet tag - load - if ((tag & 0x1f) === 0x1f) { - let oct = tag - tag = 0 - while ((oct & 0x80) === 0x80) { - oct = buf.readUInt8(fail) - if (buf.isError(oct)) { return oct } - - tag <<= 7 - tag |= oct & 0x7f + else { + validRegions.add(region); } - } else { - tag &= 0x1f - } - const tagStr = der.tag[tag] - - return { - cls: cls, - primitive: primitive, - tag: tag, - tagStr: tagStr - } -} - -function derDecodeLen (buf, primitive, fail) { - let len = buf.readUInt8(fail) - if (buf.isError(len)) { return len } - - // Indefinite form - if (!primitive && len === 0x80) { return null } - - // Definite form - if ((len & 0x80) === 0) { - // Short form - return len - } - - // Long form - const num = len & 0x7f - if (num > 4) { return buf.error('length octect is too long') } - - len = 0 - for (let i = 0; i < num; i++) { - len <<= 8 - const j = buf.readUInt8(fail) - if (buf.isError(j)) { return j } - len |= j - } - - return len -} - -module.exports = DERDecoder - - -/***/ }), - -/***/ 5017: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = { - der: __nccwpck_require__(44798), - pem: __nccwpck_require__(33956) -} - - -/***/ }), - -/***/ 33956: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { inherits } = __nccwpck_require__(73837) - -const DERDecoder = __nccwpck_require__(44798) - -function PEMDecoder (entity) { - DERDecoder.call(this, entity) - this.enc = 'pem' -} -inherits(PEMDecoder, DERDecoder) - -PEMDecoder.prototype.decode = function decode (data, options) { - const lines = data.toString().split(/[\r\n]+/g) - - const label = options.label.toUpperCase() +}; - const re = /^-----(BEGIN|END) ([^-]+)-----$/ - let start = -1 - let end = -1 - for (let i = 0; i < lines.length; i++) { - const match = lines[i].match(re) - if (match === null) { continue } +const isFipsRegion = (region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")); - if (match[2] !== label) { continue } +const getRealRegion = (region) => isFipsRegion(region) + ? ["fips-aws-global", "aws-fips"].includes(region) + ? "us-east-1" + : region.replace(/fips-(dkr-|prod-)?|-fips/, "") + : region; - if (start === -1) { - if (match[1] !== 'BEGIN') { break } - start = i - } else { - if (match[1] !== 'END') { break } - end = i - break +const resolveRegionConfig = (input) => { + const { region, useFipsEndpoint } = input; + if (!region) { + throw new Error("Region is missing"); } - } - if (start === -1 || end === -1) { throw new Error(`PEM section not found for: ${label}`) } - - const base64 = lines.slice(start + 1, end).join('') - // Remove excessive symbols - base64.replace(/[^a-z0-9+/=]+/gi, '') - - const input = Buffer.from(base64, 'base64') - return DERDecoder.prototype.decode.call(this, input, options) -} - -module.exports = PEMDecoder - - -/***/ }), - -/***/ 20846: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/* global BigInt */ -const { inherits } = __nccwpck_require__(73837) - -const Node = __nccwpck_require__(48674) -const der = __nccwpck_require__(96018) - -function DEREncoder (entity) { - this.enc = 'der' - this.name = entity.name - this.entity = entity - - // Construct base tree - this.tree = new DERNode() - this.tree._init(entity.body) -} - -DEREncoder.prototype.encode = function encode (data, reporter) { - return this.tree._encode(data, reporter).join() -} - -// Tree methods - -function DERNode (parent) { - Node.call(this, 'der', parent) -} -inherits(DERNode, Node) - -DERNode.prototype._encodeComposite = function encodeComposite (tag, - primitive, - cls, - content) { - const encodedTag = encodeTag(tag, primitive, cls, this.reporter) - - // Short form - if (content.length < 0x80) { - const header = Buffer.alloc(2) - header[0] = encodedTag - header[1] = content.length - return this._createEncoderBuffer([header, content]) - } - - // Long form - // Count octets required to store length - let lenOctets = 1 - for (let i = content.length; i >= 0x100; i >>= 8) { lenOctets++ } + return Object.assign(input, { + region: async () => { + const providedRegion = typeof region === "function" ? await region() : region; + const realRegion = getRealRegion(providedRegion); + checkRegion(realRegion); + return realRegion; + }, + useFipsEndpoint: async () => { + const providedRegion = typeof region === "string" ? region : await region(); + if (isFipsRegion(providedRegion)) { + return true; + } + return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint(); + }, + }); +}; - const header = Buffer.alloc(1 + 1 + lenOctets) - header[0] = encodedTag - header[1] = 0x80 | lenOctets +const getHostnameFromVariants = (variants = [], { useFipsEndpoint, useDualstackEndpoint }) => variants.find(({ tags }) => useFipsEndpoint === tags.includes("fips") && useDualstackEndpoint === tags.includes("dualstack"))?.hostname; - for (let i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) { header[i] = j & 0xff } +const getResolvedHostname = (resolvedRegion, { regionHostname, partitionHostname }) => regionHostname + ? regionHostname + : partitionHostname + ? partitionHostname.replace("{region}", resolvedRegion) + : undefined; - return this._createEncoderBuffer([header, content]) -} +const getResolvedPartition = (region, { partitionHash }) => Object.keys(partitionHash || {}).find((key) => partitionHash[key].regions.includes(region)) ?? "aws"; -DERNode.prototype._encodeStr = function encodeStr (str, tag) { - if (tag === 'bitstr') { - return this._createEncoderBuffer([str.unused | 0, str.data]) - } else if (tag === 'bmpstr') { - const buf = Buffer.alloc(str.length * 2) - for (let i = 0; i < str.length; i++) { - buf.writeUInt16BE(str.charCodeAt(i), i * 2) - } - return this._createEncoderBuffer(buf) - } else if (tag === 'numstr') { - if (!this._isNumstr(str)) { - return this.reporter.error('Encoding of string type: numstr supports only digits and space') - } - return this._createEncoderBuffer(str) - } else if (tag === 'printstr') { - if (!this._isPrintstr(str)) { - return this.reporter.error('Encoding of string type: printstr supports only latin upper and lower case letters, digits, space, apostrophe, left and rigth parenthesis, plus sign, comma, hyphen, dot, slash, colon, equal sign, question mark') +const getResolvedSigningRegion = (hostname, { signingRegion, regionRegex, useFipsEndpoint }) => { + if (signingRegion) { + return signingRegion; } - return this._createEncoderBuffer(str) - } else if (/str$/.test(tag)) { - return this._createEncoderBuffer(str) - } else if (tag === 'objDesc') { - return this._createEncoderBuffer(str) - } else { - return this.reporter.error(`Encoding of string type: ${tag} unsupported`) - } -} - -DERNode.prototype._encodeObjid = function encodeObjid (id, values, relative) { - if (typeof id === 'string') { - if (!values) { return this.reporter.error('string objid given, but no values map found') } - if (!Object.prototype.hasOwnProperty.call(values, id)) { return this.reporter.error('objid not found in values map') } - id = values[id].split(/[\s.]+/g) - for (let i = 0; i < id.length; i++) { id[i] |= 0 } - } else if (Array.isArray(id)) { - id = id.slice() - for (let i = 0; i < id.length; i++) { id[i] |= 0 } - } - - if (!Array.isArray(id)) { - return this.reporter.error(`objid() should be either array or string, got: ${JSON.stringify(id)}`) - } - - if (!relative) { - if (id[1] >= 40) { return this.reporter.error('Second objid identifier OOB') } - id.splice(0, 2, id[0] * 40 + id[1]) - } - - // Count number of octets - let size = 0 - for (let i = 0; i < id.length; i++) { - let ident = id[i] - for (size++; ident >= 0x80; ident >>= 7) { size++ } - } - - const objid = Buffer.alloc(size) - let offset = objid.length - 1 - for (let i = id.length - 1; i >= 0; i--) { - let ident = id[i] - objid[offset--] = ident & 0x7f - while ((ident >>= 7) > 0) { objid[offset--] = 0x80 | (ident & 0x7f) } - } - - return this._createEncoderBuffer(objid) -} - -function two (num) { - if (num < 10) { return `0${num}` } else { return num } -} - -DERNode.prototype._encodeTime = function encodeTime (time, tag) { - let str - const date = new Date(time) - - if (tag === 'gentime') { - str = [ - two(date.getUTCFullYear()), - two(date.getUTCMonth() + 1), - two(date.getUTCDate()), - two(date.getUTCHours()), - two(date.getUTCMinutes()), - two(date.getUTCSeconds()), - 'Z' - ].join('') - } else if (tag === 'utctime') { - str = [ - two(date.getUTCFullYear() % 100), - two(date.getUTCMonth() + 1), - two(date.getUTCDate()), - two(date.getUTCHours()), - two(date.getUTCMinutes()), - two(date.getUTCSeconds()), - 'Z' - ].join('') - } else { - this.reporter.error(`Encoding ${tag} time is not supported yet`) - } - - return this._encodeStr(str, 'octstr') -} - -DERNode.prototype._encodeNull = function encodeNull () { - return this._createEncoderBuffer('') -} - -function bnToBuf (bn) { - var hex = BigInt(bn).toString(16) - if (hex.length % 2) { hex = '0' + hex } - - var len = hex.length / 2 - var u8 = new Uint8Array(len) - - var i = 0 - var j = 0 - while (i < len) { - u8[i] = parseInt(hex.slice(j, j + 2), 16) - i += 1 - j += 2 - } - - return u8 -} - -DERNode.prototype._encodeInt = function encodeInt (num, values) { - if (typeof num === 'string') { - if (!values) { return this.reporter.error('String int or enum given, but no values map') } - if (!Object.prototype.hasOwnProperty.call(values, num)) { - return this.reporter.error(`Values map doesn't contain: ${JSON.stringify(num)}`) + else if (useFipsEndpoint) { + const regionRegexJs = regionRegex.replace("\\\\", "\\").replace(/^\^/g, "\\.").replace(/\$$/g, "\\."); + const regionRegexmatchArray = hostname.match(regionRegexJs); + if (regionRegexmatchArray) { + return regionRegexmatchArray[0].slice(1, -1); + } } - num = values[num] - } +}; - if (typeof num === 'bigint') { - const numArray = [...bnToBuf(num)] - if (numArray[0] & 0x80) { - numArray.unshift(0) +const getRegionInfo = (region, { useFipsEndpoint = false, useDualstackEndpoint = false, signingService, regionHash, partitionHash, }) => { + const partition = getResolvedPartition(region, { partitionHash }); + const resolvedRegion = region in regionHash ? region : partitionHash[partition]?.endpoint ?? region; + const hostnameOptions = { useFipsEndpoint, useDualstackEndpoint }; + const regionHostname = getHostnameFromVariants(regionHash[resolvedRegion]?.variants, hostnameOptions); + const partitionHostname = getHostnameFromVariants(partitionHash[partition]?.variants, hostnameOptions); + const hostname = getResolvedHostname(resolvedRegion, { regionHostname, partitionHostname }); + if (hostname === undefined) { + throw new Error(`Endpoint resolution failed for: ${{ resolvedRegion, useFipsEndpoint, useDualstackEndpoint }}`); } - num = Buffer.from(numArray) - } - - if (Buffer.isBuffer(num)) { - let size = num.length - if (num.length === 0) { size++ } - - const out = Buffer.alloc(size) - num.copy(out) - if (num.length === 0) { out[0] = 0 } - return this._createEncoderBuffer(out) - } - - if (num < 0x80) { return this._createEncoderBuffer(num) } - - if (num < 0x100) { return this._createEncoderBuffer([0, num]) } - - let size = 1 - for (let i = num; i >= 0x100; i >>= 8) { size++ } - - const out = new Array(size) - for (let i = out.length - 1; i >= 0; i--) { - out[i] = num & 0xff - num >>= 8 - } - if (out[0] & 0x80) { - out.unshift(0) - } - - return this._createEncoderBuffer(Buffer.from(out)) -} - -DERNode.prototype._encodeBool = function encodeBool (value) { - return this._createEncoderBuffer(value ? 0xff : 0) -} - -DERNode.prototype._use = function use (entity, obj) { - if (typeof entity === 'function') { entity = entity(obj) } - return entity._getEncoder('der').tree -} - -DERNode.prototype._skipDefault = function skipDefault (dataBuffer, reporter, parent) { - const state = this._baseState - let i - if (state.default === null) { return false } - - const data = dataBuffer.join() - if (state.defaultBuffer === undefined) { state.defaultBuffer = this._encodeValue(state.default, reporter, parent).join() } - - if (data.length !== state.defaultBuffer.length) { return false } - - for (i = 0; i < data.length; i++) { - if (data[i] !== state.defaultBuffer[i]) { return false } - } - - return true -} - -// Utility methods - -function encodeTag (tag, primitive, cls, reporter) { - let res - - if (tag === 'seqof') { tag = 'seq' } else if (tag === 'setof') { tag = 'set' } - - if (Object.prototype.hasOwnProperty.call(der.tagByName, tag)) { res = der.tagByName[tag] } else if (typeof tag === 'number' && (tag | 0) === tag) { res = tag } else { return reporter.error(`Unknown tag: ${tag}`) } - - if (res >= 0x1f) { return reporter.error('Multi-octet tag encoding unsupported') } - - if (!primitive) { res |= 0x20 } - - res |= (der.tagClassByName[cls || 'universal'] << 6) - - return res -} - -module.exports = DEREncoder - - -/***/ }), - -/***/ 2246: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = { - der: __nccwpck_require__(20846), - pem: __nccwpck_require__(26217) -} - - -/***/ }), - -/***/ 26217: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { inherits } = __nccwpck_require__(73837) - -const DEREncoder = __nccwpck_require__(20846) - -function PEMEncoder (entity) { - DEREncoder.call(this, entity) - this.enc = 'pem' -} -inherits(PEMEncoder, DEREncoder) - -PEMEncoder.prototype.encode = function encode (data, options) { - const buf = DEREncoder.prototype.encode.call(this, data) - - const p = buf.toString('base64') - const out = [`-----BEGIN ${options.label}-----`] - for (let i = 0; i < p.length; i += 64) { out.push(p.slice(i, i + 64)) } - out.push(`-----END ${options.label}-----`) - return out.join('\n') -} - -module.exports = PEMEncoder - - -/***/ }), - -/***/ 29912: -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + const signingRegion = getResolvedSigningRegion(hostname, { + signingRegion: regionHash[resolvedRegion]?.signingRegion, + regionRegex: partitionHash[partition].regionRegex, + useFipsEndpoint, }); + return { + partition, + signingService, + hostname, + ...(signingRegion && { signingRegion }), + ...(regionHash[resolvedRegion]?.signingService && { + signingService: regionHash[resolvedRegion].signingService, + }), + }; }; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ClientStreamingCall = void 0; -/** - * A client streaming RPC call. This means that the clients sends 0, 1, or - * more messages to the server, and the server replies with exactly one - * message. - */ -class ClientStreamingCall { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.requests = request; - this.headers = headers; - this.response = response; - this.status = status; - this.trailers = trailers; - } - /** - * Instead of awaiting the response status and trailers, you can - * just as well await this call itself to receive the server outcome. - * Note that it may still be valid to send more request messages. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then(value => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, reason => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); - } - promiseFinished() { - return __awaiter(this, void 0, void 0, function* () { - let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - headers, - response, - status, - trailers - }; - }); - } -} -exports.ClientStreamingCall = ClientStreamingCall; + +exports.CONFIG_USE_DUALSTACK_ENDPOINT = CONFIG_USE_DUALSTACK_ENDPOINT; +exports.CONFIG_USE_FIPS_ENDPOINT = CONFIG_USE_FIPS_ENDPOINT; +exports.DEFAULT_USE_DUALSTACK_ENDPOINT = DEFAULT_USE_DUALSTACK_ENDPOINT; +exports.DEFAULT_USE_FIPS_ENDPOINT = DEFAULT_USE_FIPS_ENDPOINT; +exports.ENV_USE_DUALSTACK_ENDPOINT = ENV_USE_DUALSTACK_ENDPOINT; +exports.ENV_USE_FIPS_ENDPOINT = ENV_USE_FIPS_ENDPOINT; +exports.NODE_REGION_CONFIG_FILE_OPTIONS = NODE_REGION_CONFIG_FILE_OPTIONS; +exports.NODE_REGION_CONFIG_OPTIONS = NODE_REGION_CONFIG_OPTIONS; +exports.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS; +exports.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS; +exports.REGION_ENV_NAME = REGION_ENV_NAME; +exports.REGION_INI_NAME = REGION_INI_NAME; +exports.getRegionInfo = getRegionInfo; +exports.resolveCustomEndpointsConfig = resolveCustomEndpointsConfig; +exports.resolveEndpointsConfig = resolveEndpointsConfig; +exports.resolveRegionConfig = resolveRegionConfig; /***/ }), -/***/ 85702: +/***/ 51298: /***/ ((__unused_webpack_module, exports) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Deferred = exports.DeferredState = void 0; -var DeferredState; -(function (DeferredState) { - DeferredState[DeferredState["PENDING"] = 0] = "PENDING"; - DeferredState[DeferredState["REJECTED"] = 1] = "REJECTED"; - DeferredState[DeferredState["RESOLVED"] = 2] = "RESOLVED"; -})(DeferredState = exports.DeferredState || (exports.DeferredState = {})); -/** - * A deferred promise. This is a "controller" for a promise, which lets you - * pass a promise around and reject or resolve it from the outside. - * - * Warning: This class is to be used with care. Using it can make code very - * difficult to read. It is intended for use in library code that exposes - * promises, not for regular business logic. - */ -class Deferred { - /** - * @param preventUnhandledRejectionWarning - prevents the warning - * "Unhandled Promise rejection" by adding a noop rejection handler. - * Working with calls returned from the runtime-rpc package in an - * async function usually means awaiting one call property after - * the other. This means that the "status" is not being awaited when - * an earlier await for the "headers" is rejected. This causes the - * "unhandled promise reject" warning. A more correct behaviour for - * calls might be to become aware whether at least one of the - * promises is handled and swallow the rejection warning for the - * others. - */ - constructor(preventUnhandledRejectionWarning = true) { - this._state = DeferredState.PENDING; - this._promise = new Promise((resolve, reject) => { - this._resolve = resolve; - this._reject = reject; - }); - if (preventUnhandledRejectionWarning) { - this._promise.catch(_ => { }); - } - } - /** - * Get the current state of the promise. - */ - get state() { - return this._state; - } - /** - * Get the deferred promise. - */ - get promise() { - return this._promise; - } - /** - * Resolve the promise. Throws if the promise is already resolved or rejected. - */ - resolve(value) { - if (this.state !== DeferredState.PENDING) - throw new Error(`cannot resolve ${DeferredState[this.state].toLowerCase()}`); - this._resolve(value); - this._state = DeferredState.RESOLVED; - } - /** - * Reject the promise. Throws if the promise is already resolved or rejected. - */ - reject(reason) { - if (this.state !== DeferredState.PENDING) - throw new Error(`cannot reject ${DeferredState[this.state].toLowerCase()}`); - this._reject(reason); - this._state = DeferredState.REJECTED; - } - /** - * Resolve the promise. Ignore if not pending. - */ - resolvePending(val) { - if (this._state === DeferredState.PENDING) - this.resolve(val); - } - /** - * Reject the promise. Ignore if not pending. - */ - rejectPending(reason) { - if (this._state === DeferredState.PENDING) - this.reject(reason); - } -} -exports.Deferred = Deferred; - -/***/ }), +exports.HttpAuthLocation = void 0; +(function (HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; +})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); -/***/ 17042: -/***/ (function(__unused_webpack_module, exports) { +exports.HttpApiKeyAuthLocation = void 0; +(function (HttpApiKeyAuthLocation) { + HttpApiKeyAuthLocation["HEADER"] = "header"; + HttpApiKeyAuthLocation["QUERY"] = "query"; +})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); -"use strict"; +exports.EndpointURLScheme = void 0; +(function (EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; +})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DuplexStreamingCall = void 0; -/** - * A duplex streaming RPC call. This means that the clients sends an - * arbitrary amount of messages to the server, while at the same time, - * the server sends an arbitrary amount of messages to the client. - */ -class DuplexStreamingCall { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.requests = request; - this.headers = headers; - this.responses = response; - this.status = status; - this.trailers = trailers; - } - /** - * Instead of awaiting the response status and trailers, you can - * just as well await this call itself to receive the server outcome. - * Note that it may still be valid to send more request messages. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then(value => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, reason => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); - } - promiseFinished() { - return __awaiter(this, void 0, void 0, function* () { - let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - headers, - status, - trailers, - }; +exports.AlgorithmId = void 0; +(function (AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; +})(exports.AlgorithmId || (exports.AlgorithmId = {})); +const getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256, }); } -} -exports.DuplexStreamingCall = DuplexStreamingCall; - - -/***/ }), - -/***/ 60012: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -// Public API of the rpc runtime. -// Note: we do not use `export * from ...` to help tree shakers, -// webpack verbose output hints that this should be useful -Object.defineProperty(exports, "__esModule", ({ value: true })); -var service_type_1 = __nccwpck_require__(14107); -Object.defineProperty(exports, "ServiceType", ({ enumerable: true, get: function () { return service_type_1.ServiceType; } })); -var reflection_info_1 = __nccwpck_require__(44331); -Object.defineProperty(exports, "readMethodOptions", ({ enumerable: true, get: function () { return reflection_info_1.readMethodOptions; } })); -Object.defineProperty(exports, "readMethodOption", ({ enumerable: true, get: function () { return reflection_info_1.readMethodOption; } })); -Object.defineProperty(exports, "readServiceOption", ({ enumerable: true, get: function () { return reflection_info_1.readServiceOption; } })); -var rpc_error_1 = __nccwpck_require__(63159); -Object.defineProperty(exports, "RpcError", ({ enumerable: true, get: function () { return rpc_error_1.RpcError; } })); -var rpc_options_1 = __nccwpck_require__(67386); -Object.defineProperty(exports, "mergeRpcOptions", ({ enumerable: true, get: function () { return rpc_options_1.mergeRpcOptions; } })); -var rpc_output_stream_1 = __nccwpck_require__(76637); -Object.defineProperty(exports, "RpcOutputStreamController", ({ enumerable: true, get: function () { return rpc_output_stream_1.RpcOutputStreamController; } })); -var test_transport_1 = __nccwpck_require__(87008); -Object.defineProperty(exports, "TestTransport", ({ enumerable: true, get: function () { return test_transport_1.TestTransport; } })); -var deferred_1 = __nccwpck_require__(85702); -Object.defineProperty(exports, "Deferred", ({ enumerable: true, get: function () { return deferred_1.Deferred; } })); -Object.defineProperty(exports, "DeferredState", ({ enumerable: true, get: function () { return deferred_1.DeferredState; } })); -var duplex_streaming_call_1 = __nccwpck_require__(17042); -Object.defineProperty(exports, "DuplexStreamingCall", ({ enumerable: true, get: function () { return duplex_streaming_call_1.DuplexStreamingCall; } })); -var client_streaming_call_1 = __nccwpck_require__(29912); -Object.defineProperty(exports, "ClientStreamingCall", ({ enumerable: true, get: function () { return client_streaming_call_1.ClientStreamingCall; } })); -var server_streaming_call_1 = __nccwpck_require__(30066); -Object.defineProperty(exports, "ServerStreamingCall", ({ enumerable: true, get: function () { return server_streaming_call_1.ServerStreamingCall; } })); -var unary_call_1 = __nccwpck_require__(84175); -Object.defineProperty(exports, "UnaryCall", ({ enumerable: true, get: function () { return unary_call_1.UnaryCall; } })); -var rpc_interceptor_1 = __nccwpck_require__(51680); -Object.defineProperty(exports, "stackIntercept", ({ enumerable: true, get: function () { return rpc_interceptor_1.stackIntercept; } })); -Object.defineProperty(exports, "stackDuplexStreamingInterceptors", ({ enumerable: true, get: function () { return rpc_interceptor_1.stackDuplexStreamingInterceptors; } })); -Object.defineProperty(exports, "stackClientStreamingInterceptors", ({ enumerable: true, get: function () { return rpc_interceptor_1.stackClientStreamingInterceptors; } })); -Object.defineProperty(exports, "stackServerStreamingInterceptors", ({ enumerable: true, get: function () { return rpc_interceptor_1.stackServerStreamingInterceptors; } })); -Object.defineProperty(exports, "stackUnaryInterceptors", ({ enumerable: true, get: function () { return rpc_interceptor_1.stackUnaryInterceptors; } })); -var server_call_context_1 = __nccwpck_require__(25320); -Object.defineProperty(exports, "ServerCallContextController", ({ enumerable: true, get: function () { return server_call_context_1.ServerCallContextController; } })); - - -/***/ }), - -/***/ 44331: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.readServiceOption = exports.readMethodOption = exports.readMethodOptions = exports.normalizeMethodInfo = void 0; -const runtime_1 = __nccwpck_require__(37001); -/** - * Turns PartialMethodInfo into MethodInfo. - */ -function normalizeMethodInfo(method, service) { - var _a, _b, _c; - let m = method; - m.service = service; - m.localName = (_a = m.localName) !== null && _a !== void 0 ? _a : runtime_1.lowerCamelCase(m.name); - // noinspection PointlessBooleanExpressionJS - m.serverStreaming = !!m.serverStreaming; - // noinspection PointlessBooleanExpressionJS - m.clientStreaming = !!m.clientStreaming; - m.options = (_b = m.options) !== null && _b !== void 0 ? _b : {}; - m.idempotency = (_c = m.idempotency) !== null && _c !== void 0 ? _c : undefined; - return m; -} -exports.normalizeMethodInfo = normalizeMethodInfo; -/** - * Read custom method options from a generated service client. - * - * @deprecated use readMethodOption() - */ -function readMethodOptions(service, methodName, extensionName, extensionType) { - var _a; - const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; - return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : undefined; -} -exports.readMethodOptions = readMethodOptions; -function readMethodOption(service, methodName, extensionName, extensionType) { - var _a; - const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; - if (!options) { - return undefined; - } - const optionVal = options[extensionName]; - if (optionVal === undefined) { - return optionVal; - } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; -} -exports.readMethodOption = readMethodOption; -function readServiceOption(service, extensionName, extensionType) { - const options = service.options; - if (!options) { - return undefined; - } - const optionVal = options[extensionName]; - if (optionVal === undefined) { - return optionVal; + if (runtimeConfig.md5 != undefined) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5, + }); } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; -} -exports.readServiceOption = readServiceOption; + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + }, + }; +}; +const resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}; + +const getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}; +const resolveDefaultRuntimeConfig = (config) => { + return resolveChecksumRuntimeConfig(config); +}; + +exports.FieldPosition = void 0; +(function (FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; +})(exports.FieldPosition || (exports.FieldPosition = {})); + +const SMITHY_CONTEXT_KEY = "__smithy_context"; + +exports.IniSectionType = void 0; +(function (IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; +})(exports.IniSectionType || (exports.IniSectionType = {})); + +exports.RequestHandlerProtocol = void 0; +(function (RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; +})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); + +exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY; +exports.getDefaultClientConfiguration = getDefaultClientConfiguration; +exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig; /***/ }), -/***/ 63159: +/***/ 39840: /***/ ((__unused_webpack_module, exports) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.RpcError = void 0; -/** - * An error that occurred while calling a RPC method. - */ -class RpcError extends Error { - constructor(message, code = 'UNKNOWN', meta) { - super(message); - this.name = 'RpcError'; - // see https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#example - Object.setPrototypeOf(this, new.target.prototype); - this.code = code; - this.meta = meta !== null && meta !== void 0 ? meta : {}; - } - toString() { - const l = [this.name + ': ' + this.message]; - if (this.code) { - l.push(''); - l.push('Code: ' + this.code); - } - if (this.serviceName && this.methodName) { - l.push('Method: ' + this.serviceName + '/' + this.methodName); - } - let m = Object.entries(this.meta); - if (m.length) { - l.push(''); - l.push('Meta:'); - for (let [k, v] of m) { - l.push(` ${k}: ${v}`); - } - } - return l.join('\n'); + +const booleanSelector = (obj, key, type) => { + if (!(key in obj)) + return undefined; + if (obj[key] === "true") + return true; + if (obj[key] === "false") + return false; + throw new Error(`Cannot load ${type} "${key}". Expected "true" or "false", got ${obj[key]}.`); +}; + +const numberSelector = (obj, key, type) => { + if (!(key in obj)) + return undefined; + const numberValue = parseInt(obj[key], 10); + if (Number.isNaN(numberValue)) { + throw new TypeError(`Cannot load ${type} '${key}'. Expected number, got '${obj[key]}'.`); } -} -exports.RpcError = RpcError; + return numberValue; +}; + +exports.SelectorType = void 0; +(function (SelectorType) { + SelectorType["ENV"] = "env"; + SelectorType["CONFIG"] = "shared config entry"; +})(exports.SelectorType || (exports.SelectorType = {})); + +exports.booleanSelector = booleanSelector; +exports.numberSelector = numberSelector; /***/ }), -/***/ 51680: +/***/ 29446: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.stackDuplexStreamingInterceptors = exports.stackClientStreamingInterceptors = exports.stackServerStreamingInterceptors = exports.stackUnaryInterceptors = exports.stackIntercept = void 0; -const runtime_1 = __nccwpck_require__(37001); -/** - * Creates a "stack" of of all interceptors specified in the given `RpcOptions`. - * Used by generated client implementations. - * @internal - */ -function stackIntercept(kind, transport, method, options, input) { - var _a, _b, _c, _d; - if (kind == "unary") { - let tail = (mtd, inp, opt) => transport.unary(mtd, inp, opt); - for (const curr of ((_a = options.interceptors) !== null && _a !== void 0 ? _a : []).filter(i => i.interceptUnary).reverse()) { - const next = tail; - tail = (mtd, inp, opt) => curr.interceptUnary(next, mtd, inp, opt); + +var types = __nccwpck_require__(51298); + +class EndpointCache { + capacity; + data = new Map(); + parameters = []; + constructor({ size, params }) { + this.capacity = size ?? 50; + if (params) { + this.parameters = params; } - return tail(method, input, options); } - if (kind == "serverStreaming") { - let tail = (mtd, inp, opt) => transport.serverStreaming(mtd, inp, opt); - for (const curr of ((_b = options.interceptors) !== null && _b !== void 0 ? _b : []).filter(i => i.interceptServerStreaming).reverse()) { - const next = tail; - tail = (mtd, inp, opt) => curr.interceptServerStreaming(next, mtd, inp, opt); + get(endpointParams, resolver) { + const key = this.hash(endpointParams); + if (key === false) { + return resolver(); } - return tail(method, input, options); - } - if (kind == "clientStreaming") { - let tail = (mtd, opt) => transport.clientStreaming(mtd, opt); - for (const curr of ((_c = options.interceptors) !== null && _c !== void 0 ? _c : []).filter(i => i.interceptClientStreaming).reverse()) { - const next = tail; - tail = (mtd, opt) => curr.interceptClientStreaming(next, mtd, opt); + if (!this.data.has(key)) { + if (this.data.size > this.capacity + 10) { + const keys = this.data.keys(); + let i = 0; + while (true) { + const { value, done } = keys.next(); + this.data.delete(value); + if (done || ++i > 10) { + break; + } + } + } + this.data.set(key, resolver()); } - return tail(method, options); + return this.data.get(key); } - if (kind == "duplex") { - let tail = (mtd, opt) => transport.duplex(mtd, opt); - for (const curr of ((_d = options.interceptors) !== null && _d !== void 0 ? _d : []).filter(i => i.interceptDuplex).reverse()) { - const next = tail; - tail = (mtd, opt) => curr.interceptDuplex(next, mtd, opt); + size() { + return this.data.size; + } + hash(endpointParams) { + let buffer = ""; + const { parameters } = this; + if (parameters.length === 0) { + return false; } - return tail(method, options); + for (const param of parameters) { + const val = String(endpointParams[param] ?? ""); + if (val.includes("|;")) { + return false; + } + buffer += val + "|;"; + } + return buffer; } - runtime_1.assertNever(kind); -} -exports.stackIntercept = stackIntercept; -/** - * @deprecated replaced by `stackIntercept()`, still here to support older generated code - */ -function stackUnaryInterceptors(transport, method, input, options) { - return stackIntercept("unary", transport, method, options, input); -} -exports.stackUnaryInterceptors = stackUnaryInterceptors; -/** - * @deprecated replaced by `stackIntercept()`, still here to support older generated code - */ -function stackServerStreamingInterceptors(transport, method, input, options) { - return stackIntercept("serverStreaming", transport, method, options, input); -} -exports.stackServerStreamingInterceptors = stackServerStreamingInterceptors; -/** - * @deprecated replaced by `stackIntercept()`, still here to support older generated code - */ -function stackClientStreamingInterceptors(transport, method, options) { - return stackIntercept("clientStreaming", transport, method, options); -} -exports.stackClientStreamingInterceptors = stackClientStreamingInterceptors; -/** - * @deprecated replaced by `stackIntercept()`, still here to support older generated code - */ -function stackDuplexStreamingInterceptors(transport, method, options) { - return stackIntercept("duplex", transport, method, options); } -exports.stackDuplexStreamingInterceptors = stackDuplexStreamingInterceptors; +const IP_V4_REGEX = new RegExp(`^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$`); +const isIpAddress = (value) => IP_V4_REGEX.test(value) || (value.startsWith("[") && value.endsWith("]")); -/***/ }), +const VALID_HOST_LABEL_REGEX = new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`); +const isValidHostLabel = (value, allowSubDomains = false) => { + if (!allowSubDomains) { + return VALID_HOST_LABEL_REGEX.test(value); + } + const labels = value.split("."); + for (const label of labels) { + if (!isValidHostLabel(label)) { + return false; + } + } + return true; +}; -/***/ 67386: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +const customEndpointFunctions = {}; -"use strict"; +const debugId = "endpoints"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.mergeRpcOptions = void 0; -const runtime_1 = __nccwpck_require__(37001); -/** - * Merges custom RPC options with defaults. Returns a new instance and keeps - * the "defaults" and the "options" unmodified. - * - * Merges `RpcMetadata` "meta", overwriting values from "defaults" with - * values from "options". Does not append values to existing entries. - * - * Merges "jsonOptions", including "jsonOptions.typeRegistry", by creating - * a new array that contains types from "options.jsonOptions.typeRegistry" - * first, then types from "defaults.jsonOptions.typeRegistry". - * - * Merges "binaryOptions". - * - * Merges "interceptors" by creating a new array that contains interceptors - * from "defaults" first, then interceptors from "options". - * - * Works with objects that extend `RpcOptions`, but only if the added - * properties are of type Date, primitive like string, boolean, or Array - * of primitives. If you have other property types, you have to merge them - * yourself. - */ -function mergeRpcOptions(defaults, options) { - if (!options) - return defaults; - let o = {}; - copy(defaults, o); - copy(options, o); - for (let key of Object.keys(options)) { - let val = options[key]; - switch (key) { - case "jsonOptions": - o.jsonOptions = runtime_1.mergeJsonOptions(defaults.jsonOptions, o.jsonOptions); - break; - case "binaryOptions": - o.binaryOptions = runtime_1.mergeBinaryOptions(defaults.binaryOptions, o.binaryOptions); - break; - case "meta": - o.meta = {}; - copy(defaults.meta, o.meta); - copy(options.meta, o.meta); - break; - case "interceptors": - o.interceptors = defaults.interceptors ? defaults.interceptors.concat(val) : val.concat(); - break; - } +function toDebugString(input) { + if (typeof input !== "object" || input == null) { + return input; } - return o; + if ("ref" in input) { + return `$${toDebugString(input.ref)}`; + } + if ("fn" in input) { + return `${input.fn}(${(input.argv || []).map(toDebugString).join(", ")})`; + } + return JSON.stringify(input, null, 2); } -exports.mergeRpcOptions = mergeRpcOptions; -function copy(a, into) { - if (!a) - return; - let c = into; - for (let [k, v] of Object.entries(a)) { - if (v instanceof Date) - c[k] = new Date(v.getTime()); - else if (Array.isArray(v)) - c[k] = v.concat(); - else - c[k] = v; + +class EndpointError extends Error { + constructor(message) { + super(message); + this.name = "EndpointError"; } } +const booleanEquals = (value1, value2) => value1 === value2; -/***/ }), +const getAttrPathList = (path) => { + const parts = path.split("."); + const pathList = []; + for (const part of parts) { + const squareBracketIndex = part.indexOf("["); + if (squareBracketIndex !== -1) { + if (part.indexOf("]") !== part.length - 1) { + throw new EndpointError(`Path: '${path}' does not end with ']'`); + } + const arrayIndex = part.slice(squareBracketIndex + 1, -1); + if (Number.isNaN(parseInt(arrayIndex))) { + throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path}'`); + } + if (squareBracketIndex !== 0) { + pathList.push(part.slice(0, squareBracketIndex)); + } + pathList.push(arrayIndex); + } + else { + pathList.push(part); + } + } + return pathList; +}; -/***/ 76637: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +const getAttr = (value, path) => getAttrPathList(path).reduce((acc, index) => { + if (typeof acc !== "object") { + throw new EndpointError(`Index '${index}' in '${path}' not found in '${JSON.stringify(value)}'`); + } + else if (Array.isArray(acc)) { + return acc[parseInt(index)]; + } + return acc[index]; +}, value); -"use strict"; +const isSet = (value) => value != null; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.RpcOutputStreamController = void 0; -const deferred_1 = __nccwpck_require__(85702); -const runtime_1 = __nccwpck_require__(37001); -/** - * A `RpcOutputStream` that you control. - */ -class RpcOutputStreamController { - constructor() { - this._lis = { - nxt: [], - msg: [], - err: [], - cmp: [], - }; - this._closed = false; - } - // --- RpcOutputStream callback API - onNext(callback) { - return this.addLis(callback, this._lis.nxt); +const not = (value) => !value; + +const DEFAULT_PORTS = { + [types.EndpointURLScheme.HTTP]: 80, + [types.EndpointURLScheme.HTTPS]: 443, +}; +const parseURL = (value) => { + const whatwgURL = (() => { + try { + if (value instanceof URL) { + return value; + } + if (typeof value === "object" && "hostname" in value) { + const { hostname, port, protocol = "", path = "", query = {} } = value; + const url = new URL(`${protocol}//${hostname}${port ? `:${port}` : ""}${path}`); + url.search = Object.entries(query) + .map(([k, v]) => `${k}=${v}`) + .join("&"); + return url; + } + return new URL(value); + } + catch (error) { + return null; + } + })(); + if (!whatwgURL) { + console.error(`Unable to parse ${JSON.stringify(value)} as a whatwg URL.`); + return null; } - onMessage(callback) { - return this.addLis(callback, this._lis.msg); + const urlString = whatwgURL.href; + const { host, hostname, pathname, protocol, search } = whatwgURL; + if (search) { + return null; } - onError(callback) { - return this.addLis(callback, this._lis.err); + const scheme = protocol.slice(0, -1); + if (!Object.values(types.EndpointURLScheme).includes(scheme)) { + return null; } - onComplete(callback) { - return this.addLis(callback, this._lis.cmp); + const isIp = isIpAddress(hostname); + const inputContainsDefaultPort = urlString.includes(`${host}:${DEFAULT_PORTS[scheme]}`) || + (typeof value === "string" && value.includes(`${host}:${DEFAULT_PORTS[scheme]}`)); + const authority = `${host}${inputContainsDefaultPort ? `:${DEFAULT_PORTS[scheme]}` : ``}`; + return { + scheme, + authority, + path: pathname, + normalizedPath: pathname.endsWith("/") ? pathname : `${pathname}/`, + isIp, + }; +}; + +const stringEquals = (value1, value2) => value1 === value2; + +const substring = (input, start, stop, reverse) => { + if (start >= stop || input.length < stop || /[^\u0000-\u007f]/.test(input)) { + return null; } - addLis(callback, list) { - list.push(callback); - return () => { - let i = list.indexOf(callback); - if (i >= 0) - list.splice(i, 1); - }; + if (!reverse) { + return input.substring(start, stop); } - // remove all listeners - clearLis() { - for (let l of Object.values(this._lis)) - l.splice(0, l.length); + return input.substring(input.length - stop, input.length - start); +}; + +const uriEncode = (value) => encodeURIComponent(value).replace(/[!*'()]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`); + +const endpointFunctions = { + booleanEquals, + getAttr, + isSet, + isValidHostLabel, + not, + parseURL, + stringEquals, + substring, + uriEncode, +}; + +const evaluateTemplate = (template, options) => { + const evaluatedTemplateArr = []; + const templateContext = { + ...options.endpointParams, + ...options.referenceRecord, + }; + let currentIndex = 0; + while (currentIndex < template.length) { + const openingBraceIndex = template.indexOf("{", currentIndex); + if (openingBraceIndex === -1) { + evaluatedTemplateArr.push(template.slice(currentIndex)); + break; + } + evaluatedTemplateArr.push(template.slice(currentIndex, openingBraceIndex)); + const closingBraceIndex = template.indexOf("}", openingBraceIndex); + if (closingBraceIndex === -1) { + evaluatedTemplateArr.push(template.slice(openingBraceIndex)); + break; + } + if (template[openingBraceIndex + 1] === "{" && template[closingBraceIndex + 1] === "}") { + evaluatedTemplateArr.push(template.slice(openingBraceIndex + 1, closingBraceIndex)); + currentIndex = closingBraceIndex + 2; + } + const parameterName = template.substring(openingBraceIndex + 1, closingBraceIndex); + if (parameterName.includes("#")) { + const [refName, attrName] = parameterName.split("#"); + evaluatedTemplateArr.push(getAttr(templateContext[refName], attrName)); + } + else { + evaluatedTemplateArr.push(templateContext[parameterName]); + } + currentIndex = closingBraceIndex + 1; } - // --- Controller API - /** - * Is this stream already closed by a completion or error? - */ - get closed() { - return this._closed !== false; + return evaluatedTemplateArr.join(""); +}; + +const getReferenceValue = ({ ref }, options) => { + const referenceRecord = { + ...options.endpointParams, + ...options.referenceRecord, + }; + return referenceRecord[ref]; +}; + +const evaluateExpression = (obj, keyName, options) => { + if (typeof obj === "string") { + return evaluateTemplate(obj, options); } - /** - * Emit message, close with error, or close successfully, but only one - * at a time. - * Can be used to wrap a stream by using the other stream's `onNext`. - */ - notifyNext(message, error, complete) { - runtime_1.assert((message ? 1 : 0) + (error ? 1 : 0) + (complete ? 1 : 0) <= 1, 'only one emission at a time'); - if (message) - this.notifyMessage(message); - if (error) - this.notifyError(error); - if (complete) - this.notifyComplete(); + else if (obj["fn"]) { + return group$2.callFunction(obj, options); } - /** - * Emits a new message. Throws if stream is closed. - * - * Triggers onNext and onMessage callbacks. - */ - notifyMessage(message) { - runtime_1.assert(!this.closed, 'stream is closed'); - this.pushIt({ value: message, done: false }); - this._lis.msg.forEach(l => l(message)); - this._lis.nxt.forEach(l => l(message, undefined, false)); + else if (obj["ref"]) { + return getReferenceValue(obj, options); } - /** - * Closes the stream with an error. Throws if stream is closed. - * - * Triggers onNext and onError callbacks. - */ - notifyError(error) { - runtime_1.assert(!this.closed, 'stream is closed'); - this._closed = error; - this.pushIt(error); - this._lis.err.forEach(l => l(error)); - this._lis.nxt.forEach(l => l(undefined, error, false)); - this.clearLis(); + throw new EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`); +}; +const callFunction = ({ fn, argv }, options) => { + const evaluatedArgs = argv.map((arg) => ["boolean", "number"].includes(typeof arg) ? arg : group$2.evaluateExpression(arg, "arg", options)); + const fnSegments = fn.split("."); + if (fnSegments[0] in customEndpointFunctions && fnSegments[1] != null) { + return customEndpointFunctions[fnSegments[0]][fnSegments[1]](...evaluatedArgs); } - /** - * Closes the stream successfully. Throws if stream is closed. - * - * Triggers onNext and onComplete callbacks. - */ - notifyComplete() { - runtime_1.assert(!this.closed, 'stream is closed'); - this._closed = true; - this.pushIt({ value: null, done: true }); - this._lis.cmp.forEach(l => l()); - this._lis.nxt.forEach(l => l(undefined, undefined, true)); - this.clearLis(); + return endpointFunctions[fn](...evaluatedArgs); +}; +const group$2 = { + evaluateExpression, + callFunction, +}; + +const evaluateCondition = ({ assign, ...fnArgs }, options) => { + if (assign && assign in options.referenceRecord) { + throw new EndpointError(`'${assign}' is already defined in Reference Record.`); } - /** - * Creates an async iterator (that can be used with `for await {...}`) - * to consume the stream. - * - * Some things to note: - * - If an error occurs, the `for await` will throw it. - * - If an error occurred before the `for await` was started, `for await` - * will re-throw it. - * - If the stream is already complete, the `for await` will be empty. - * - If your `for await` consumes slower than the stream produces, - * for example because you are relaying messages in a slow operation, - * messages are queued. - */ - [Symbol.asyncIterator]() { - // init the iterator state, enabling pushIt() - if (!this._itState) { - this._itState = { q: [] }; - } - // if we are closed, we are definitely not receiving any more messages. - // but we can't let the iterator get stuck. we want to either: - // a) finish the new iterator immediately, because we are completed - // b) reject the new iterator, because we errored - if (this._closed === true) - this.pushIt({ value: null, done: true }); - else if (this._closed !== false) - this.pushIt(this._closed); - // the async iterator - return { - next: () => { - let state = this._itState; - runtime_1.assert(state, "bad state"); // if we don't have a state here, code is broken - // there should be no pending result. - // did the consumer call next() before we resolved our previous result promise? - runtime_1.assert(!state.p, "iterator contract broken"); - // did we produce faster than the iterator consumed? - // return the oldest result from the queue. - let first = state.q.shift(); - if (first) - return ("value" in first) ? Promise.resolve(first) : Promise.reject(first); - // we have no result ATM, but we promise one. - // as soon as we have a result, we must resolve promise. - state.p = new deferred_1.Deferred(); - return state.p.promise; + const value = callFunction(fnArgs, options); + options.logger?.debug?.(`${debugId} evaluateCondition: ${toDebugString(fnArgs)} = ${toDebugString(value)}`); + return { + result: value === "" ? true : !!value, + ...(assign != null && { toAssign: { name: assign, value } }), + }; +}; + +const evaluateConditions = (conditions = [], options) => { + const conditionsReferenceRecord = {}; + for (const condition of conditions) { + const { result, toAssign } = evaluateCondition(condition, { + ...options, + referenceRecord: { + ...options.referenceRecord, + ...conditionsReferenceRecord, }, - }; - } - // "push" a new iterator result. - // this either resolves a pending promise, or enqueues the result. - pushIt(result) { - let state = this._itState; - if (!state) - return; - // is the consumer waiting for us? - if (state.p) { - // yes, consumer is waiting for this promise. - const p = state.p; - runtime_1.assert(p.state == deferred_1.DeferredState.PENDING, "iterator contract broken"); - // resolve the promise - ("value" in result) ? p.resolve(result) : p.reject(result); - // must cleanup, otherwise iterator.next() would pick it up again. - delete state.p; + }); + if (!result) { + return { result }; } - else { - // we are producing faster than the iterator consumes. - // push result onto queue. - state.q.push(result); + if (toAssign) { + conditionsReferenceRecord[toAssign.name] = toAssign.value; + options.logger?.debug?.(`${debugId} assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`); } } -} -exports.RpcOutputStreamController = RpcOutputStreamController; + return { result: true, referenceRecord: conditionsReferenceRecord }; +}; +const getEndpointHeaders = (headers, options) => Object.entries(headers).reduce((acc, [headerKey, headerVal]) => ({ + ...acc, + [headerKey]: headerVal.map((headerValEntry) => { + const processedExpr = evaluateExpression(headerValEntry, "Header value entry", options); + if (typeof processedExpr !== "string") { + throw new EndpointError(`Header '${headerKey}' value '${processedExpr}' is not a string`); + } + return processedExpr; + }), +}), {}); -/***/ }), +const getEndpointProperties = (properties, options) => Object.entries(properties).reduce((acc, [propertyKey, propertyVal]) => ({ + ...acc, + [propertyKey]: group$1.getEndpointProperty(propertyVal, options), +}), {}); +const getEndpointProperty = (property, options) => { + if (Array.isArray(property)) { + return property.map((propertyEntry) => getEndpointProperty(propertyEntry, options)); + } + switch (typeof property) { + case "string": + return evaluateTemplate(property, options); + case "object": + if (property === null) { + throw new EndpointError(`Unexpected endpoint property: ${property}`); + } + return group$1.getEndpointProperties(property, options); + case "boolean": + return property; + default: + throw new EndpointError(`Unexpected endpoint property type: ${typeof property}`); + } +}; +const group$1 = { + getEndpointProperty, + getEndpointProperties, +}; -/***/ 25320: -/***/ ((__unused_webpack_module, exports) => { +const getEndpointUrl = (endpointUrl, options) => { + const expression = evaluateExpression(endpointUrl, "Endpoint URL", options); + if (typeof expression === "string") { + try { + return new URL(expression); + } + catch (error) { + console.error(`Failed to construct URL with ${expression}`, error); + throw error; + } + } + throw new EndpointError(`Endpoint URL must be a string, got ${typeof expression}`); +}; -"use strict"; +const evaluateEndpointRule = (endpointRule, options) => { + const { conditions, endpoint } = endpointRule; + const { result, referenceRecord } = evaluateConditions(conditions, options); + if (!result) { + return; + } + const endpointRuleOptions = { + ...options, + referenceRecord: { ...options.referenceRecord, ...referenceRecord }, + }; + const { url, properties, headers } = endpoint; + options.logger?.debug?.(`${debugId} Resolving endpoint from template: ${toDebugString(endpoint)}`); + return { + ...(headers != undefined && { + headers: getEndpointHeaders(headers, endpointRuleOptions), + }), + ...(properties != undefined && { + properties: getEndpointProperties(properties, endpointRuleOptions), + }), + url: getEndpointUrl(url, endpointRuleOptions), + }; +}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ServerCallContextController = void 0; -class ServerCallContextController { - constructor(method, headers, deadline, sendResponseHeadersFn, defaultStatus = { code: 'OK', detail: '' }) { - this._cancelled = false; - this._listeners = []; - this.method = method; - this.headers = headers; - this.deadline = deadline; - this.trailers = {}; - this._sendRH = sendResponseHeadersFn; - this.status = defaultStatus; +const evaluateErrorRule = (errorRule, options) => { + const { conditions, error } = errorRule; + const { result, referenceRecord } = evaluateConditions(conditions, options); + if (!result) { + return; } - /** - * Set the call cancelled. - * - * Invokes all callbacks registered with onCancel() and - * sets `cancelled = true`. - */ - notifyCancelled() { - if (!this._cancelled) { - this._cancelled = true; - for (let l of this._listeners) { - l(); + throw new EndpointError(evaluateExpression(error, "Error", { + ...options, + referenceRecord: { ...options.referenceRecord, ...referenceRecord }, + })); +}; + +const evaluateRules = (rules, options) => { + for (const rule of rules) { + if (rule.type === "endpoint") { + const endpointOrUndefined = evaluateEndpointRule(rule, options); + if (endpointOrUndefined) { + return endpointOrUndefined; + } + } + else if (rule.type === "error") { + evaluateErrorRule(rule, options); + } + else if (rule.type === "tree") { + const endpointOrUndefined = group.evaluateTreeRule(rule, options); + if (endpointOrUndefined) { + return endpointOrUndefined; } } + else { + throw new EndpointError(`Unknown endpoint rule: ${rule}`); + } } - /** - * Send response headers. - */ - sendResponseHeaders(data) { - this._sendRH(data); + throw new EndpointError(`Rules evaluation failed`); +}; +const evaluateTreeRule = (treeRule, options) => { + const { conditions, rules } = treeRule; + const { result, referenceRecord } = evaluateConditions(conditions, options); + if (!result) { + return; } - /** - * Is the call cancelled? - * - * When the client closes the connection before the server - * is done, the call is cancelled. - * - * If you want to cancel a request on the server, throw a - * RpcError with the CANCELLED status code. - */ - get cancelled() { - return this._cancelled; + return group.evaluateRules(rules, { + ...options, + referenceRecord: { ...options.referenceRecord, ...referenceRecord }, + }); +}; +const group = { + evaluateRules, + evaluateTreeRule, +}; + +const resolveEndpoint = (ruleSetObject, options) => { + const { endpointParams, logger } = options; + const { parameters, rules } = ruleSetObject; + options.logger?.debug?.(`${debugId} Initial EndpointParams: ${toDebugString(endpointParams)}`); + const paramsWithDefault = Object.entries(parameters) + .filter(([, v]) => v.default != null) + .map(([k, v]) => [k, v.default]); + if (paramsWithDefault.length > 0) { + for (const [paramKey, paramDefaultValue] of paramsWithDefault) { + endpointParams[paramKey] = endpointParams[paramKey] ?? paramDefaultValue; + } } - /** - * Add a callback for cancellation. - */ - onCancel(callback) { - const l = this._listeners; - l.push(callback); - return () => { - let i = l.indexOf(callback); - if (i >= 0) - l.splice(i, 1); - }; + const requiredParams = Object.entries(parameters) + .filter(([, v]) => v.required) + .map(([k]) => k); + for (const requiredParam of requiredParams) { + if (endpointParams[requiredParam] == null) { + throw new EndpointError(`Missing required parameter: '${requiredParam}'`); + } } -} -exports.ServerCallContextController = ServerCallContextController; + const endpoint = evaluateRules(rules, { endpointParams, logger, referenceRecord: {} }); + options.logger?.debug?.(`${debugId} Resolved endpoint: ${toDebugString(endpoint)}`); + return endpoint; +}; + +exports.EndpointCache = EndpointCache; +exports.EndpointError = EndpointError; +exports.customEndpointFunctions = customEndpointFunctions; +exports.isIpAddress = isIpAddress; +exports.isValidHostLabel = isValidHostLabel; +exports.resolveEndpoint = resolveEndpoint; /***/ }), -/***/ 30066: -/***/ (function(__unused_webpack_module, exports) { +/***/ 50308: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + +var types = __nccwpck_require__(51298); + +const getSmithyContext = (context) => context[types.SMITHY_CONTEXT_KEY] || (context[types.SMITHY_CONTEXT_KEY] = {}); + +const normalizeProvider = (input) => { + if (typeof input === "function") + return input; + const promisified = Promise.resolve(input); + return () => promisified; }; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ServerStreamingCall = void 0; -/** - * A server streaming RPC call. The client provides exactly one input message - * but the server may respond with 0, 1, or more messages. - */ -class ServerStreamingCall { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.request = request; - this.headers = headers; - this.responses = response; - this.status = status; - this.trailers = trailers; - } - /** - * Instead of awaiting the response status and trailers, you can - * just as well await this call itself to receive the server outcome. - * You should first setup some listeners to the `request` to - * see the actual messages the server replied with. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then(value => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, reason => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); - } - promiseFinished() { - return __awaiter(this, void 0, void 0, function* () { - let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - request: this.request, - headers, - status, - trailers, - }; - }); - } -} -exports.ServerStreamingCall = ServerStreamingCall; + +exports.getSmithyContext = getSmithyContext; +exports.normalizeProvider = normalizeProvider; /***/ }), -/***/ 14107: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 55829: +/***/ ((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 __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +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); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ServiceType = void 0; -const reflection_info_1 = __nccwpck_require__(44331); -class ServiceType { - constructor(typeName, methods, options) { - this.typeName = typeName; - this.methods = methods.map(i => reflection_info_1.normalizeMethodInfo(i, this)); - this.options = options !== null && options !== void 0 ? options : {}; - } +// src/index.ts +var src_exports = {}; +__export(src_exports, { + DefaultIdentityProviderConfig: () => DefaultIdentityProviderConfig, + EXPIRATION_MS: () => EXPIRATION_MS, + HttpApiKeyAuthSigner: () => HttpApiKeyAuthSigner, + HttpBearerAuthSigner: () => HttpBearerAuthSigner, + NoAuthSigner: () => NoAuthSigner, + createIsIdentityExpiredFunction: () => createIsIdentityExpiredFunction, + createPaginator: () => createPaginator, + doesIdentityRequireRefresh: () => doesIdentityRequireRefresh, + getHttpAuthSchemeEndpointRuleSetPlugin: () => getHttpAuthSchemeEndpointRuleSetPlugin, + getHttpAuthSchemePlugin: () => getHttpAuthSchemePlugin, + getHttpSigningPlugin: () => getHttpSigningPlugin, + getSmithyContext: () => getSmithyContext, + httpAuthSchemeEndpointRuleSetMiddlewareOptions: () => httpAuthSchemeEndpointRuleSetMiddlewareOptions, + httpAuthSchemeMiddleware: () => httpAuthSchemeMiddleware, + httpAuthSchemeMiddlewareOptions: () => httpAuthSchemeMiddlewareOptions, + httpSigningMiddleware: () => httpSigningMiddleware, + httpSigningMiddlewareOptions: () => httpSigningMiddlewareOptions, + isIdentityExpired: () => isIdentityExpired, + memoizeIdentityProvider: () => memoizeIdentityProvider, + normalizeProvider: () => normalizeProvider, + requestBuilder: () => import_protocols.requestBuilder, + setFeature: () => setFeature +}); +module.exports = __toCommonJS(src_exports); + +// src/getSmithyContext.ts +var import_types = __nccwpck_require__(55756); +var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); + +// src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts +var import_util_middleware = __nccwpck_require__(2390); +function convertHttpAuthSchemesToMap(httpAuthSchemes) { + const map = /* @__PURE__ */ new Map(); + for (const scheme of httpAuthSchemes) { + map.set(scheme.schemeId, scheme); + } + return map; } -exports.ServiceType = ServiceType; +__name(convertHttpAuthSchemesToMap, "convertHttpAuthSchemesToMap"); +var httpAuthSchemeMiddleware = /* @__PURE__ */ __name((config, mwOptions) => (next, context) => async (args) => { + const options = config.httpAuthSchemeProvider( + await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input) + ); + const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes); + const smithyContext = (0, import_util_middleware.getSmithyContext)(context); + const failureReasons = []; + for (const option of options) { + const scheme = authSchemes.get(option.schemeId); + if (!scheme) { + failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`); + continue; + } + const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config)); + if (!identityProvider) { + failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`); + continue; + } + const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context) || {}; + option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties); + option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties); + smithyContext.selectedHttpAuthScheme = { + httpAuthOption: option, + identity: await identityProvider(option.identityProperties), + signer: scheme.signer + }; + break; + } + if (!smithyContext.selectedHttpAuthScheme) { + throw new Error(failureReasons.join("\n")); + } + return next(args); +}, "httpAuthSchemeMiddleware"); +// src/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.ts +var httpAuthSchemeEndpointRuleSetMiddlewareOptions = { + step: "serialize", + tags: ["HTTP_AUTH_SCHEME"], + name: "httpAuthSchemeMiddleware", + override: true, + relation: "before", + toMiddleware: "endpointV2Middleware" +}; +var getHttpAuthSchemeEndpointRuleSetPlugin = /* @__PURE__ */ __name((config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider +}) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo( + httpAuthSchemeMiddleware(config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider + }), + httpAuthSchemeEndpointRuleSetMiddlewareOptions + ); + } +}), "getHttpAuthSchemeEndpointRuleSetPlugin"); -/***/ }), +// src/middleware-http-auth-scheme/getHttpAuthSchemePlugin.ts +var import_middleware_serde = __nccwpck_require__(81238); +var httpAuthSchemeMiddlewareOptions = { + step: "serialize", + tags: ["HTTP_AUTH_SCHEME"], + name: "httpAuthSchemeMiddleware", + override: true, + relation: "before", + toMiddleware: import_middleware_serde.serializerMiddlewareOption.name +}; +var getHttpAuthSchemePlugin = /* @__PURE__ */ __name((config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider +}) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo( + httpAuthSchemeMiddleware(config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider + }), + httpAuthSchemeMiddlewareOptions + ); + } +}), "getHttpAuthSchemePlugin"); -/***/ 87008: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +// src/middleware-http-signing/httpSigningMiddleware.ts +var import_protocol_http = __nccwpck_require__(64418); -"use strict"; +var defaultErrorHandler = /* @__PURE__ */ __name((signingProperties) => (error) => { + throw error; +}, "defaultErrorHandler"); +var defaultSuccessHandler = /* @__PURE__ */ __name((httpResponse, signingProperties) => { +}, "defaultSuccessHandler"); +var httpSigningMiddleware = /* @__PURE__ */ __name((config) => (next, context) => async (args) => { + if (!import_protocol_http.HttpRequest.isInstance(args.request)) { + return next(args); + } + const smithyContext = (0, import_util_middleware.getSmithyContext)(context); + const scheme = smithyContext.selectedHttpAuthScheme; + if (!scheme) { + throw new Error(`No HttpAuthScheme was selected: unable to sign request`); + } + const { + httpAuthOption: { signingProperties = {} }, + identity, + signer + } = scheme; + const output = await next({ + ...args, + request: await signer.sign(args.request, identity, signingProperties) + }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties)); + (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties); + return output; +}, "httpSigningMiddleware"); -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); +// src/middleware-http-signing/getHttpSigningMiddleware.ts +var httpSigningMiddlewareOptions = { + step: "finalizeRequest", + tags: ["HTTP_SIGNING"], + name: "httpSigningMiddleware", + aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"], + override: true, + relation: "after", + toMiddleware: "retryMiddleware" }; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.TestTransport = void 0; -const rpc_error_1 = __nccwpck_require__(63159); -const runtime_1 = __nccwpck_require__(37001); -const rpc_output_stream_1 = __nccwpck_require__(76637); -const rpc_options_1 = __nccwpck_require__(67386); -const unary_call_1 = __nccwpck_require__(84175); -const server_streaming_call_1 = __nccwpck_require__(30066); -const client_streaming_call_1 = __nccwpck_require__(29912); -const duplex_streaming_call_1 = __nccwpck_require__(17042); -/** - * Transport for testing. - */ -class TestTransport { - /** - * Initialize with mock data. Omitted fields have default value. - */ - constructor(data) { - /** - * Suppress warning / error about uncaught rejections of - * "status" and "trailers". - */ - this.suppressUncaughtRejections = true; - this.headerDelay = 10; - this.responseDelay = 50; - this.betweenResponseDelay = 10; - this.afterResponseDelay = 10; - this.data = data !== null && data !== void 0 ? data : {}; - } - /** - * Sent message(s) during the last operation. - */ - get sentMessages() { - if (this.lastInput instanceof TestInputStream) { - return this.lastInput.sent; - } - else if (typeof this.lastInput == "object") { - return [this.lastInput.single]; - } - return []; - } - /** - * Sending message(s) completed? - */ - get sendComplete() { - if (this.lastInput instanceof TestInputStream) { - return this.lastInput.completed; - } - else if (typeof this.lastInput == "object") { - return true; - } - return false; - } - // Creates a promise for response headers from the mock data. - promiseHeaders() { - var _a; - const headers = (_a = this.data.headers) !== null && _a !== void 0 ? _a : TestTransport.defaultHeaders; - return headers instanceof rpc_error_1.RpcError - ? Promise.reject(headers) - : Promise.resolve(headers); - } - // Creates a promise for a single, valid, message from the mock data. - promiseSingleResponse(method) { - if (this.data.response instanceof rpc_error_1.RpcError) { - return Promise.reject(this.data.response); - } - let r; - if (Array.isArray(this.data.response)) { - runtime_1.assert(this.data.response.length > 0); - r = this.data.response[0]; - } - else if (this.data.response !== undefined) { - r = this.data.response; - } - else { - r = method.O.create(); - } - runtime_1.assert(method.O.is(r)); - return Promise.resolve(r); - } - /** - * Pushes response messages from the mock data to the output stream. - * If an error response, status or trailers are mocked, the stream is - * closed with the respective error. - * Otherwise, stream is completed successfully. - * - * The returned promise resolves when the stream is closed. It should - * not reject. If it does, code is broken. - */ - streamResponses(method, stream, abort) { - return __awaiter(this, void 0, void 0, function* () { - // normalize "data.response" into an array of valid output messages - const messages = []; - if (this.data.response === undefined) { - messages.push(method.O.create()); - } - else if (Array.isArray(this.data.response)) { - for (let msg of this.data.response) { - runtime_1.assert(method.O.is(msg)); - messages.push(msg); - } - } - else if (!(this.data.response instanceof rpc_error_1.RpcError)) { - runtime_1.assert(method.O.is(this.data.response)); - messages.push(this.data.response); - } - // start the stream with an initial delay. - // if the request is cancelled, notify() error and exit. - try { - yield delay(this.responseDelay, abort)(undefined); - } - catch (error) { - stream.notifyError(error); - return; - } - // if error response was mocked, notify() error (stream is now closed with error) and exit. - if (this.data.response instanceof rpc_error_1.RpcError) { - stream.notifyError(this.data.response); - return; - } - // regular response messages were mocked. notify() them. - for (let msg of messages) { - stream.notifyMessage(msg); - // add a short delay between responses - // if the request is cancelled, notify() error and exit. - try { - yield delay(this.betweenResponseDelay, abort)(undefined); - } - catch (error) { - stream.notifyError(error); - return; - } - } - // error status was mocked, notify() error (stream is now closed with error) and exit. - if (this.data.status instanceof rpc_error_1.RpcError) { - stream.notifyError(this.data.status); - return; - } - // error trailers were mocked, notify() error (stream is now closed with error) and exit. - if (this.data.trailers instanceof rpc_error_1.RpcError) { - stream.notifyError(this.data.trailers); - return; - } - // stream completed successfully - stream.notifyComplete(); - }); - } - // Creates a promise for response status from the mock data. - promiseStatus() { - var _a; - const status = (_a = this.data.status) !== null && _a !== void 0 ? _a : TestTransport.defaultStatus; - return status instanceof rpc_error_1.RpcError - ? Promise.reject(status) - : Promise.resolve(status); - } - // Creates a promise for response trailers from the mock data. - promiseTrailers() { - var _a; - const trailers = (_a = this.data.trailers) !== null && _a !== void 0 ? _a : TestTransport.defaultTrailers; - return trailers instanceof rpc_error_1.RpcError - ? Promise.reject(trailers) - : Promise.resolve(trailers); +var getHttpSigningPlugin = /* @__PURE__ */ __name((config) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(httpSigningMiddleware(config), httpSigningMiddlewareOptions); + } +}), "getHttpSigningPlugin"); + +// src/normalizeProvider.ts +var normalizeProvider = /* @__PURE__ */ __name((input) => { + if (typeof input === "function") + return input; + const promisified = Promise.resolve(input); + return () => promisified; +}, "normalizeProvider"); + +// src/pagination/createPaginator.ts +var makePagedClientRequest = /* @__PURE__ */ __name(async (CommandCtor, client, input, withCommand = (_) => _, ...args) => { + let command = new CommandCtor(input); + command = withCommand(command) ?? command; + return await client.send(command, ...args); +}, "makePagedClientRequest"); +function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) { + return /* @__PURE__ */ __name(async function* paginateOperation(config, input, ...additionalArguments) { + const _input = input; + let token = config.startingToken ?? _input[inputTokenName]; + let hasNext = true; + let page; + while (hasNext) { + _input[inputTokenName] = token; + if (pageSizeTokenName) { + _input[pageSizeTokenName] = _input[pageSizeTokenName] ?? config.pageSize; + } + if (config.client instanceof ClientCtor) { + page = await makePagedClientRequest( + CommandCtor, + config.client, + input, + config.withCommand, + ...additionalArguments + ); + } else { + throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`); + } + yield page; + const prevToken = token; + token = get(page, outputTokenName); + hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); } - maybeSuppressUncaught(...promise) { - if (this.suppressUncaughtRejections) { - for (let p of promise) { - p.catch(() => { - }); - } - } + return void 0; + }, "paginateOperation"); +} +__name(createPaginator, "createPaginator"); +var get = /* @__PURE__ */ __name((fromObject, path) => { + let cursor = fromObject; + const pathComponents = path.split("."); + for (const step of pathComponents) { + if (!cursor || typeof cursor !== "object") { + return void 0; } - mergeOptions(options) { - return rpc_options_1.mergeRpcOptions({}, options); + cursor = cursor[step]; + } + return cursor; +}, "get"); + +// src/protocols/requestBuilder.ts +var import_protocols = __nccwpck_require__(2241); + +// src/setFeature.ts +function setFeature(context, feature, value) { + if (!context.__smithy_context) { + context.__smithy_context = { + features: {} + }; + } else if (!context.__smithy_context.features) { + context.__smithy_context.features = {}; + } + context.__smithy_context.features[feature] = value; +} +__name(setFeature, "setFeature"); + +// src/util-identity-and-auth/DefaultIdentityProviderConfig.ts +var DefaultIdentityProviderConfig = class { + /** + * Creates an IdentityProviderConfig with a record of scheme IDs to identity providers. + * + * @param config scheme IDs and identity providers to configure + */ + constructor(config) { + this.authSchemes = /* @__PURE__ */ new Map(); + for (const [key, value] of Object.entries(config)) { + if (value !== void 0) { + this.authSchemes.set(key, value); + } } - unary(method, input, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders() - .then(delay(this.headerDelay, options.abort)), responsePromise = headersPromise - .catch(_ => { - }) - .then(delay(this.responseDelay, options.abort)) - .then(_ => this.promiseSingleResponse(method)), statusPromise = responsePromise - .catch(_ => { - }) - .then(delay(this.afterResponseDelay, options.abort)) - .then(_ => this.promiseStatus()), trailersPromise = responsePromise - .catch(_ => { - }) - .then(delay(this.afterResponseDelay, options.abort)) - .then(_ => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = { single: input }; - return new unary_call_1.UnaryCall(method, requestHeaders, input, headersPromise, responsePromise, statusPromise, trailersPromise); + } + static { + __name(this, "DefaultIdentityProviderConfig"); + } + getIdentityProvider(schemeId) { + return this.authSchemes.get(schemeId); + } +}; + +// src/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.ts + + +var HttpApiKeyAuthSigner = class { + static { + __name(this, "HttpApiKeyAuthSigner"); + } + async sign(httpRequest, identity, signingProperties) { + if (!signingProperties) { + throw new Error( + "request could not be signed with `apiKey` since the `name` and `in` signer properties are missing" + ); } - serverStreaming(method, input, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders() - .then(delay(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise - .then(delay(this.responseDelay, options.abort)) - .catch(() => { - }) - .then(() => this.streamResponses(method, outputStream, options.abort)) - .then(delay(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise - .then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise - .then(() => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = { single: input }; - return new server_streaming_call_1.ServerStreamingCall(method, requestHeaders, input, headersPromise, outputStream, statusPromise, trailersPromise); + if (!signingProperties.name) { + throw new Error("request could not be signed with `apiKey` since the `name` signer property is missing"); } - clientStreaming(method, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders() - .then(delay(this.headerDelay, options.abort)), responsePromise = headersPromise - .catch(_ => { - }) - .then(delay(this.responseDelay, options.abort)) - .then(_ => this.promiseSingleResponse(method)), statusPromise = responsePromise - .catch(_ => { - }) - .then(delay(this.afterResponseDelay, options.abort)) - .then(_ => this.promiseStatus()), trailersPromise = responsePromise - .catch(_ => { - }) - .then(delay(this.afterResponseDelay, options.abort)) - .then(_ => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = new TestInputStream(this.data, options.abort); - return new client_streaming_call_1.ClientStreamingCall(method, requestHeaders, this.lastInput, headersPromise, responsePromise, statusPromise, trailersPromise); + if (!signingProperties.in) { + throw new Error("request could not be signed with `apiKey` since the `in` signer property is missing"); } - duplex(method, options) { - var _a; - const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders() - .then(delay(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise - .then(delay(this.responseDelay, options.abort)) - .catch(() => { - }) - .then(() => this.streamResponses(method, outputStream, options.abort)) - .then(delay(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise - .then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise - .then(() => this.promiseTrailers()); - this.maybeSuppressUncaught(statusPromise, trailersPromise); - this.lastInput = new TestInputStream(this.data, options.abort); - return new duplex_streaming_call_1.DuplexStreamingCall(method, requestHeaders, this.lastInput, headersPromise, outputStream, statusPromise, trailersPromise); + if (!identity.apiKey) { + throw new Error("request could not be signed with `apiKey` since the `apiKey` is not defined"); } -} -exports.TestTransport = TestTransport; -TestTransport.defaultHeaders = { - responseHeader: "test" + const clonedRequest = import_protocol_http.HttpRequest.clone(httpRequest); + if (signingProperties.in === import_types.HttpApiKeyAuthLocation.QUERY) { + clonedRequest.query[signingProperties.name] = identity.apiKey; + } else if (signingProperties.in === import_types.HttpApiKeyAuthLocation.HEADER) { + clonedRequest.headers[signingProperties.name] = signingProperties.scheme ? `${signingProperties.scheme} ${identity.apiKey}` : identity.apiKey; + } else { + throw new Error( + "request can only be signed with `apiKey` locations `query` or `header`, but found: `" + signingProperties.in + "`" + ); + } + return clonedRequest; + } }; -TestTransport.defaultStatus = { - code: "OK", detail: "all good" + +// src/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.ts + +var HttpBearerAuthSigner = class { + static { + __name(this, "HttpBearerAuthSigner"); + } + async sign(httpRequest, identity, signingProperties) { + const clonedRequest = import_protocol_http.HttpRequest.clone(httpRequest); + if (!identity.token) { + throw new Error("request could not be signed with `token` since the `token` is not defined"); + } + clonedRequest.headers["Authorization"] = `Bearer ${identity.token}`; + return clonedRequest; + } }; -TestTransport.defaultTrailers = { - responseTrailer: "test" + +// src/util-identity-and-auth/httpAuthSchemes/noAuth.ts +var NoAuthSigner = class { + static { + __name(this, "NoAuthSigner"); + } + async sign(httpRequest, identity, signingProperties) { + return httpRequest; + } }; -function delay(ms, abort) { - return (v) => new Promise((resolve, reject) => { - if (abort === null || abort === void 0 ? void 0 : abort.aborted) { - reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); - } - else { - const id = setTimeout(() => resolve(v), ms); - if (abort) { - abort.addEventListener("abort", ev => { - clearTimeout(id); - reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); - }); - } - } - }); -} -class TestInputStream { - constructor(data, abort) { - this._completed = false; - this._sent = []; - this.data = data; - this.abort = abort; + +// src/util-identity-and-auth/memoizeIdentityProvider.ts +var createIsIdentityExpiredFunction = /* @__PURE__ */ __name((expirationMs) => (identity) => doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs, "createIsIdentityExpiredFunction"); +var EXPIRATION_MS = 3e5; +var isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS); +var doesIdentityRequireRefresh = /* @__PURE__ */ __name((identity) => identity.expiration !== void 0, "doesIdentityRequireRefresh"); +var memoizeIdentityProvider = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { + if (provider === void 0) { + return void 0; + } + const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider; + let resolved; + let pending; + let hasResult; + let isConstant = false; + const coalesceProvider = /* @__PURE__ */ __name(async (options) => { + if (!pending) { + pending = normalizedProvider(options); } - get sent() { - return this._sent; + try { + resolved = await pending; + hasResult = true; + isConstant = false; + } finally { + pending = void 0; } - get completed() { - return this._completed; + return resolved; + }, "coalesceProvider"); + if (isExpired === void 0) { + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(options); + } + return resolved; + }; + } + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(options); } - send(message) { - if (this.data.inputMessage instanceof rpc_error_1.RpcError) { - return Promise.reject(this.data.inputMessage); - } - const delayMs = this.data.inputMessage === undefined - ? 10 - : this.data.inputMessage; - return Promise.resolve(undefined) - .then(() => { - this._sent.push(message); - }) - .then(delay(delayMs, this.abort)); + if (isConstant) { + return resolved; } - complete() { - if (this.data.inputComplete instanceof rpc_error_1.RpcError) { - return Promise.reject(this.data.inputComplete); - } - const delayMs = this.data.inputComplete === undefined - ? 10 - : this.data.inputComplete; - return Promise.resolve(undefined) - .then(() => { - this._completed = true; - }) - .then(delay(delayMs, this.abort)); + if (!requiresRefresh(resolved)) { + isConstant = true; + return resolved; + } + if (isExpired(resolved)) { + await coalesceProvider(options); + return resolved; + } + return resolved; + }; +}, "memoizeIdentityProvider"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 2241: +/***/ ((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 }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/submodules/protocols/index.ts +var protocols_exports = {}; +__export(protocols_exports, { + RequestBuilder: () => RequestBuilder, + collectBody: () => collectBody, + extendedEncodeURIComponent: () => extendedEncodeURIComponent, + requestBuilder: () => requestBuilder, + resolvedPath: () => resolvedPath +}); +module.exports = __toCommonJS(protocols_exports); + +// src/submodules/protocols/collect-stream-body.ts +var import_util_stream = __nccwpck_require__(96607); +var collectBody = async (streamBody = new Uint8Array(), context) => { + if (streamBody instanceof Uint8Array) { + return import_util_stream.Uint8ArrayBlobAdapter.mutate(streamBody); + } + if (!streamBody) { + return import_util_stream.Uint8ArrayBlobAdapter.mutate(new Uint8Array()); + } + const fromContext = context.streamCollector(streamBody); + return import_util_stream.Uint8ArrayBlobAdapter.mutate(await fromContext); +}; + +// src/submodules/protocols/extended-encode-uri-component.ts +function extendedEncodeURIComponent(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); + }); +} + +// src/submodules/protocols/requestBuilder.ts +var import_protocol_http = __nccwpck_require__(64418); + +// src/submodules/protocols/resolve-path.ts +var resolvedPath = (resolvedPath2, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => { + if (input != null && input[memberName] !== void 0) { + const labelValue = labelValueProvider(); + if (labelValue.length <= 0) { + throw new Error("Empty value provided for input HTTP label: " + memberName + "."); } + resolvedPath2 = resolvedPath2.replace( + uriLabel, + isGreedyLabel ? labelValue.split("/").map((segment) => extendedEncodeURIComponent(segment)).join("/") : extendedEncodeURIComponent(labelValue) + ); + } else { + throw new Error("No value provided for input HTTP label: " + memberName + "."); + } + return resolvedPath2; +}; + +// src/submodules/protocols/requestBuilder.ts +function requestBuilder(input, context) { + return new RequestBuilder(input, context); } +var RequestBuilder = class { + constructor(input, context) { + this.input = input; + this.context = context; + this.query = {}; + this.method = ""; + this.headers = {}; + this.path = ""; + this.body = null; + this.hostname = ""; + this.resolvePathStack = []; + } + async build() { + const { hostname, protocol = "https", port, path: basePath } = await this.context.endpoint(); + this.path = basePath; + for (const resolvePath of this.resolvePathStack) { + resolvePath(this.path); + } + return new import_protocol_http.HttpRequest({ + protocol, + hostname: this.hostname || hostname, + port, + method: this.method, + path: this.path, + query: this.query, + body: this.body, + headers: this.headers + }); + } + /** + * Brevity setter for "hostname". + */ + hn(hostname) { + this.hostname = hostname; + return this; + } + /** + * Brevity initial builder for "basepath". + */ + bp(uriLabel) { + this.resolvePathStack.push((basePath) => { + this.path = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + uriLabel; + }); + return this; + } + /** + * Brevity incremental builder for "path". + */ + p(memberName, labelValueProvider, uriLabel, isGreedyLabel) { + this.resolvePathStack.push((path) => { + this.path = resolvedPath(path, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel); + }); + return this; + } + /** + * Brevity setter for "headers". + */ + h(headers) { + this.headers = headers; + return this; + } + /** + * Brevity setter for "query". + */ + q(query) { + this.query = query; + return this; + } + /** + * Brevity setter for "body". + */ + b(body) { + this.body = body; + return this; + } + /** + * Brevity setter for "method". + */ + m(method) { + this.method = method; + return this; + } +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 84175: -/***/ (function(__unused_webpack_module, exports) { +/***/ 7477: +/***/ ((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 __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +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); -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); +// src/index.ts +var src_exports = {}; +__export(src_exports, { + DEFAULT_MAX_RETRIES: () => DEFAULT_MAX_RETRIES, + DEFAULT_TIMEOUT: () => DEFAULT_TIMEOUT, + ENV_CMDS_AUTH_TOKEN: () => ENV_CMDS_AUTH_TOKEN, + ENV_CMDS_FULL_URI: () => ENV_CMDS_FULL_URI, + ENV_CMDS_RELATIVE_URI: () => ENV_CMDS_RELATIVE_URI, + Endpoint: () => Endpoint, + fromContainerMetadata: () => fromContainerMetadata, + fromInstanceMetadata: () => fromInstanceMetadata, + getInstanceMetadataEndpoint: () => getInstanceMetadataEndpoint, + httpRequest: () => httpRequest, + providerConfigFromInit: () => providerConfigFromInit +}); +module.exports = __toCommonJS(src_exports); + +// src/fromContainerMetadata.ts + +var import_url = __nccwpck_require__(57310); + +// src/remoteProvider/httpRequest.ts +var import_property_provider = __nccwpck_require__(79721); +var import_buffer = __nccwpck_require__(14300); +var import_http = __nccwpck_require__(13685); +function httpRequest(options) { + return new Promise((resolve, reject) => { + const req = (0, import_http.request)({ + method: "GET", + ...options, + // Node.js http module doesn't accept hostname with square brackets + // Refs: https://github.com/nodejs/node/issues/39738 + hostname: options.hostname?.replace(/^\[(.+)\]$/, "$1") + }); + req.on("error", (err) => { + reject(Object.assign(new import_property_provider.ProviderError("Unable to connect to instance metadata service"), err)); + req.destroy(); + }); + req.on("timeout", () => { + reject(new import_property_provider.ProviderError("TimeoutError from instance metadata service")); + req.destroy(); + }); + req.on("response", (res) => { + const { statusCode = 400 } = res; + if (statusCode < 200 || 300 <= statusCode) { + reject( + Object.assign(new import_property_provider.ProviderError("Error response received from instance metadata service"), { statusCode }) + ); + req.destroy(); + } + const chunks = []; + res.on("data", (chunk) => { + chunks.push(chunk); + }); + res.on("end", () => { + resolve(import_buffer.Buffer.concat(chunks)); + req.destroy(); + }); }); + req.end(); + }); +} +__name(httpRequest, "httpRequest"); + +// src/remoteProvider/ImdsCredentials.ts +var isImdsCredentials = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.AccessKeyId === "string" && typeof arg.SecretAccessKey === "string" && typeof arg.Token === "string" && typeof arg.Expiration === "string", "isImdsCredentials"); +var fromImdsCredentials = /* @__PURE__ */ __name((creds) => ({ + accessKeyId: creds.AccessKeyId, + secretAccessKey: creds.SecretAccessKey, + sessionToken: creds.Token, + expiration: new Date(creds.Expiration), + ...creds.AccountId && { accountId: creds.AccountId } +}), "fromImdsCredentials"); + +// src/remoteProvider/RemoteProviderInit.ts +var DEFAULT_TIMEOUT = 1e3; +var DEFAULT_MAX_RETRIES = 0; +var providerConfigFromInit = /* @__PURE__ */ __name(({ + maxRetries = DEFAULT_MAX_RETRIES, + timeout = DEFAULT_TIMEOUT +}) => ({ maxRetries, timeout }), "providerConfigFromInit"); + +// src/remoteProvider/retry.ts +var retry = /* @__PURE__ */ __name((toRetry, maxRetries) => { + let promise = toRetry(); + for (let i = 0; i < maxRetries; i++) { + promise = promise.catch(toRetry); + } + return promise; +}, "retry"); + +// src/fromContainerMetadata.ts +var ENV_CMDS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; +var ENV_CMDS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; +var ENV_CMDS_AUTH_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; +var fromContainerMetadata = /* @__PURE__ */ __name((init = {}) => { + const { timeout, maxRetries } = providerConfigFromInit(init); + return () => retry(async () => { + const requestOptions = await getCmdsUri({ logger: init.logger }); + const credsResponse = JSON.parse(await requestFromEcsImds(timeout, requestOptions)); + if (!isImdsCredentials(credsResponse)) { + throw new import_property_provider.CredentialsProviderError("Invalid response received from instance metadata service.", { + logger: init.logger + }); + } + return fromImdsCredentials(credsResponse); + }, maxRetries); +}, "fromContainerMetadata"); +var requestFromEcsImds = /* @__PURE__ */ __name(async (timeout, options) => { + if (process.env[ENV_CMDS_AUTH_TOKEN]) { + options.headers = { + ...options.headers, + Authorization: process.env[ENV_CMDS_AUTH_TOKEN] + }; + } + const buffer = await httpRequest({ + ...options, + timeout + }); + return buffer.toString(); +}, "requestFromEcsImds"); +var CMDS_IP = "169.254.170.2"; +var GREENGRASS_HOSTS = { + localhost: true, + "127.0.0.1": true }; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.UnaryCall = void 0; -/** - * A unary RPC call. Unary means there is exactly one input message and - * exactly one output message unless an error occurred. - */ -class UnaryCall { - constructor(method, requestHeaders, request, headers, response, status, trailers) { - this.method = method; - this.requestHeaders = requestHeaders; - this.request = request; - this.headers = headers; - this.response = response; - this.status = status; - this.trailers = trailers; +var GREENGRASS_PROTOCOLS = { + "http:": true, + "https:": true +}; +var getCmdsUri = /* @__PURE__ */ __name(async ({ logger }) => { + if (process.env[ENV_CMDS_RELATIVE_URI]) { + return { + hostname: CMDS_IP, + path: process.env[ENV_CMDS_RELATIVE_URI] + }; + } + if (process.env[ENV_CMDS_FULL_URI]) { + const parsed = (0, import_url.parse)(process.env[ENV_CMDS_FULL_URI]); + if (!parsed.hostname || !(parsed.hostname in GREENGRASS_HOSTS)) { + throw new import_property_provider.CredentialsProviderError(`${parsed.hostname} is not a valid container metadata service hostname`, { + tryNextLink: false, + logger + }); } - /** - * If you are only interested in the final outcome of this call, - * you can await it to receive a `FinishedUnaryCall`. - */ - then(onfulfilled, onrejected) { - return this.promiseFinished().then(value => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, reason => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); + if (!parsed.protocol || !(parsed.protocol in GREENGRASS_PROTOCOLS)) { + throw new import_property_provider.CredentialsProviderError(`${parsed.protocol} is not a valid container metadata service protocol`, { + tryNextLink: false, + logger + }); } - promiseFinished() { - return __awaiter(this, void 0, void 0, function* () { - let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); - return { - method: this.method, - requestHeaders: this.requestHeaders, - request: this.request, - headers, - response, - status, - trailers - }; - }); + return { + ...parsed, + port: parsed.port ? parseInt(parsed.port, 10) : void 0 + }; + } + throw new import_property_provider.CredentialsProviderError( + `The container metadata credential provider cannot be used unless the ${ENV_CMDS_RELATIVE_URI} or ${ENV_CMDS_FULL_URI} environment variable is set`, + { + tryNextLink: false, + logger } -} -exports.UnaryCall = UnaryCall; + ); +}, "getCmdsUri"); +// src/fromInstanceMetadata.ts -/***/ }), -/***/ 54253: -/***/ ((__unused_webpack_module, exports) => { -"use strict"; +// src/error/InstanceMetadataV1FallbackError.ts -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.assertFloat32 = exports.assertUInt32 = exports.assertInt32 = exports.assertNever = exports.assert = void 0; -/** - * assert that condition is true or throw error (with message) - */ -function assert(condition, msg) { - if (!condition) { - throw new Error(msg); - } -} -exports.assert = assert; -/** - * assert that value cannot exist = type `never`. throw runtime error if it does. - */ -function assertNever(value, msg) { - throw new Error(msg !== null && msg !== void 0 ? msg : 'Unexpected object: ' + value); -} -exports.assertNever = assertNever; -const FLOAT32_MAX = 3.4028234663852886e+38, FLOAT32_MIN = -3.4028234663852886e+38, UINT32_MAX = 0xFFFFFFFF, INT32_MAX = 0X7FFFFFFF, INT32_MIN = -0X80000000; -function assertInt32(arg) { - if (typeof arg !== "number") - throw new Error('invalid int 32: ' + typeof arg); - if (!Number.isInteger(arg) || arg > INT32_MAX || arg < INT32_MIN) - throw new Error('invalid int 32: ' + arg); -} -exports.assertInt32 = assertInt32; -function assertUInt32(arg) { - if (typeof arg !== "number") - throw new Error('invalid uint 32: ' + typeof arg); - if (!Number.isInteger(arg) || arg > UINT32_MAX || arg < 0) - throw new Error('invalid uint 32: ' + arg); -} -exports.assertUInt32 = assertUInt32; -function assertFloat32(arg) { - if (typeof arg !== "number") - throw new Error('invalid float 32: ' + typeof arg); - if (!Number.isFinite(arg)) - return; - if (arg > FLOAT32_MAX || arg < FLOAT32_MIN) - throw new Error('invalid float 32: ' + arg); -} -exports.assertFloat32 = assertFloat32; +var InstanceMetadataV1FallbackError = class _InstanceMetadataV1FallbackError extends import_property_provider.CredentialsProviderError { + constructor(message, tryNextLink = true) { + super(message, tryNextLink); + this.tryNextLink = tryNextLink; + this.name = "InstanceMetadataV1FallbackError"; + Object.setPrototypeOf(this, _InstanceMetadataV1FallbackError.prototype); + } + static { + __name(this, "InstanceMetadataV1FallbackError"); + } +}; +// src/utils/getInstanceMetadataEndpoint.ts +var import_node_config_provider = __nccwpck_require__(33461); +var import_url_parser = __nccwpck_require__(14681); -/***/ }), +// src/config/Endpoint.ts +var Endpoint = /* @__PURE__ */ ((Endpoint2) => { + Endpoint2["IPv4"] = "http://169.254.169.254"; + Endpoint2["IPv6"] = "http://[fd00:ec2::254]"; + return Endpoint2; +})(Endpoint || {}); -/***/ 20196: -/***/ ((__unused_webpack_module, exports) => { +// src/config/EndpointConfigOptions.ts +var ENV_ENDPOINT_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT"; +var CONFIG_ENDPOINT_NAME = "ec2_metadata_service_endpoint"; +var ENDPOINT_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => env[ENV_ENDPOINT_NAME], + configFileSelector: (profile) => profile[CONFIG_ENDPOINT_NAME], + default: void 0 +}; -"use strict"; +// src/config/EndpointMode.ts +var EndpointMode = /* @__PURE__ */ ((EndpointMode2) => { + EndpointMode2["IPv4"] = "IPv4"; + EndpointMode2["IPv6"] = "IPv6"; + return EndpointMode2; +})(EndpointMode || {}); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.base64encode = exports.base64decode = void 0; -// lookup table from base64 character to byte -let encTable = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); -// lookup table from base64 character *code* to byte because lookup by number is fast -let decTable = []; -for (let i = 0; i < encTable.length; i++) - decTable[encTable[i].charCodeAt(0)] = i; -// support base64url variants -decTable["-".charCodeAt(0)] = encTable.indexOf("+"); -decTable["_".charCodeAt(0)] = encTable.indexOf("/"); -/** - * Decodes a base64 string to a byte array. - * - * - ignores white-space, including line breaks and tabs - * - allows inner padding (can decode concatenated base64 strings) - * - does not require padding - * - understands base64url encoding: - * "-" instead of "+", - * "_" instead of "/", - * no padding - */ -function base64decode(base64Str) { - // estimate byte size, not accounting for inner padding and whitespace - let es = base64Str.length * 3 / 4; - // if (es % 3 !== 0) - // throw new Error('invalid base64 string'); - if (base64Str[base64Str.length - 2] == '=') - es -= 2; - else if (base64Str[base64Str.length - 1] == '=') - es -= 1; - let bytes = new Uint8Array(es), bytePos = 0, // position in byte array - groupPos = 0, // position in base64 group - b, // current byte - p = 0 // previous byte - ; - for (let i = 0; i < base64Str.length; i++) { - b = decTable[base64Str.charCodeAt(i)]; - if (b === undefined) { - // noinspection FallThroughInSwitchStatementJS - switch (base64Str[i]) { - case '=': - groupPos = 0; // reset state when padding found - case '\n': - case '\r': - case '\t': - case ' ': - continue; // skip white-space, and padding - default: - throw Error(`invalid base64 string.`); +// src/config/EndpointModeConfigOptions.ts +var ENV_ENDPOINT_MODE_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE"; +var CONFIG_ENDPOINT_MODE_NAME = "ec2_metadata_service_endpoint_mode"; +var ENDPOINT_MODE_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => env[ENV_ENDPOINT_MODE_NAME], + configFileSelector: (profile) => profile[CONFIG_ENDPOINT_MODE_NAME], + default: "IPv4" /* IPv4 */ +}; + +// src/utils/getInstanceMetadataEndpoint.ts +var getInstanceMetadataEndpoint = /* @__PURE__ */ __name(async () => (0, import_url_parser.parseUrl)(await getFromEndpointConfig() || await getFromEndpointModeConfig()), "getInstanceMetadataEndpoint"); +var getFromEndpointConfig = /* @__PURE__ */ __name(async () => (0, import_node_config_provider.loadConfig)(ENDPOINT_CONFIG_OPTIONS)(), "getFromEndpointConfig"); +var getFromEndpointModeConfig = /* @__PURE__ */ __name(async () => { + const endpointMode = await (0, import_node_config_provider.loadConfig)(ENDPOINT_MODE_CONFIG_OPTIONS)(); + switch (endpointMode) { + case "IPv4" /* IPv4 */: + return "http://169.254.169.254" /* IPv4 */; + case "IPv6" /* IPv6 */: + return "http://[fd00:ec2::254]" /* IPv6 */; + default: + throw new Error(`Unsupported endpoint mode: ${endpointMode}. Select from ${Object.values(EndpointMode)}`); + } +}, "getFromEndpointModeConfig"); + +// src/utils/getExtendedInstanceMetadataCredentials.ts +var STATIC_STABILITY_REFRESH_INTERVAL_SECONDS = 5 * 60; +var STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS = 5 * 60; +var STATIC_STABILITY_DOC_URL = "https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html"; +var getExtendedInstanceMetadataCredentials = /* @__PURE__ */ __name((credentials, logger) => { + const refreshInterval = STATIC_STABILITY_REFRESH_INTERVAL_SECONDS + Math.floor(Math.random() * STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS); + const newExpiration = new Date(Date.now() + refreshInterval * 1e3); + logger.warn( + `Attempting credential expiration extension due to a credential service availability issue. A refresh of these credentials will be attempted after ${new Date(newExpiration)}. +For more information, please visit: ` + STATIC_STABILITY_DOC_URL + ); + const originalExpiration = credentials.originalExpiration ?? credentials.expiration; + return { + ...credentials, + ...originalExpiration ? { originalExpiration } : {}, + expiration: newExpiration + }; +}, "getExtendedInstanceMetadataCredentials"); + +// src/utils/staticStabilityProvider.ts +var staticStabilityProvider = /* @__PURE__ */ __name((provider, options = {}) => { + const logger = options?.logger || console; + let pastCredentials; + return async () => { + let credentials; + try { + credentials = await provider(); + if (credentials.expiration && credentials.expiration.getTime() < Date.now()) { + credentials = getExtendedInstanceMetadataCredentials(credentials, logger); + } + } catch (e) { + if (pastCredentials) { + logger.warn("Credential renew failed: ", e); + credentials = getExtendedInstanceMetadataCredentials(pastCredentials, logger); + } else { + throw e; + } + } + pastCredentials = credentials; + return credentials; + }; +}, "staticStabilityProvider"); + +// src/fromInstanceMetadata.ts +var IMDS_PATH = "/latest/meta-data/iam/security-credentials/"; +var IMDS_TOKEN_PATH = "/latest/api/token"; +var AWS_EC2_METADATA_V1_DISABLED = "AWS_EC2_METADATA_V1_DISABLED"; +var PROFILE_AWS_EC2_METADATA_V1_DISABLED = "ec2_metadata_v1_disabled"; +var X_AWS_EC2_METADATA_TOKEN = "x-aws-ec2-metadata-token"; +var fromInstanceMetadata = /* @__PURE__ */ __name((init = {}) => staticStabilityProvider(getInstanceMetadataProvider(init), { logger: init.logger }), "fromInstanceMetadata"); +var getInstanceMetadataProvider = /* @__PURE__ */ __name((init = {}) => { + let disableFetchToken = false; + const { logger, profile } = init; + const { timeout, maxRetries } = providerConfigFromInit(init); + const getCredentials = /* @__PURE__ */ __name(async (maxRetries2, options) => { + const isImdsV1Fallback = disableFetchToken || options.headers?.[X_AWS_EC2_METADATA_TOKEN] == null; + if (isImdsV1Fallback) { + let fallbackBlockedFromProfile = false; + let fallbackBlockedFromProcessEnv = false; + const configValue = await (0, import_node_config_provider.loadConfig)( + { + environmentVariableSelector: (env) => { + const envValue = env[AWS_EC2_METADATA_V1_DISABLED]; + fallbackBlockedFromProcessEnv = !!envValue && envValue !== "false"; + if (envValue === void 0) { + throw new import_property_provider.CredentialsProviderError( + `${AWS_EC2_METADATA_V1_DISABLED} not set in env, checking config file next.`, + { logger: init.logger } + ); } + return fallbackBlockedFromProcessEnv; + }, + configFileSelector: (profile2) => { + const profileValue = profile2[PROFILE_AWS_EC2_METADATA_V1_DISABLED]; + fallbackBlockedFromProfile = !!profileValue && profileValue !== "false"; + return fallbackBlockedFromProfile; + }, + default: false + }, + { + profile } - switch (groupPos) { - case 0: - p = b; - groupPos = 1; - break; - case 1: - bytes[bytePos++] = p << 2 | (b & 48) >> 4; - p = b; - groupPos = 2; - break; - case 2: - bytes[bytePos++] = (p & 15) << 4 | (b & 60) >> 2; - p = b; - groupPos = 3; - break; - case 3: - bytes[bytePos++] = (p & 3) << 6 | b; - groupPos = 0; - break; - } + )(); + if (init.ec2MetadataV1Disabled || configValue) { + const causes = []; + if (init.ec2MetadataV1Disabled) + causes.push("credential provider initialization (runtime option ec2MetadataV1Disabled)"); + if (fallbackBlockedFromProfile) + causes.push(`config file profile (${PROFILE_AWS_EC2_METADATA_V1_DISABLED})`); + if (fallbackBlockedFromProcessEnv) + causes.push(`process environment variable (${AWS_EC2_METADATA_V1_DISABLED})`); + throw new InstanceMetadataV1FallbackError( + `AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${causes.join( + ", " + )}].` + ); + } } - if (groupPos == 1) - throw Error(`invalid base64 string.`); - return bytes.subarray(0, bytePos); -} -exports.base64decode = base64decode; -/** - * Encodes a byte array to a base64 string. - * Adds padding at the end. - * Does not insert newlines. - */ -function base64encode(bytes) { - let base64 = '', groupPos = 0, // position in base64 group - b, // current byte - p = 0; // carry over from previous byte - for (let i = 0; i < bytes.length; i++) { - b = bytes[i]; - switch (groupPos) { - case 0: - base64 += encTable[b >> 2]; - p = (b & 3) << 4; - groupPos = 1; - break; - case 1: - base64 += encTable[p | b >> 4]; - p = (b & 15) << 2; - groupPos = 2; - break; - case 2: - base64 += encTable[p | b >> 6]; - base64 += encTable[b & 63]; - groupPos = 0; - break; + const imdsProfile = (await retry(async () => { + let profile2; + try { + profile2 = await getProfile(options); + } catch (err) { + if (err.statusCode === 401) { + disableFetchToken = false; } + throw err; + } + return profile2; + }, maxRetries2)).trim(); + return retry(async () => { + let creds; + try { + creds = await getCredentialsFromProfile(imdsProfile, options, init); + } catch (err) { + if (err.statusCode === 401) { + disableFetchToken = false; + } + throw err; + } + return creds; + }, maxRetries2); + }, "getCredentials"); + return async () => { + const endpoint = await getInstanceMetadataEndpoint(); + if (disableFetchToken) { + logger?.debug("AWS SDK Instance Metadata", "using v1 fallback (no token fetch)"); + return getCredentials(maxRetries, { ...endpoint, timeout }); + } else { + let token; + try { + token = (await getMetadataToken({ ...endpoint, timeout })).toString(); + } catch (error) { + if (error?.statusCode === 400) { + throw Object.assign(error, { + message: "EC2 Metadata token request returned error" + }); + } else if (error.message === "TimeoutError" || [403, 404, 405].includes(error.statusCode)) { + disableFetchToken = true; + } + logger?.debug("AWS SDK Instance Metadata", "using v1 fallback (initial)"); + return getCredentials(maxRetries, { ...endpoint, timeout }); + } + return getCredentials(maxRetries, { + ...endpoint, + headers: { + [X_AWS_EC2_METADATA_TOKEN]: token + }, + timeout + }); } - // padding required? - if (groupPos) { - base64 += encTable[p]; - base64 += '='; - if (groupPos == 1) - base64 += '='; - } - return base64; -} -exports.base64encode = base64encode; + }; +}, "getInstanceMetadataProvider"); +var getMetadataToken = /* @__PURE__ */ __name(async (options) => httpRequest({ + ...options, + path: IMDS_TOKEN_PATH, + method: "PUT", + headers: { + "x-aws-ec2-metadata-token-ttl-seconds": "21600" + } +}), "getMetadataToken"); +var getProfile = /* @__PURE__ */ __name(async (options) => (await httpRequest({ ...options, path: IMDS_PATH })).toString(), "getProfile"); +var getCredentialsFromProfile = /* @__PURE__ */ __name(async (profile, options, init) => { + const credentialsResponse = JSON.parse( + (await httpRequest({ + ...options, + path: IMDS_PATH + profile + })).toString() + ); + if (!isImdsCredentials(credentialsResponse)) { + throw new import_property_provider.CredentialsProviderError("Invalid response received from instance metadata service.", { + logger: init.logger + }); + } + return fromImdsCredentials(credentialsResponse); +}, "getCredentialsFromProfile"); +// Annotate the CommonJS export names for ESM import in node: +0 && (0); -/***/ }), -/***/ 84921: -/***/ ((__unused_webpack_module, exports) => { -"use strict"; +/***/ }), -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.WireType = exports.mergeBinaryOptions = exports.UnknownFieldHandler = void 0; -/** - * This handler implements the default behaviour for unknown fields. - * When reading data, unknown fields are stored on the message, in a - * symbol property. - * When writing data, the symbol property is queried and unknown fields - * are serialized into the output again. - */ -var UnknownFieldHandler; -(function (UnknownFieldHandler) { - /** - * The symbol used to store unknown fields for a message. - * The property must conform to `UnknownFieldContainer`. - */ - UnknownFieldHandler.symbol = Symbol.for("protobuf-ts/unknown"); - /** - * Store an unknown field during binary read directly on the message. - * This method is compatible with `BinaryReadOptions.readUnknownField`. - */ - UnknownFieldHandler.onRead = (typeName, message, fieldNo, wireType, data) => { - let container = is(message) ? message[UnknownFieldHandler.symbol] : message[UnknownFieldHandler.symbol] = []; - container.push({ no: fieldNo, wireType, data }); - }; - /** - * Write unknown fields stored for the message to the writer. - * This method is compatible with `BinaryWriteOptions.writeUnknownFields`. - */ - UnknownFieldHandler.onWrite = (typeName, message, writer) => { - for (let { no, wireType, data } of UnknownFieldHandler.list(message)) - writer.tag(no, wireType).raw(data); - }; - /** - * List unknown fields stored for the message. - * Note that there may be multiples fields with the same number. - */ - UnknownFieldHandler.list = (message, fieldNo) => { - if (is(message)) { - let all = message[UnknownFieldHandler.symbol]; - return fieldNo ? all.filter(uf => uf.no == fieldNo) : all; - } - return []; - }; - /** - * Returns the last unknown field by field number. - */ - UnknownFieldHandler.last = (message, fieldNo) => UnknownFieldHandler.list(message, fieldNo).slice(-1)[0]; - const is = (message) => message && Array.isArray(message[UnknownFieldHandler.symbol]); -})(UnknownFieldHandler = exports.UnknownFieldHandler || (exports.UnknownFieldHandler = {})); -/** - * Merges binary write or read options. Later values override earlier values. - */ -function mergeBinaryOptions(a, b) { - return Object.assign(Object.assign({}, a), b); -} -exports.mergeBinaryOptions = mergeBinaryOptions; -/** - * Protobuf binary format wire types. - * - * A wire type provides just enough information to find the length of the - * following value. - * - * See https://developers.google.com/protocol-buffers/docs/encoding#structure - */ -var WireType; -(function (WireType) { - /** - * Used for int32, int64, uint32, uint64, sint32, sint64, bool, enum - */ - WireType[WireType["Varint"] = 0] = "Varint"; - /** - * Used for fixed64, sfixed64, double. - * Always 8 bytes with little-endian byte order. - */ - WireType[WireType["Bit64"] = 1] = "Bit64"; - /** - * Used for string, bytes, embedded messages, packed repeated fields - * - * Only repeated numeric types (types which use the varint, 32-bit, - * or 64-bit wire types) can be packed. In proto3, such fields are - * packed by default. - */ - WireType[WireType["LengthDelimited"] = 2] = "LengthDelimited"; - /** - * Used for groups - * @deprecated - */ - WireType[WireType["StartGroup"] = 3] = "StartGroup"; - /** - * Used for groups - * @deprecated - */ - WireType[WireType["EndGroup"] = 4] = "EndGroup"; - /** - * Used for fixed32, sfixed32, float. - * Always 4 bytes with little-endian byte order. - */ - WireType[WireType["Bit32"] = 5] = "Bit32"; -})(WireType = exports.WireType || (exports.WireType = {})); +/***/ 56459: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +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); -/***/ }), +// src/index.ts +var src_exports = {}; +__export(src_exports, { + EventStreamCodec: () => EventStreamCodec, + HeaderMarshaller: () => HeaderMarshaller, + Int64: () => Int64, + MessageDecoderStream: () => MessageDecoderStream, + MessageEncoderStream: () => MessageEncoderStream, + SmithyMessageDecoderStream: () => SmithyMessageDecoderStream, + SmithyMessageEncoderStream: () => SmithyMessageEncoderStream +}); +module.exports = __toCommonJS(src_exports); -/***/ 65210: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// src/EventStreamCodec.ts +var import_crc322 = __nccwpck_require__(48408); -"use strict"; +// src/HeaderMarshaller.ts -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.BinaryReader = exports.binaryReadOptions = void 0; -const binary_format_contract_1 = __nccwpck_require__(84921); -const pb_long_1 = __nccwpck_require__(47777); -const goog_varint_1 = __nccwpck_require__(30433); -const defaultsRead = { - readUnknownField: true, - readerFactory: bytes => new BinaryReader(bytes), -}; -/** - * Make options for reading binary data form partial options. - */ -function binaryReadOptions(options) { - return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; -} -exports.binaryReadOptions = binaryReadOptions; -class BinaryReader { - constructor(buf, textDecoder) { - this.varint64 = goog_varint_1.varint64read; // dirty cast for `this` - /** - * Read a `uint32` field, an unsigned 32 bit varint. - */ - this.uint32 = goog_varint_1.varint32read; // dirty cast for `this` and access to protected `buf` - this.buf = buf; - this.len = buf.length; - this.pos = 0; - this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength); - this.textDecoder = textDecoder !== null && textDecoder !== void 0 ? textDecoder : new TextDecoder("utf-8", { - fatal: true, - ignoreBOM: true, - }); - } - /** - * Reads a tag - field number and wire type. - */ - tag() { - let tag = this.uint32(), fieldNo = tag >>> 3, wireType = tag & 7; - if (fieldNo <= 0 || wireType < 0 || wireType > 5) - throw new Error("illegal tag: field no " + fieldNo + " wire type " + wireType); - return [fieldNo, wireType]; - } - /** - * Skip one element on the wire and return the skipped data. - * Supports WireType.StartGroup since v2.0.0-alpha.23. - */ - skip(wireType) { - let start = this.pos; - // noinspection FallThroughInSwitchStatementJS - switch (wireType) { - case binary_format_contract_1.WireType.Varint: - while (this.buf[this.pos++] & 0x80) { - // ignore - } - break; - case binary_format_contract_1.WireType.Bit64: - this.pos += 4; - case binary_format_contract_1.WireType.Bit32: - this.pos += 4; - break; - case binary_format_contract_1.WireType.LengthDelimited: - let len = this.uint32(); - this.pos += len; - break; - case binary_format_contract_1.WireType.StartGroup: - // From descriptor.proto: Group type is deprecated, not supported in proto3. - // But we must still be able to parse and treat as unknown. - let t; - while ((t = this.tag()[1]) !== binary_format_contract_1.WireType.EndGroup) { - this.skip(t); - } - break; - default: - throw new Error("cant skip wire type " + wireType); - } - this.assertBounds(); - return this.buf.subarray(start, this.pos); - } - /** - * Throws error if position in byte array is out of range. - */ - assertBounds() { - if (this.pos > this.len) - throw new RangeError("premature EOF"); - } - /** - * Read a `int32` field, a signed 32 bit varint. - */ - int32() { - return this.uint32() | 0; + +// src/Int64.ts +var import_util_hex_encoding = __nccwpck_require__(45364); +var Int64 = class _Int64 { + constructor(bytes) { + this.bytes = bytes; + if (bytes.byteLength !== 8) { + throw new Error("Int64 buffers must be exactly 8 bytes"); } - /** - * Read a `sint32` field, a signed, zigzag-encoded 32-bit varint. - */ - sint32() { - let zze = this.uint32(); - // decode zigzag - return (zze >>> 1) ^ -(zze & 1); + } + static { + __name(this, "Int64"); + } + static fromNumber(number) { + if (number > 9223372036854776e3 || number < -9223372036854776e3) { + throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`); } - /** - * Read a `int64` field, a signed 64-bit varint. - */ - int64() { - return new pb_long_1.PbLong(...this.varint64()); + const bytes = new Uint8Array(8); + for (let i = 7, remaining = Math.abs(Math.round(number)); i > -1 && remaining > 0; i--, remaining /= 256) { + bytes[i] = remaining; } - /** - * Read a `uint64` field, an unsigned 64-bit varint. - */ - uint64() { - return new pb_long_1.PbULong(...this.varint64()); + if (number < 0) { + negate(bytes); } - /** - * Read a `sint64` field, a signed, zig-zag-encoded 64-bit varint. - */ - sint64() { - let [lo, hi] = this.varint64(); - // decode zig zag - let s = -(lo & 1); - lo = ((lo >>> 1 | (hi & 1) << 31) ^ s); - hi = (hi >>> 1 ^ s); - return new pb_long_1.PbLong(lo, hi); + return new _Int64(bytes); + } + /** + * Called implicitly by infix arithmetic operators. + */ + valueOf() { + const bytes = this.bytes.slice(0); + const negative = bytes[0] & 128; + if (negative) { + negate(bytes); } - /** - * Read a `bool` field, a variant. - */ - bool() { - let [lo, hi] = this.varint64(); - return lo !== 0 || hi !== 0; + return parseInt((0, import_util_hex_encoding.toHex)(bytes), 16) * (negative ? -1 : 1); + } + toString() { + return String(this.valueOf()); + } +}; +function negate(bytes) { + for (let i = 0; i < 8; i++) { + bytes[i] ^= 255; + } + for (let i = 7; i > -1; i--) { + bytes[i]++; + if (bytes[i] !== 0) + break; + } +} +__name(negate, "negate"); + +// src/HeaderMarshaller.ts +var HeaderMarshaller = class { + constructor(toUtf8, fromUtf8) { + this.toUtf8 = toUtf8; + this.fromUtf8 = fromUtf8; + } + static { + __name(this, "HeaderMarshaller"); + } + format(headers) { + const chunks = []; + for (const headerName of Object.keys(headers)) { + const bytes = this.fromUtf8(headerName); + chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName])); } - /** - * Read a `fixed32` field, an unsigned, fixed-length 32-bit integer. - */ - fixed32() { - return this.view.getUint32((this.pos += 4) - 4, true); + const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0)); + let position = 0; + for (const chunk of chunks) { + out.set(chunk, position); + position += chunk.byteLength; } - /** - * Read a `sfixed32` field, a signed, fixed-length 32-bit integer. - */ - sfixed32() { - return this.view.getInt32((this.pos += 4) - 4, true); + return out; + } + formatHeaderValue(header) { + switch (header.type) { + case "boolean": + return Uint8Array.from([header.value ? 0 /* boolTrue */ : 1 /* boolFalse */]); + case "byte": + return Uint8Array.from([2 /* byte */, header.value]); + case "short": + const shortView = new DataView(new ArrayBuffer(3)); + shortView.setUint8(0, 3 /* short */); + shortView.setInt16(1, header.value, false); + return new Uint8Array(shortView.buffer); + case "integer": + const intView = new DataView(new ArrayBuffer(5)); + intView.setUint8(0, 4 /* integer */); + intView.setInt32(1, header.value, false); + return new Uint8Array(intView.buffer); + case "long": + const longBytes = new Uint8Array(9); + longBytes[0] = 5 /* long */; + longBytes.set(header.value.bytes, 1); + return longBytes; + case "binary": + const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); + binView.setUint8(0, 6 /* byteArray */); + binView.setUint16(1, header.value.byteLength, false); + const binBytes = new Uint8Array(binView.buffer); + binBytes.set(header.value, 3); + return binBytes; + case "string": + const utf8Bytes = this.fromUtf8(header.value); + const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); + strView.setUint8(0, 7 /* string */); + strView.setUint16(1, utf8Bytes.byteLength, false); + const strBytes = new Uint8Array(strView.buffer); + strBytes.set(utf8Bytes, 3); + return strBytes; + case "timestamp": + const tsBytes = new Uint8Array(9); + tsBytes[0] = 8 /* timestamp */; + tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1); + return tsBytes; + case "uuid": + if (!UUID_PATTERN.test(header.value)) { + throw new Error(`Invalid UUID received: ${header.value}`); + } + const uuidBytes = new Uint8Array(17); + uuidBytes[0] = 9 /* uuid */; + uuidBytes.set((0, import_util_hex_encoding.fromHex)(header.value.replace(/\-/g, "")), 1); + return uuidBytes; } - /** - * Read a `fixed64` field, an unsigned, fixed-length 64 bit integer. - */ - fixed64() { - return new pb_long_1.PbULong(this.sfixed32(), this.sfixed32()); + } + parse(headers) { + const out = {}; + let position = 0; + while (position < headers.byteLength) { + const nameLength = headers.getUint8(position++); + const name = this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, nameLength)); + position += nameLength; + switch (headers.getUint8(position++)) { + case 0 /* boolTrue */: + out[name] = { + type: BOOLEAN_TAG, + value: true + }; + break; + case 1 /* boolFalse */: + out[name] = { + type: BOOLEAN_TAG, + value: false + }; + break; + case 2 /* byte */: + out[name] = { + type: BYTE_TAG, + value: headers.getInt8(position++) + }; + break; + case 3 /* short */: + out[name] = { + type: SHORT_TAG, + value: headers.getInt16(position, false) + }; + position += 2; + break; + case 4 /* integer */: + out[name] = { + type: INT_TAG, + value: headers.getInt32(position, false) + }; + position += 4; + break; + case 5 /* long */: + out[name] = { + type: LONG_TAG, + value: new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)) + }; + position += 8; + break; + case 6 /* byteArray */: + const binaryLength = headers.getUint16(position, false); + position += 2; + out[name] = { + type: BINARY_TAG, + value: new Uint8Array(headers.buffer, headers.byteOffset + position, binaryLength) + }; + position += binaryLength; + break; + case 7 /* string */: + const stringLength = headers.getUint16(position, false); + position += 2; + out[name] = { + type: STRING_TAG, + value: this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, stringLength)) + }; + position += stringLength; + break; + case 8 /* timestamp */: + out[name] = { + type: TIMESTAMP_TAG, + value: new Date(new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)).valueOf()) + }; + position += 8; + break; + case 9 /* uuid */: + const uuidBytes = new Uint8Array(headers.buffer, headers.byteOffset + position, 16); + position += 16; + out[name] = { + type: UUID_TAG, + value: `${(0, import_util_hex_encoding.toHex)(uuidBytes.subarray(0, 4))}-${(0, import_util_hex_encoding.toHex)(uuidBytes.subarray(4, 6))}-${(0, import_util_hex_encoding.toHex)( + uuidBytes.subarray(6, 8) + )}-${(0, import_util_hex_encoding.toHex)(uuidBytes.subarray(8, 10))}-${(0, import_util_hex_encoding.toHex)(uuidBytes.subarray(10))}` + }; + break; + default: + throw new Error(`Unrecognized header type tag`); + } } - /** - * Read a `fixed64` field, a signed, fixed-length 64-bit integer. - */ - sfixed64() { - return new pb_long_1.PbLong(this.sfixed32(), this.sfixed32()); + return out; + } +}; +var BOOLEAN_TAG = "boolean"; +var BYTE_TAG = "byte"; +var SHORT_TAG = "short"; +var INT_TAG = "integer"; +var LONG_TAG = "long"; +var BINARY_TAG = "binary"; +var STRING_TAG = "string"; +var TIMESTAMP_TAG = "timestamp"; +var UUID_TAG = "uuid"; +var UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; + +// src/splitMessage.ts +var import_crc32 = __nccwpck_require__(48408); +var PRELUDE_MEMBER_LENGTH = 4; +var PRELUDE_LENGTH = PRELUDE_MEMBER_LENGTH * 2; +var CHECKSUM_LENGTH = 4; +var MINIMUM_MESSAGE_LENGTH = PRELUDE_LENGTH + CHECKSUM_LENGTH * 2; +function splitMessage({ byteLength, byteOffset, buffer }) { + if (byteLength < MINIMUM_MESSAGE_LENGTH) { + throw new Error("Provided message too short to accommodate event stream message overhead"); + } + const view = new DataView(buffer, byteOffset, byteLength); + const messageLength = view.getUint32(0, false); + if (byteLength !== messageLength) { + throw new Error("Reported message length does not match received message length"); + } + const headerLength = view.getUint32(PRELUDE_MEMBER_LENGTH, false); + const expectedPreludeChecksum = view.getUint32(PRELUDE_LENGTH, false); + const expectedMessageChecksum = view.getUint32(byteLength - CHECKSUM_LENGTH, false); + const checksummer = new import_crc32.Crc32().update(new Uint8Array(buffer, byteOffset, PRELUDE_LENGTH)); + if (expectedPreludeChecksum !== checksummer.digest()) { + throw new Error( + `The prelude checksum specified in the message (${expectedPreludeChecksum}) does not match the calculated CRC32 checksum (${checksummer.digest()})` + ); + } + checksummer.update( + new Uint8Array(buffer, byteOffset + PRELUDE_LENGTH, byteLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH)) + ); + if (expectedMessageChecksum !== checksummer.digest()) { + throw new Error( + `The message checksum (${checksummer.digest()}) did not match the expected value of ${expectedMessageChecksum}` + ); + } + return { + headers: new DataView(buffer, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH, headerLength), + body: new Uint8Array( + buffer, + byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH + headerLength, + messageLength - headerLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH + CHECKSUM_LENGTH) + ) + }; +} +__name(splitMessage, "splitMessage"); + +// src/EventStreamCodec.ts +var EventStreamCodec = class { + static { + __name(this, "EventStreamCodec"); + } + constructor(toUtf8, fromUtf8) { + this.headerMarshaller = new HeaderMarshaller(toUtf8, fromUtf8); + this.messageBuffer = []; + this.isEndOfStream = false; + } + feed(message) { + this.messageBuffer.push(this.decode(message)); + } + endOfStream() { + this.isEndOfStream = true; + } + getMessage() { + const message = this.messageBuffer.pop(); + const isEndOfStream = this.isEndOfStream; + return { + getMessage() { + return message; + }, + isEndOfStream() { + return isEndOfStream; + } + }; + } + getAvailableMessages() { + const messages = this.messageBuffer; + this.messageBuffer = []; + const isEndOfStream = this.isEndOfStream; + return { + getMessages() { + return messages; + }, + isEndOfStream() { + return isEndOfStream; + } + }; + } + /** + * Convert a structured JavaScript object with tagged headers into a binary + * event stream message. + */ + encode({ headers: rawHeaders, body }) { + const headers = this.headerMarshaller.format(rawHeaders); + const length = headers.byteLength + body.byteLength + 16; + const out = new Uint8Array(length); + const view = new DataView(out.buffer, out.byteOffset, out.byteLength); + const checksum = new import_crc322.Crc32(); + view.setUint32(0, length, false); + view.setUint32(4, headers.byteLength, false); + view.setUint32(8, checksum.update(out.subarray(0, 8)).digest(), false); + out.set(headers, 12); + out.set(body, headers.byteLength + 12); + view.setUint32(length - 4, checksum.update(out.subarray(8, length - 4)).digest(), false); + return out; + } + /** + * Convert a binary event stream message into a JavaScript object with an + * opaque, binary body and tagged, parsed headers. + */ + decode(message) { + const { headers, body } = splitMessage(message); + return { headers: this.headerMarshaller.parse(headers), body }; + } + /** + * Convert a structured JavaScript object with tagged headers into a binary + * event stream message header. + */ + formatHeaders(rawHeaders) { + return this.headerMarshaller.format(rawHeaders); + } +}; + +// src/MessageDecoderStream.ts +var MessageDecoderStream = class { + constructor(options) { + this.options = options; + } + static { + __name(this, "MessageDecoderStream"); + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async *asyncIterator() { + for await (const bytes of this.options.inputStream) { + const decoded = this.options.decoder.decode(bytes); + yield decoded; } - /** - * Read a `float` field, 32-bit floating point number. - */ - float() { - return this.view.getFloat32((this.pos += 4) - 4, true); + } +}; + +// src/MessageEncoderStream.ts +var MessageEncoderStream = class { + constructor(options) { + this.options = options; + } + static { + __name(this, "MessageEncoderStream"); + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async *asyncIterator() { + for await (const msg of this.options.messageStream) { + const encoded = this.options.encoder.encode(msg); + yield encoded; } - /** - * Read a `double` field, a 64-bit floating point number. - */ - double() { - return this.view.getFloat64((this.pos += 8) - 8, true); + if (this.options.includeEndFrame) { + yield new Uint8Array(0); } - /** - * Read a `bytes` field, length-delimited arbitrary data. - */ - bytes() { - let len = this.uint32(); - let start = this.pos; - this.pos += len; - this.assertBounds(); - return this.buf.subarray(start, start + len); + } +}; + +// src/SmithyMessageDecoderStream.ts +var SmithyMessageDecoderStream = class { + constructor(options) { + this.options = options; + } + static { + __name(this, "SmithyMessageDecoderStream"); + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async *asyncIterator() { + for await (const message of this.options.messageStream) { + const deserialized = await this.options.deserializer(message); + if (deserialized === void 0) + continue; + yield deserialized; } - /** - * Read a `string` field, length-delimited data converted to UTF-8 text. - */ - string() { - return this.textDecoder.decode(this.bytes()); + } +}; + +// src/SmithyMessageEncoderStream.ts +var SmithyMessageEncoderStream = class { + constructor(options) { + this.options = options; + } + static { + __name(this, "SmithyMessageEncoderStream"); + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async *asyncIterator() { + for await (const chunk of this.options.inputStream) { + const payloadBuf = this.options.serializer(chunk); + yield payloadBuf; } -} -exports.BinaryReader = BinaryReader; + } +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); -/***/ }), -/***/ 44354: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +/***/ }), -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.BinaryWriter = exports.binaryWriteOptions = void 0; -const pb_long_1 = __nccwpck_require__(47777); -const goog_varint_1 = __nccwpck_require__(30433); -const assert_1 = __nccwpck_require__(54253); -const defaultsWrite = { - writeUnknownFields: true, - writerFactory: () => new BinaryWriter(), +/***/ 16181: +/***/ ((module) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); }; -/** - * Make options for writing binary data form partial options. - */ -function binaryWriteOptions(options) { - return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; -} -exports.binaryWriteOptions = binaryWriteOptions; -class BinaryWriter { - constructor(textEncoder) { - /** - * Previous fork states. - */ - this.stack = []; - this.textEncoder = textEncoder !== null && textEncoder !== void 0 ? textEncoder : new TextEncoder(); - this.chunks = []; - this.buf = []; - } - /** - * Return all bytes written and reset this writer. - */ - finish() { - this.chunks.push(new Uint8Array(this.buf)); // flush the buffer - let len = 0; - for (let i = 0; i < this.chunks.length; i++) - len += this.chunks[i].length; - let bytes = new Uint8Array(len); - let offset = 0; - for (let i = 0; i < this.chunks.length; i++) { - bytes.set(this.chunks[i], offset); - offset += this.chunks[i].length; - } - this.chunks = []; - return bytes; - } - /** - * Start a new fork for length-delimited data like a message - * or a packed repeated field. - * - * Must be joined later with `join()`. - */ - fork() { - this.stack.push({ chunks: this.chunks, buf: this.buf }); - this.chunks = []; - this.buf = []; - return this; - } - /** - * Join the last fork. Write its length and bytes, then - * return to the previous state. - */ - join() { - // get chunk of fork - let chunk = this.finish(); - // restore previous state - let prev = this.stack.pop(); - if (!prev) - throw new Error('invalid state, fork stack empty'); - this.chunks = prev.chunks; - this.buf = prev.buf; - // write length of chunk as varint - this.uint32(chunk.byteLength); - return this.raw(chunk); - } - /** - * Writes a tag (field number and wire type). - * - * Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`. - * - * Generated code should compute the tag ahead of time and call `uint32()`. - */ - tag(fieldNo, type) { - return this.uint32((fieldNo << 3 | type) >>> 0); - } - /** - * Write a chunk of raw bytes. - */ - raw(chunk) { - if (this.buf.length) { - this.chunks.push(new Uint8Array(this.buf)); - this.buf = []; - } - this.chunks.push(chunk); - return this; - } - /** - * Write a `uint32` value, an unsigned 32 bit varint. - */ - uint32(value) { - assert_1.assertUInt32(value); - // write value as varint 32, inlined for speed - while (value > 0x7f) { - this.buf.push((value & 0x7f) | 0x80); - value = value >>> 7; - } - this.buf.push(value); - return this; - } - /** - * Write a `int32` value, a signed 32 bit varint. - */ - int32(value) { - assert_1.assertInt32(value); - goog_varint_1.varint32write(value, this.buf); - return this; - } - /** - * Write a `bool` value, a variant. - */ - bool(value) { - this.buf.push(value ? 1 : 0); - return this; - } - /** - * Write a `bytes` value, length-delimited arbitrary data. - */ - bytes(value) { - this.uint32(value.byteLength); // write length of chunk as varint - return this.raw(value); - } - /** - * Write a `string` value, length-delimited data converted to UTF-8 text. - */ - string(value) { - let chunk = this.textEncoder.encode(value); - this.uint32(chunk.byteLength); // write length of chunk as varint - return this.raw(chunk); - } - /** - * Write a `float` value, 32-bit floating point number. - */ - float(value) { - assert_1.assertFloat32(value); - let chunk = new Uint8Array(4); - new DataView(chunk.buffer).setFloat32(0, value, true); - return this.raw(chunk); - } - /** - * Write a `double` value, a 64-bit floating point number. - */ - double(value) { - let chunk = new Uint8Array(8); - new DataView(chunk.buffer).setFloat64(0, value, true); - return this.raw(chunk); - } - /** - * Write a `fixed32` value, an unsigned, fixed-length 32-bit integer. - */ - fixed32(value) { - assert_1.assertUInt32(value); - let chunk = new Uint8Array(4); - new DataView(chunk.buffer).setUint32(0, value, true); - return this.raw(chunk); - } - /** - * Write a `sfixed32` value, a signed, fixed-length 32-bit integer. - */ - sfixed32(value) { - assert_1.assertInt32(value); - let chunk = new Uint8Array(4); - new DataView(chunk.buffer).setInt32(0, value, true); - return this.raw(chunk); - } - /** - * Write a `sint32` value, a signed, zigzag-encoded 32-bit varint. - */ - sint32(value) { - assert_1.assertInt32(value); - // zigzag encode - value = ((value << 1) ^ (value >> 31)) >>> 0; - goog_varint_1.varint32write(value, this.buf); - return this; - } - /** - * Write a `fixed64` value, a signed, fixed-length 64-bit integer. - */ - sfixed64(value) { - let chunk = new Uint8Array(8); - let view = new DataView(chunk.buffer); - let long = pb_long_1.PbLong.from(value); - view.setInt32(0, long.lo, true); - view.setInt32(4, long.hi, true); - return this.raw(chunk); - } - /** - * Write a `fixed64` value, an unsigned, fixed-length 64 bit integer. - */ - fixed64(value) { - let chunk = new Uint8Array(8); - let view = new DataView(chunk.buffer); - let long = pb_long_1.PbULong.from(value); - view.setInt32(0, long.lo, true); - view.setInt32(4, long.hi, true); - return this.raw(chunk); - } - /** - * Write a `int64` value, a signed 64-bit varint. - */ - int64(value) { - let long = pb_long_1.PbLong.from(value); - goog_varint_1.varint64write(long.lo, long.hi, this.buf); - return this; +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); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + resolveEventStreamSerdeConfig: () => resolveEventStreamSerdeConfig +}); +module.exports = __toCommonJS(src_exports); + +// src/EventStreamSerdeConfig.ts +var resolveEventStreamSerdeConfig = /* @__PURE__ */ __name((input) => Object.assign(input, { + eventStreamMarshaller: input.eventStreamSerdeProvider(input) +}), "resolveEventStreamSerdeConfig"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 77682: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +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); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + EventStreamMarshaller: () => EventStreamMarshaller, + eventStreamSerdeProvider: () => eventStreamSerdeProvider +}); +module.exports = __toCommonJS(src_exports); + +// src/EventStreamMarshaller.ts +var import_eventstream_serde_universal = __nccwpck_require__(66673); +var import_stream = __nccwpck_require__(12781); + +// src/utils.ts +async function* readabletoIterable(readStream) { + let streamEnded = false; + let generationEnded = false; + const records = new Array(); + readStream.on("error", (err) => { + if (!streamEnded) { + streamEnded = true; } - /** - * Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint. - */ - sint64(value) { - let long = pb_long_1.PbLong.from(value), - // zigzag encode - sign = long.hi >> 31, lo = (long.lo << 1) ^ sign, hi = ((long.hi << 1) | (long.lo >>> 31)) ^ sign; - goog_varint_1.varint64write(lo, hi, this.buf); - return this; + if (err) { + throw err; } - /** - * Write a `uint64` value, an unsigned 64-bit varint. - */ - uint64(value) { - let long = pb_long_1.PbULong.from(value); - goog_varint_1.varint64write(long.lo, long.hi, this.buf); - return this; + }); + readStream.on("data", (data) => { + records.push(data); + }); + readStream.on("end", () => { + streamEnded = true; + }); + while (!generationEnded) { + const value = await new Promise((resolve) => setTimeout(() => resolve(records.shift()), 0)); + if (value) { + yield value; } + generationEnded = streamEnded && records.length === 0; + } } -exports.BinaryWriter = BinaryWriter; +__name(readabletoIterable, "readabletoIterable"); + +// src/EventStreamMarshaller.ts +var EventStreamMarshaller = class { + static { + __name(this, "EventStreamMarshaller"); + } + constructor({ utf8Encoder, utf8Decoder }) { + this.universalMarshaller = new import_eventstream_serde_universal.EventStreamMarshaller({ + utf8Decoder, + utf8Encoder + }); + } + deserialize(body, deserializer) { + const bodyIterable = typeof body[Symbol.asyncIterator] === "function" ? body : readabletoIterable(body); + return this.universalMarshaller.deserialize(bodyIterable, deserializer); + } + serialize(input, serializer) { + return import_stream.Readable.from(this.universalMarshaller.serialize(input, serializer)); + } +}; + +// src/provider.ts +var eventStreamSerdeProvider = /* @__PURE__ */ __name((options) => new EventStreamMarshaller(options), "eventStreamSerdeProvider"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + /***/ }), -/***/ 20085: -/***/ ((__unused_webpack_module, exports) => { +/***/ 66673: +/***/ ((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 __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +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); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.listEnumNumbers = exports.listEnumNames = exports.listEnumValues = exports.isEnumObject = void 0; -/** - * Is this a lookup object generated by Typescript, for a Typescript enum - * generated by protobuf-ts? - * - * - No `const enum` (enum must not be inlined, we need reverse mapping). - * - No string enum (we need int32 for protobuf). - * - Must have a value for 0 (otherwise, we would need to support custom default values). - */ -function isEnumObject(arg) { - if (typeof arg != 'object' || arg === null) { - return false; - } - if (!arg.hasOwnProperty(0)) { - return false; +// src/index.ts +var src_exports = {}; +__export(src_exports, { + EventStreamMarshaller: () => EventStreamMarshaller, + eventStreamSerdeProvider: () => eventStreamSerdeProvider +}); +module.exports = __toCommonJS(src_exports); + +// src/EventStreamMarshaller.ts +var import_eventstream_codec = __nccwpck_require__(56459); + +// src/getChunkedStream.ts +function getChunkedStream(source) { + let currentMessageTotalLength = 0; + let currentMessagePendingLength = 0; + let currentMessage = null; + let messageLengthBuffer = null; + const allocateMessage = /* @__PURE__ */ __name((size) => { + if (typeof size !== "number") { + throw new Error("Attempted to allocate an event message where size was not a number: " + size); } - for (let k of Object.keys(arg)) { - let num = parseInt(k); - if (!Number.isNaN(num)) { - // is there a name for the number? - let nam = arg[num]; - if (nam === undefined) - return false; - // does the name resolve back to the number? - if (arg[nam] !== num) - return false; + currentMessageTotalLength = size; + currentMessagePendingLength = 4; + currentMessage = new Uint8Array(size); + const currentMessageView = new DataView(currentMessage.buffer); + currentMessageView.setUint32(0, size, false); + }, "allocateMessage"); + const iterator = /* @__PURE__ */ __name(async function* () { + const sourceIterator = source[Symbol.asyncIterator](); + while (true) { + const { value, done } = await sourceIterator.next(); + if (done) { + if (!currentMessageTotalLength) { + return; + } else if (currentMessageTotalLength === currentMessagePendingLength) { + yield currentMessage; + } else { + throw new Error("Truncated event message received."); } - else { - // is there a number for the name? - let num = arg[k]; - if (num === undefined) - return false; - // is it a string enum? - if (typeof num !== 'number') - return false; - // do we know the number? - if (arg[num] === undefined) - return false; + return; + } + const chunkLength = value.length; + let currentOffset = 0; + while (currentOffset < chunkLength) { + if (!currentMessage) { + const bytesRemaining = chunkLength - currentOffset; + if (!messageLengthBuffer) { + messageLengthBuffer = new Uint8Array(4); + } + const numBytesForTotal = Math.min( + 4 - currentMessagePendingLength, + // remaining bytes to fill the messageLengthBuffer + bytesRemaining + // bytes left in chunk + ); + messageLengthBuffer.set( + // @ts-ignore error TS2532: Object is possibly 'undefined' for value + value.slice(currentOffset, currentOffset + numBytesForTotal), + currentMessagePendingLength + ); + currentMessagePendingLength += numBytesForTotal; + currentOffset += numBytesForTotal; + if (currentMessagePendingLength < 4) { + break; + } + allocateMessage(new DataView(messageLengthBuffer.buffer).getUint32(0, false)); + messageLengthBuffer = null; + } + const numBytesToWrite = Math.min( + currentMessageTotalLength - currentMessagePendingLength, + // number of bytes left to complete message + chunkLength - currentOffset + // number of bytes left in the original chunk + ); + currentMessage.set( + // @ts-ignore error TS2532: Object is possibly 'undefined' for value + value.slice(currentOffset, currentOffset + numBytesToWrite), + currentMessagePendingLength + ); + currentMessagePendingLength += numBytesToWrite; + currentOffset += numBytesToWrite; + if (currentMessageTotalLength && currentMessageTotalLength === currentMessagePendingLength) { + yield currentMessage; + currentMessage = null; + currentMessageTotalLength = 0; + currentMessagePendingLength = 0; } + } } - return true; -} -exports.isEnumObject = isEnumObject; -/** - * Lists all values of a Typescript enum, as an array of objects with a "name" - * property and a "number" property. - * - * Note that it is possible that a number appears more than once, because it is - * possible to have aliases in an enum. - * - * Throws if the enum does not adhere to the rules of enums generated by - * protobuf-ts. See `isEnumObject()`. - */ -function listEnumValues(enumObject) { - if (!isEnumObject(enumObject)) - throw new Error("not a typescript enum object"); - let values = []; - for (let [name, number] of Object.entries(enumObject)) - if (typeof number == "number") - values.push({ name, number }); - return values; -} -exports.listEnumValues = listEnumValues; -/** - * Lists the names of a Typescript enum. - * - * Throws if the enum does not adhere to the rules of enums generated by - * protobuf-ts. See `isEnumObject()`. - */ -function listEnumNames(enumObject) { - return listEnumValues(enumObject).map(val => val.name); + }, "iterator"); + return { + [Symbol.asyncIterator]: iterator + }; } -exports.listEnumNames = listEnumNames; -/** - * Lists the numbers of a Typescript enum. - * - * Throws if the enum does not adhere to the rules of enums generated by - * protobuf-ts. See `isEnumObject()`. - */ -function listEnumNumbers(enumObject) { - return listEnumValues(enumObject) - .map(val => val.number) - .filter((num, index, arr) => arr.indexOf(num) == index); +__name(getChunkedStream, "getChunkedStream"); + +// src/getUnmarshalledStream.ts +function getMessageUnmarshaller(deserializer, toUtf8) { + return async function(message) { + const { value: messageType } = message.headers[":message-type"]; + if (messageType === "error") { + const unmodeledError = new Error(message.headers[":error-message"].value || "UnknownError"); + unmodeledError.name = message.headers[":error-code"].value; + throw unmodeledError; + } else if (messageType === "exception") { + const code = message.headers[":exception-type"].value; + const exception = { [code]: message }; + const deserializedException = await deserializer(exception); + if (deserializedException.$unknown) { + const error = new Error(toUtf8(message.body)); + error.name = code; + throw error; + } + throw deserializedException[code]; + } else if (messageType === "event") { + const event = { + [message.headers[":event-type"].value]: message + }; + const deserialized = await deserializer(event); + if (deserialized.$unknown) + return; + return deserialized; + } else { + throw Error(`Unrecognizable event type: ${message.headers[":event-type"].value}`); + } + }; } -exports.listEnumNumbers = listEnumNumbers; +__name(getMessageUnmarshaller, "getMessageUnmarshaller"); + +// src/EventStreamMarshaller.ts +var EventStreamMarshaller = class { + static { + __name(this, "EventStreamMarshaller"); + } + constructor({ utf8Encoder, utf8Decoder }) { + this.eventStreamCodec = new import_eventstream_codec.EventStreamCodec(utf8Encoder, utf8Decoder); + this.utfEncoder = utf8Encoder; + } + deserialize(body, deserializer) { + const inputStream = getChunkedStream(body); + return new import_eventstream_codec.SmithyMessageDecoderStream({ + messageStream: new import_eventstream_codec.MessageDecoderStream({ inputStream, decoder: this.eventStreamCodec }), + // @ts-expect-error Type 'T' is not assignable to type 'Record' + deserializer: getMessageUnmarshaller(deserializer, this.utfEncoder) + }); + } + serialize(inputStream, serializer) { + return new import_eventstream_codec.MessageEncoderStream({ + messageStream: new import_eventstream_codec.SmithyMessageEncoderStream({ inputStream, serializer }), + encoder: this.eventStreamCodec, + includeEndFrame: true + }); + } +}; + +// src/provider.ts +var eventStreamSerdeProvider = /* @__PURE__ */ __name((options) => new EventStreamMarshaller(options), "eventStreamSerdeProvider"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + /***/ }), -/***/ 30433: -/***/ ((__unused_webpack_module, exports) => { +/***/ 82687: +/***/ ((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 __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +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); -// Copyright 2008 Google Inc. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Code generated by the Protocol Buffer compiler is owned by the owner -// of the input file used when generating it. This code is not -// standalone and requires a support library to be linked with it. This -// support library is itself covered by the above license. -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.varint32read = exports.varint32write = exports.int64toString = exports.int64fromString = exports.varint64write = exports.varint64read = void 0; -/** - * Read a 64 bit varint as two JS numbers. - * - * Returns tuple: - * [0]: low bits - * [0]: high bits - * - * Copyright 2008 Google Inc. All rights reserved. - * - * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L175 - */ -function varint64read() { - let lowBits = 0; - let highBits = 0; - for (let shift = 0; shift < 28; shift += 7) { - let b = this.buf[this.pos++]; - lowBits |= (b & 0x7F) << shift; - if ((b & 0x80) == 0) { - this.assertBounds(); - return [lowBits, highBits]; - } +// src/index.ts +var src_exports = {}; +__export(src_exports, { + FetchHttpHandler: () => FetchHttpHandler, + keepAliveSupport: () => keepAliveSupport, + streamCollector: () => streamCollector +}); +module.exports = __toCommonJS(src_exports); + +// src/fetch-http-handler.ts +var import_protocol_http = __nccwpck_require__(64418); +var import_querystring_builder = __nccwpck_require__(68031); + +// src/create-request.ts +function createRequest(url, requestOptions) { + return new Request(url, requestOptions); +} +__name(createRequest, "createRequest"); + +// src/request-timeout.ts +function requestTimeout(timeoutInMs = 0) { + return new Promise((resolve, reject) => { + if (timeoutInMs) { + setTimeout(() => { + const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`); + timeoutError.name = "TimeoutError"; + reject(timeoutError); + }, timeoutInMs); } - let middleByte = this.buf[this.pos++]; - // last four bits of the first 32 bit number - lowBits |= (middleByte & 0x0F) << 28; - // 3 upper bits are part of the next 32 bit number - highBits = (middleByte & 0x70) >> 4; - if ((middleByte & 0x80) == 0) { - this.assertBounds(); - return [lowBits, highBits]; + }); +} +__name(requestTimeout, "requestTimeout"); + +// src/fetch-http-handler.ts +var keepAliveSupport = { + supported: void 0 +}; +var FetchHttpHandler = class _FetchHttpHandler { + static { + __name(this, "FetchHttpHandler"); + } + /** + * @returns the input if it is an HttpHandler of any class, + * or instantiates a new instance of this handler. + */ + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; } - for (let shift = 3; shift <= 31; shift += 7) { - let b = this.buf[this.pos++]; - highBits |= (b & 0x7F) << shift; - if ((b & 0x80) == 0) { - this.assertBounds(); - return [lowBits, highBits]; - } + return new _FetchHttpHandler(instanceOrOptions); + } + constructor(options) { + if (typeof options === "function") { + this.configProvider = options().then((opts) => opts || {}); + } else { + this.config = options ?? {}; + this.configProvider = Promise.resolve(this.config); } - throw new Error('invalid varint'); -} -exports.varint64read = varint64read; -/** - * Write a 64 bit varint, given as two JS numbers, to the given bytes array. - * - * Copyright 2008 Google Inc. All rights reserved. - * - * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/writer.js#L344 - */ -function varint64write(lo, hi, bytes) { - for (let i = 0; i < 28; i = i + 7) { - const shift = lo >>> i; - const hasNext = !((shift >>> 7) == 0 && hi == 0); - const byte = (hasNext ? shift | 0x80 : shift) & 0xFF; - bytes.push(byte); - if (!hasNext) { - return; - } + if (keepAliveSupport.supported === void 0) { + keepAliveSupport.supported = Boolean( + typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]") + ); } - const splitBits = ((lo >>> 28) & 0x0F) | ((hi & 0x07) << 4); - const hasMoreBits = !((hi >> 3) == 0); - bytes.push((hasMoreBits ? splitBits | 0x80 : splitBits) & 0xFF); - if (!hasMoreBits) { - return; + } + destroy() { + } + async handle(request, { abortSignal } = {}) { + if (!this.config) { + this.config = await this.configProvider; } - for (let i = 3; i < 31; i = i + 7) { - const shift = hi >>> i; - const hasNext = !((shift >>> 7) == 0); - const byte = (hasNext ? shift | 0x80 : shift) & 0xFF; - bytes.push(byte); - if (!hasNext) { - return; - } + const requestTimeoutInMs = this.config.requestTimeout; + const keepAlive = this.config.keepAlive === true; + const credentials = this.config.credentials; + if (abortSignal?.aborted) { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + return Promise.reject(abortError); } - bytes.push((hi >>> 31) & 0x01); -} -exports.varint64write = varint64write; -// constants for binary math -const TWO_PWR_32_DBL = (1 << 16) * (1 << 16); -/** - * Parse decimal string of 64 bit integer value as two JS numbers. - * - * Returns tuple: - * [0]: minus sign? - * [1]: low bits - * [2]: high bits - * - * Copyright 2008 Google Inc. - */ -function int64fromString(dec) { - // Check for minus sign. - let minus = dec[0] == '-'; - if (minus) - dec = dec.slice(1); - // Work 6 decimal digits at a time, acting like we're converting base 1e6 - // digits to binary. This is safe to do with floating point math because - // Number.isSafeInteger(ALL_32_BITS * 1e6) == true. - const base = 1e6; - let lowBits = 0; - let highBits = 0; - function add1e6digit(begin, end) { - // Note: Number('') is 0. - const digit1e6 = Number(dec.slice(begin, end)); - highBits *= base; - lowBits = lowBits * base + digit1e6; - // Carry bits from lowBits to highBits - if (lowBits >= TWO_PWR_32_DBL) { - highBits = highBits + ((lowBits / TWO_PWR_32_DBL) | 0); - lowBits = lowBits % TWO_PWR_32_DBL; - } + let path = request.path; + const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); + if (queryString) { + path += `?${queryString}`; } - add1e6digit(-24, -18); - add1e6digit(-18, -12); - add1e6digit(-12, -6); - add1e6digit(-6); - return [minus, lowBits, highBits]; -} -exports.int64fromString = int64fromString; -/** - * Format 64 bit integer value (as two JS numbers) to decimal string. - * - * Copyright 2008 Google Inc. - */ -function int64toString(bitsLow, bitsHigh) { - // Skip the expensive conversion if the number is small enough to use the - // built-in conversions. - if ((bitsHigh >>> 0) <= 0x1FFFFF) { - return '' + (TWO_PWR_32_DBL * bitsHigh + (bitsLow >>> 0)); + if (request.fragment) { + path += `#${request.fragment}`; } - // What this code is doing is essentially converting the input number from - // base-2 to base-1e7, which allows us to represent the 64-bit range with - // only 3 (very large) digits. Those digits are then trivial to convert to - // a base-10 string. - // The magic numbers used here are - - // 2^24 = 16777216 = (1,6777216) in base-1e7. - // 2^48 = 281474976710656 = (2,8147497,6710656) in base-1e7. - // Split 32:32 representation into 16:24:24 representation so our - // intermediate digits don't overflow. - let low = bitsLow & 0xFFFFFF; - let mid = (((bitsLow >>> 24) | (bitsHigh << 8)) >>> 0) & 0xFFFFFF; - let high = (bitsHigh >> 16) & 0xFFFF; - // Assemble our three base-1e7 digits, ignoring carries. The maximum - // value in a digit at this step is representable as a 48-bit integer, which - // can be stored in a 64-bit floating point number. - let digitA = low + (mid * 6777216) + (high * 6710656); - let digitB = mid + (high * 8147497); - let digitC = (high * 2); - // Apply carries from A to B and from B to C. - let base = 10000000; - if (digitA >= base) { - digitB += Math.floor(digitA / base); - digitA %= base; + let auth = ""; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}@`; } - if (digitB >= base) { - digitC += Math.floor(digitB / base); - digitB %= base; + const { port, method } = request; + const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path}`; + const body = method === "GET" || method === "HEAD" ? void 0 : request.body; + const requestOptions = { + body, + headers: new Headers(request.headers), + method, + credentials + }; + if (this.config?.cache) { + requestOptions.cache = this.config.cache; } - // Convert base-1e7 digits to base-10, with optional leading zeroes. - function decimalFrom1e7(digit1e7, needLeadingZeros) { - let partial = digit1e7 ? String(digit1e7) : ''; - if (needLeadingZeros) { - return '0000000'.slice(partial.length) + partial; - } - return partial; + if (body) { + requestOptions.duplex = "half"; } - return decimalFrom1e7(digitC, /*needLeadingZeros=*/ 0) + - decimalFrom1e7(digitB, /*needLeadingZeros=*/ digitC) + - // If the final 1e7 digit didn't need leading zeros, we would have - // returned via the trivial code path at the top. - decimalFrom1e7(digitA, /*needLeadingZeros=*/ 1); -} -exports.int64toString = int64toString; -/** - * Write a 32 bit varint, signed or unsigned. Same as `varint64write(0, value, bytes)` - * - * Copyright 2008 Google Inc. All rights reserved. - * - * See https://github.com/protocolbuffers/protobuf/blob/1b18833f4f2a2f681f4e4a25cdf3b0a43115ec26/js/binary/encoder.js#L144 - */ -function varint32write(value, bytes) { - if (value >= 0) { - // write value as varint 32 - while (value > 0x7f) { - bytes.push((value & 0x7f) | 0x80); - value = value >>> 7; - } - bytes.push(value); + if (typeof AbortController !== "undefined") { + requestOptions.signal = abortSignal; } - else { - for (let i = 0; i < 9; i++) { - bytes.push(value & 127 | 128); - value = value >> 7; - } - bytes.push(1); + if (keepAliveSupport.supported) { + requestOptions.keepalive = keepAlive; } -} -exports.varint32write = varint32write; -/** - * Read an unsigned 32 bit varint. - * - * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L220 - */ -function varint32read() { - let b = this.buf[this.pos++]; - let result = b & 0x7F; - if ((b & 0x80) == 0) { - this.assertBounds(); - return result; + if (typeof this.config.requestInit === "function") { + Object.assign(requestOptions, this.config.requestInit(request)); } - b = this.buf[this.pos++]; - result |= (b & 0x7F) << 7; - if ((b & 0x80) == 0) { - this.assertBounds(); - return result; + let removeSignalEventListener = /* @__PURE__ */ __name(() => { + }, "removeSignalEventListener"); + const fetchRequest = createRequest(url, requestOptions); + const raceOfPromises = [ + fetch(fetchRequest).then((response) => { + const fetchHeaders = response.headers; + const transformedHeaders = {}; + for (const pair of fetchHeaders.entries()) { + transformedHeaders[pair[0]] = pair[1]; + } + const hasReadableStream = response.body != void 0; + if (!hasReadableStream) { + return response.blob().then((body2) => ({ + response: new import_protocol_http.HttpResponse({ + headers: transformedHeaders, + reason: response.statusText, + statusCode: response.status, + body: body2 + }) + })); + } + return { + response: new import_protocol_http.HttpResponse({ + headers: transformedHeaders, + reason: response.statusText, + statusCode: response.status, + body: response.body + }) + }; + }), + requestTimeout(requestTimeoutInMs) + ]; + if (abortSignal) { + raceOfPromises.push( + new Promise((resolve, reject) => { + const onAbort = /* @__PURE__ */ __name(() => { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + }, "onAbort"); + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + removeSignalEventListener = /* @__PURE__ */ __name(() => signal.removeEventListener("abort", onAbort), "removeSignalEventListener"); + } else { + abortSignal.onabort = onAbort; + } + }) + ); } - b = this.buf[this.pos++]; - result |= (b & 0x7F) << 14; - if ((b & 0x80) == 0) { - this.assertBounds(); - return result; + return Promise.race(raceOfPromises).finally(removeSignalEventListener); + } + updateHttpClientConfig(key, value) { + this.config = void 0; + this.configProvider = this.configProvider.then((config) => { + config[key] = value; + return config; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } +}; + +// src/stream-collector.ts +var import_util_base64 = __nccwpck_require__(75600); +var streamCollector = /* @__PURE__ */ __name(async (stream) => { + if (typeof Blob === "function" && stream instanceof Blob || stream.constructor?.name === "Blob") { + if (Blob.prototype.arrayBuffer !== void 0) { + return new Uint8Array(await stream.arrayBuffer()); } - b = this.buf[this.pos++]; - result |= (b & 0x7F) << 21; - if ((b & 0x80) == 0) { - this.assertBounds(); - return result; + return collectBlob(stream); + } + return collectStream(stream); +}, "streamCollector"); +async function collectBlob(blob) { + const base64 = await readToBase64(blob); + const arrayBuffer = (0, import_util_base64.fromBase64)(base64); + return new Uint8Array(arrayBuffer); +} +__name(collectBlob, "collectBlob"); +async function collectStream(stream) { + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + let length = 0; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + length += value.length; } - // Extract only last 4 bits - b = this.buf[this.pos++]; - result |= (b & 0x0F) << 28; - for (let readBytes = 5; ((b & 0x80) !== 0) && readBytes < 10; readBytes++) - b = this.buf[this.pos++]; - if ((b & 0x80) != 0) - throw new Error('invalid varint'); - this.assertBounds(); - // Result can have 32 bits, convert it to unsigned - return result >>> 0; + isDone = done; + } + const collected = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + collected.set(chunk, offset); + offset += chunk.length; + } + return collected; } -exports.varint32read = varint32read; +__name(collectStream, "collectStream"); +function readToBase64(blob) { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onloadend = () => { + if (reader.readyState !== 2) { + return reject(new Error("Reader aborted too early")); + } + const result = reader.result ?? ""; + const commaIndex = result.indexOf(","); + const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length; + resolve(result.substring(dataOffset)); + }; + reader.onabort = () => reject(new Error("Read aborted")); + reader.onerror = () => reject(reader.error); + reader.readAsDataURL(blob); + }); +} +__name(readToBase64, "readToBase64"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + /***/ }), -/***/ 37001: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 3081: +/***/ ((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 __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +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); -// Public API of the protobuf-ts runtime. -// Note: we do not use `export * from ...` to help tree shakers, -// webpack verbose output hints that this should be useful -Object.defineProperty(exports, "__esModule", ({ value: true })); -// Convenience JSON typings and corresponding type guards -var json_typings_1 = __nccwpck_require__(70661); -Object.defineProperty(exports, "typeofJsonValue", ({ enumerable: true, get: function () { return json_typings_1.typeofJsonValue; } })); -Object.defineProperty(exports, "isJsonObject", ({ enumerable: true, get: function () { return json_typings_1.isJsonObject; } })); -// Base 64 encoding -var base64_1 = __nccwpck_require__(20196); -Object.defineProperty(exports, "base64decode", ({ enumerable: true, get: function () { return base64_1.base64decode; } })); -Object.defineProperty(exports, "base64encode", ({ enumerable: true, get: function () { return base64_1.base64encode; } })); -// UTF8 encoding -var protobufjs_utf8_1 = __nccwpck_require__(95290); -Object.defineProperty(exports, "utf8read", ({ enumerable: true, get: function () { return protobufjs_utf8_1.utf8read; } })); -// Binary format contracts, options for reading and writing, for example -var binary_format_contract_1 = __nccwpck_require__(84921); -Object.defineProperty(exports, "WireType", ({ enumerable: true, get: function () { return binary_format_contract_1.WireType; } })); -Object.defineProperty(exports, "mergeBinaryOptions", ({ enumerable: true, get: function () { return binary_format_contract_1.mergeBinaryOptions; } })); -Object.defineProperty(exports, "UnknownFieldHandler", ({ enumerable: true, get: function () { return binary_format_contract_1.UnknownFieldHandler; } })); -// Standard IBinaryReader implementation -var binary_reader_1 = __nccwpck_require__(65210); -Object.defineProperty(exports, "BinaryReader", ({ enumerable: true, get: function () { return binary_reader_1.BinaryReader; } })); -Object.defineProperty(exports, "binaryReadOptions", ({ enumerable: true, get: function () { return binary_reader_1.binaryReadOptions; } })); -// Standard IBinaryWriter implementation -var binary_writer_1 = __nccwpck_require__(44354); -Object.defineProperty(exports, "BinaryWriter", ({ enumerable: true, get: function () { return binary_writer_1.BinaryWriter; } })); -Object.defineProperty(exports, "binaryWriteOptions", ({ enumerable: true, get: function () { return binary_writer_1.binaryWriteOptions; } })); -// Int64 and UInt64 implementations required for the binary format -var pb_long_1 = __nccwpck_require__(47777); -Object.defineProperty(exports, "PbLong", ({ enumerable: true, get: function () { return pb_long_1.PbLong; } })); -Object.defineProperty(exports, "PbULong", ({ enumerable: true, get: function () { return pb_long_1.PbULong; } })); -// JSON format contracts, options for reading and writing, for example -var json_format_contract_1 = __nccwpck_require__(48139); -Object.defineProperty(exports, "jsonReadOptions", ({ enumerable: true, get: function () { return json_format_contract_1.jsonReadOptions; } })); -Object.defineProperty(exports, "jsonWriteOptions", ({ enumerable: true, get: function () { return json_format_contract_1.jsonWriteOptions; } })); -Object.defineProperty(exports, "mergeJsonOptions", ({ enumerable: true, get: function () { return json_format_contract_1.mergeJsonOptions; } })); -// Message type contract -var message_type_contract_1 = __nccwpck_require__(1682); -Object.defineProperty(exports, "MESSAGE_TYPE", ({ enumerable: true, get: function () { return message_type_contract_1.MESSAGE_TYPE; } })); -// Message type implementation via reflection -var message_type_1 = __nccwpck_require__(63664); -Object.defineProperty(exports, "MessageType", ({ enumerable: true, get: function () { return message_type_1.MessageType; } })); -// Reflection info, generated by the plugin, exposed to the user, used by reflection ops -var reflection_info_1 = __nccwpck_require__(21370); -Object.defineProperty(exports, "ScalarType", ({ enumerable: true, get: function () { return reflection_info_1.ScalarType; } })); -Object.defineProperty(exports, "LongType", ({ enumerable: true, get: function () { return reflection_info_1.LongType; } })); -Object.defineProperty(exports, "RepeatType", ({ enumerable: true, get: function () { return reflection_info_1.RepeatType; } })); -Object.defineProperty(exports, "normalizeFieldInfo", ({ enumerable: true, get: function () { return reflection_info_1.normalizeFieldInfo; } })); -Object.defineProperty(exports, "readFieldOptions", ({ enumerable: true, get: function () { return reflection_info_1.readFieldOptions; } })); -Object.defineProperty(exports, "readFieldOption", ({ enumerable: true, get: function () { return reflection_info_1.readFieldOption; } })); -Object.defineProperty(exports, "readMessageOption", ({ enumerable: true, get: function () { return reflection_info_1.readMessageOption; } })); -// Message operations via reflection -var reflection_type_check_1 = __nccwpck_require__(20903); -Object.defineProperty(exports, "ReflectionTypeCheck", ({ enumerable: true, get: function () { return reflection_type_check_1.ReflectionTypeCheck; } })); -var reflection_create_1 = __nccwpck_require__(60390); -Object.defineProperty(exports, "reflectionCreate", ({ enumerable: true, get: function () { return reflection_create_1.reflectionCreate; } })); -var reflection_scalar_default_1 = __nccwpck_require__(74863); -Object.defineProperty(exports, "reflectionScalarDefault", ({ enumerable: true, get: function () { return reflection_scalar_default_1.reflectionScalarDefault; } })); -var reflection_merge_partial_1 = __nccwpck_require__(7869); -Object.defineProperty(exports, "reflectionMergePartial", ({ enumerable: true, get: function () { return reflection_merge_partial_1.reflectionMergePartial; } })); -var reflection_equals_1 = __nccwpck_require__(39473); -Object.defineProperty(exports, "reflectionEquals", ({ enumerable: true, get: function () { return reflection_equals_1.reflectionEquals; } })); -var reflection_binary_reader_1 = __nccwpck_require__(91593); -Object.defineProperty(exports, "ReflectionBinaryReader", ({ enumerable: true, get: function () { return reflection_binary_reader_1.ReflectionBinaryReader; } })); -var reflection_binary_writer_1 = __nccwpck_require__(57170); -Object.defineProperty(exports, "ReflectionBinaryWriter", ({ enumerable: true, get: function () { return reflection_binary_writer_1.ReflectionBinaryWriter; } })); -var reflection_json_reader_1 = __nccwpck_require__(229); -Object.defineProperty(exports, "ReflectionJsonReader", ({ enumerable: true, get: function () { return reflection_json_reader_1.ReflectionJsonReader; } })); -var reflection_json_writer_1 = __nccwpck_require__(68980); -Object.defineProperty(exports, "ReflectionJsonWriter", ({ enumerable: true, get: function () { return reflection_json_writer_1.ReflectionJsonWriter; } })); -var reflection_contains_message_type_1 = __nccwpck_require__(67317); -Object.defineProperty(exports, "containsMessageType", ({ enumerable: true, get: function () { return reflection_contains_message_type_1.containsMessageType; } })); -// Oneof helpers -var oneof_1 = __nccwpck_require__(78531); -Object.defineProperty(exports, "isOneofGroup", ({ enumerable: true, get: function () { return oneof_1.isOneofGroup; } })); -Object.defineProperty(exports, "setOneofValue", ({ enumerable: true, get: function () { return oneof_1.setOneofValue; } })); -Object.defineProperty(exports, "getOneofValue", ({ enumerable: true, get: function () { return oneof_1.getOneofValue; } })); -Object.defineProperty(exports, "clearOneofValue", ({ enumerable: true, get: function () { return oneof_1.clearOneofValue; } })); -Object.defineProperty(exports, "getSelectedOneofValue", ({ enumerable: true, get: function () { return oneof_1.getSelectedOneofValue; } })); -// Enum object type guard and reflection util, may be interesting to the user. -var enum_object_1 = __nccwpck_require__(20085); -Object.defineProperty(exports, "listEnumValues", ({ enumerable: true, get: function () { return enum_object_1.listEnumValues; } })); -Object.defineProperty(exports, "listEnumNames", ({ enumerable: true, get: function () { return enum_object_1.listEnumNames; } })); -Object.defineProperty(exports, "listEnumNumbers", ({ enumerable: true, get: function () { return enum_object_1.listEnumNumbers; } })); -Object.defineProperty(exports, "isEnumObject", ({ enumerable: true, get: function () { return enum_object_1.isEnumObject; } })); -// lowerCamelCase() is exported for plugin, rpc-runtime and other rpc packages -var lower_camel_case_1 = __nccwpck_require__(34772); -Object.defineProperty(exports, "lowerCamelCase", ({ enumerable: true, get: function () { return lower_camel_case_1.lowerCamelCase; } })); -// assertion functions are exported for plugin, may also be useful to user -var assert_1 = __nccwpck_require__(54253); -Object.defineProperty(exports, "assert", ({ enumerable: true, get: function () { return assert_1.assert; } })); -Object.defineProperty(exports, "assertNever", ({ enumerable: true, get: function () { return assert_1.assertNever; } })); -Object.defineProperty(exports, "assertInt32", ({ enumerable: true, get: function () { return assert_1.assertInt32; } })); -Object.defineProperty(exports, "assertUInt32", ({ enumerable: true, get: function () { return assert_1.assertUInt32; } })); -Object.defineProperty(exports, "assertFloat32", ({ enumerable: true, get: function () { return assert_1.assertFloat32; } })); +// src/index.ts +var src_exports = {}; +__export(src_exports, { + Hash: () => Hash +}); +module.exports = __toCommonJS(src_exports); +var import_util_buffer_from = __nccwpck_require__(31381); +var import_util_utf8 = __nccwpck_require__(41895); +var import_buffer = __nccwpck_require__(14300); +var import_crypto = __nccwpck_require__(6113); +var Hash = class { + static { + __name(this, "Hash"); + } + constructor(algorithmIdentifier, secret) { + this.algorithmIdentifier = algorithmIdentifier; + this.secret = secret; + this.reset(); + } + update(toHash, encoding) { + this.hash.update((0, import_util_utf8.toUint8Array)(castSourceData(toHash, encoding))); + } + digest() { + return Promise.resolve(this.hash.digest()); + } + reset() { + this.hash = this.secret ? (0, import_crypto.createHmac)(this.algorithmIdentifier, castSourceData(this.secret)) : (0, import_crypto.createHash)(this.algorithmIdentifier); + } +}; +function castSourceData(toCast, encoding) { + if (import_buffer.Buffer.isBuffer(toCast)) { + return toCast; + } + if (typeof toCast === "string") { + return (0, import_util_buffer_from.fromString)(toCast, encoding); + } + if (ArrayBuffer.isView(toCast)) { + return (0, import_util_buffer_from.fromArrayBuffer)(toCast.buffer, toCast.byteOffset, toCast.byteLength); + } + return (0, import_util_buffer_from.fromArrayBuffer)(toCast); +} +__name(castSourceData, "castSourceData"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 48866: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +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); +// src/index.ts +var src_exports = {}; +__export(src_exports, { + fileStreamHasher: () => fileStreamHasher, + readableStreamHasher: () => readableStreamHasher +}); +module.exports = __toCommonJS(src_exports); -/***/ }), +// src/fileStreamHasher.ts +var import_fs = __nccwpck_require__(57147); -/***/ 48139: -/***/ ((__unused_webpack_module, exports) => { +// src/HashCalculator.ts +var import_util_utf8 = __nccwpck_require__(41895); +var import_stream = __nccwpck_require__(12781); +var HashCalculator = class extends import_stream.Writable { + constructor(hash, options) { + super(options); + this.hash = hash; + } + static { + __name(this, "HashCalculator"); + } + _write(chunk, encoding, callback) { + try { + this.hash.update((0, import_util_utf8.toUint8Array)(chunk)); + } catch (err) { + return callback(err); + } + callback(); + } +}; -"use strict"; +// src/fileStreamHasher.ts +var fileStreamHasher = /* @__PURE__ */ __name((hashCtor, fileStream) => new Promise((resolve, reject) => { + if (!isReadStream(fileStream)) { + reject(new Error("Unable to calculate hash for non-file streams.")); + return; + } + const fileStreamTee = (0, import_fs.createReadStream)(fileStream.path, { + start: fileStream.start, + end: fileStream.end + }); + const hash = new hashCtor(); + const hashCalculator = new HashCalculator(hash); + fileStreamTee.pipe(hashCalculator); + fileStreamTee.on("error", (err) => { + hashCalculator.end(); + reject(err); + }); + hashCalculator.on("error", reject); + hashCalculator.on("finish", function() { + hash.digest().then(resolve).catch(reject); + }); +}), "fileStreamHasher"); +var isReadStream = /* @__PURE__ */ __name((stream) => typeof stream.path === "string", "isReadStream"); + +// src/readableStreamHasher.ts +var readableStreamHasher = /* @__PURE__ */ __name((hashCtor, readableStream) => { + if (readableStream.readableFlowing !== null) { + throw new Error("Unable to calculate hash for flowing readable stream"); + } + const hash = new hashCtor(); + const hashCalculator = new HashCalculator(hash); + readableStream.pipe(hashCalculator); + return new Promise((resolve, reject) => { + readableStream.on("error", (err) => { + hashCalculator.end(); + reject(err); + }); + hashCalculator.on("error", reject); + hashCalculator.on("finish", () => { + hash.digest().then(resolve).catch(reject); + }); + }); +}, "readableStreamHasher"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.mergeJsonOptions = exports.jsonWriteOptions = exports.jsonReadOptions = void 0; -const defaultsWrite = { - emitDefaultValues: false, - enumAsInteger: false, - useProtoFieldName: false, - prettySpaces: 0, -}, defaultsRead = { - ignoreUnknownFields: false, -}; -/** - * Make options for reading JSON data from partial options. - */ -function jsonReadOptions(options) { - return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; -} -exports.jsonReadOptions = jsonReadOptions; -/** - * Make options for writing JSON data from partial options. - */ -function jsonWriteOptions(options) { - return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; -} -exports.jsonWriteOptions = jsonWriteOptions; -/** - * Merges JSON write or read options. Later values override earlier values. Type registries are merged. - */ -function mergeJsonOptions(a, b) { - var _a, _b; - let c = Object.assign(Object.assign({}, a), b); - c.typeRegistry = [...((_a = a === null || a === void 0 ? void 0 : a.typeRegistry) !== null && _a !== void 0 ? _a : []), ...((_b = b === null || b === void 0 ? void 0 : b.typeRegistry) !== null && _b !== void 0 ? _b : [])]; - return c; -} -exports.mergeJsonOptions = mergeJsonOptions; /***/ }), -/***/ 70661: -/***/ ((__unused_webpack_module, exports) => { +/***/ 10780: +/***/ ((module) => { -"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +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); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + isArrayBuffer: () => isArrayBuffer +}); +module.exports = __toCommonJS(src_exports); +var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isJsonObject = exports.typeofJsonValue = void 0; -/** - * Get the type of a JSON value. - * Distinguishes between array, null and object. - */ -function typeofJsonValue(value) { - let t = typeof value; - if (t == "object") { - if (Array.isArray(value)) - return "array"; - if (value === null) - return "null"; - } - return t; -} -exports.typeofJsonValue = typeofJsonValue; -/** - * Is this a JSON object (instead of an array or null)? - */ -function isJsonObject(value) { - return value !== null && typeof value == "object" && !Array.isArray(value); -} -exports.isJsonObject = isJsonObject; /***/ }), -/***/ 34772: -/***/ ((__unused_webpack_module, exports) => { +/***/ 82800: +/***/ ((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 __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +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); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.lowerCamelCase = void 0; -/** - * Converts snake_case to lowerCamelCase. - * - * Should behave like protoc: - * https://github.com/protocolbuffers/protobuf/blob/e8ae137c96444ea313485ed1118c5e43b2099cf1/src/google/protobuf/compiler/java/java_helpers.cc#L118 - */ -function lowerCamelCase(snakeCase) { - let capNext = false; - const sb = []; - for (let i = 0; i < snakeCase.length; i++) { - let next = snakeCase.charAt(i); - if (next == '_') { - capNext = true; - } - else if (/\d/.test(next)) { - sb.push(next); - capNext = true; - } - else if (capNext) { - sb.push(next.toUpperCase()); - capNext = false; - } - else if (i == 0) { - sb.push(next.toLowerCase()); - } - else { - sb.push(next); +// src/index.ts +var src_exports = {}; +__export(src_exports, { + contentLengthMiddleware: () => contentLengthMiddleware, + contentLengthMiddlewareOptions: () => contentLengthMiddlewareOptions, + getContentLengthPlugin: () => getContentLengthPlugin +}); +module.exports = __toCommonJS(src_exports); +var import_protocol_http = __nccwpck_require__(64418); +var CONTENT_LENGTH_HEADER = "content-length"; +function contentLengthMiddleware(bodyLengthChecker) { + return (next) => async (args) => { + const request = args.request; + if (import_protocol_http.HttpRequest.isInstance(request)) { + const { body, headers } = request; + if (body && Object.keys(headers).map((str) => str.toLowerCase()).indexOf(CONTENT_LENGTH_HEADER) === -1) { + try { + const length = bodyLengthChecker(body); + request.headers = { + ...request.headers, + [CONTENT_LENGTH_HEADER]: String(length) + }; + } catch (error) { } + } } - return sb.join(''); + return next({ + ...args, + request + }); + }; } -exports.lowerCamelCase = lowerCamelCase; - - -/***/ }), - -/***/ 1682: -/***/ ((__unused_webpack_module, exports) => { +__name(contentLengthMiddleware, "contentLengthMiddleware"); +var contentLengthMiddlewareOptions = { + step: "build", + tags: ["SET_CONTENT_LENGTH", "CONTENT_LENGTH"], + name: "contentLengthMiddleware", + override: true +}; +var getContentLengthPlugin = /* @__PURE__ */ __name((options) => ({ + applyToStack: (clientStack) => { + clientStack.add(contentLengthMiddleware(options.bodyLengthChecker), contentLengthMiddlewareOptions); + } +}), "getContentLengthPlugin"); +// Annotate the CommonJS export names for ESM import in node: -"use strict"; +0 && (0); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.MESSAGE_TYPE = void 0; -/** - * The symbol used as a key on message objects to store the message type. - * - * Note that this is an experimental feature - it is here to stay, but - * implementation details may change without notice. - */ -exports.MESSAGE_TYPE = Symbol.for("protobuf-ts/message-type"); /***/ }), -/***/ 63664: +/***/ 31518: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.MessageType = void 0; -const message_type_contract_1 = __nccwpck_require__(1682); -const reflection_info_1 = __nccwpck_require__(21370); -const reflection_type_check_1 = __nccwpck_require__(20903); -const reflection_json_reader_1 = __nccwpck_require__(229); -const reflection_json_writer_1 = __nccwpck_require__(68980); -const reflection_binary_reader_1 = __nccwpck_require__(91593); -const reflection_binary_writer_1 = __nccwpck_require__(57170); -const reflection_create_1 = __nccwpck_require__(60390); -const reflection_merge_partial_1 = __nccwpck_require__(7869); -const json_typings_1 = __nccwpck_require__(70661); -const json_format_contract_1 = __nccwpck_require__(48139); -const reflection_equals_1 = __nccwpck_require__(39473); -const binary_writer_1 = __nccwpck_require__(44354); -const binary_reader_1 = __nccwpck_require__(65210); -const baseDescriptors = Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})); -/** - * This standard message type provides reflection-based - * operations to work with a message. - */ -class MessageType { - constructor(name, fields, options) { - this.defaultCheckDepth = 16; - this.typeName = name; - this.fields = fields.map(reflection_info_1.normalizeFieldInfo); - this.options = options !== null && options !== void 0 ? options : {}; - this.messagePrototype = Object.create(null, Object.assign(Object.assign({}, baseDescriptors), { [message_type_contract_1.MESSAGE_TYPE]: { value: this } })); - this.refTypeCheck = new reflection_type_check_1.ReflectionTypeCheck(this); - this.refJsonReader = new reflection_json_reader_1.ReflectionJsonReader(this); - this.refJsonWriter = new reflection_json_writer_1.ReflectionJsonWriter(this); - this.refBinReader = new reflection_binary_reader_1.ReflectionBinaryReader(this); - this.refBinWriter = new reflection_binary_writer_1.ReflectionBinaryWriter(this); - } - create(value) { - let message = reflection_create_1.reflectionCreate(this); - if (value !== undefined) { - reflection_merge_partial_1.reflectionMergePartial(this, message, value); - } - return message; - } - /** - * Clone the message. - * - * Unknown fields are discarded. - */ - clone(message) { - let copy = this.create(); - reflection_merge_partial_1.reflectionMergePartial(this, copy, message); - return copy; - } - /** - * Determines whether two message of the same type have the same field values. - * Checks for deep equality, traversing repeated fields, oneof groups, maps - * and messages recursively. - * Will also return true if both messages are `undefined`. - */ - equals(a, b) { - return reflection_equals_1.reflectionEquals(this, a, b); - } - /** - * Is the given value assignable to our message type - * and contains no [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? - */ - is(arg, depth = this.defaultCheckDepth) { - return this.refTypeCheck.is(arg, depth, false); - } - /** - * Is the given value assignable to our message type, - * regardless of [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? - */ - isAssignable(arg, depth = this.defaultCheckDepth) { - return this.refTypeCheck.is(arg, depth, true); - } - /** - * Copy partial data into the target message. - */ - mergePartial(target, source) { - reflection_merge_partial_1.reflectionMergePartial(this, target, source); - } - /** - * Create a new message from binary format. - */ - fromBinary(data, options) { - let opt = binary_reader_1.binaryReadOptions(options); - return this.internalBinaryRead(opt.readerFactory(data), data.byteLength, opt); - } - /** - * Read a new message from a JSON value. - */ - fromJson(json, options) { - return this.internalJsonRead(json, json_format_contract_1.jsonReadOptions(options)); - } - /** - * Read a new message from a JSON string. - * This is equivalent to `T.fromJson(JSON.parse(json))`. - */ - fromJsonString(json, options) { - let value = JSON.parse(json); - return this.fromJson(value, options); - } - /** - * Write the message to canonical JSON value. - */ - toJson(message, options) { - return this.internalJsonWrite(message, json_format_contract_1.jsonWriteOptions(options)); - } - /** - * Convert the message to canonical JSON string. - * This is equivalent to `JSON.stringify(T.toJson(t))` - */ - toJsonString(message, options) { - var _a; - let value = this.toJson(message, options); - return JSON.stringify(value, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0); - } - /** - * Write the message to binary format. - */ - toBinary(message, options) { - let opt = binary_writer_1.binaryWriteOptions(options); - return this.internalBinaryWrite(message, opt.writerFactory(), opt).finish(); - } - /** - * This is an internal method. If you just want to read a message from - * JSON, use `fromJson()` or `fromJsonString()`. - * - * Reads JSON value and merges the fields into the target - * according to protobuf rules. If the target is omitted, - * a new instance is created first. - */ - internalJsonRead(json, options, target) { - if (json !== null && typeof json == "object" && !Array.isArray(json)) { - let message = target !== null && target !== void 0 ? target : this.create(); - this.refJsonReader.read(json, message, options); - return message; - } - throw new Error(`Unable to parse message ${this.typeName} from JSON ${json_typings_1.typeofJsonValue(json)}.`); - } - /** - * This is an internal method. If you just want to write a message - * to JSON, use `toJson()` or `toJsonString(). - * - * Writes JSON value and returns it. - */ - internalJsonWrite(message, options) { - return this.refJsonWriter.write(message, options); - } - /** - * This is an internal method. If you just want to write a message - * in binary format, use `toBinary()`. - * - * Serializes the message in binary format and appends it to the given - * writer. Returns passed writer. - */ - internalBinaryWrite(message, writer, options) { - this.refBinWriter.write(message, writer, options); - return writer; - } - /** - * This is an internal method. If you just want to read a message from - * binary data, use `fromBinary()`. - * - * Reads data from binary format and merges the fields into - * the target according to protobuf rules. If the target is - * omitted, a new instance is created first. - */ - internalBinaryRead(reader, length, options, target) { - let message = target !== null && target !== void 0 ? target : this.create(); - this.refBinReader.read(reader, message, options, length); - return message; - } -} -exports.MessageType = MessageType; +exports.getEndpointFromConfig = void 0; +const node_config_provider_1 = __nccwpck_require__(33461); +const getEndpointUrlConfig_1 = __nccwpck_require__(7574); +const getEndpointFromConfig = async (serviceId) => (0, node_config_provider_1.loadConfig)((0, getEndpointUrlConfig_1.getEndpointUrlConfig)(serviceId !== null && serviceId !== void 0 ? serviceId : ""))(); +exports.getEndpointFromConfig = getEndpointFromConfig; /***/ }), -/***/ 78531: -/***/ ((__unused_webpack_module, exports) => { +/***/ 7574: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getSelectedOneofValue = exports.clearOneofValue = exports.setUnknownOneofValue = exports.setOneofValue = exports.getOneofValue = exports.isOneofGroup = void 0; -/** - * Is the given value a valid oneof group? - * - * We represent protobuf `oneof` as algebraic data types (ADT) in generated - * code. But when working with messages of unknown type, the ADT does not - * help us. - * - * This type guard checks if the given object adheres to the ADT rules, which - * are as follows: - * - * 1) Must be an object. - * - * 2) Must have a "oneofKind" discriminator property. - * - * 3) If "oneofKind" is `undefined`, no member field is selected. The object - * must not have any other properties. - * - * 4) If "oneofKind" is a `string`, the member field with this name is - * selected. - * - * 5) If a member field is selected, the object must have a second property - * with this name. The property must not be `undefined`. - * - * 6) No extra properties are allowed. The object has either one property - * (no selection) or two properties (selection). - * - */ -function isOneofGroup(any) { - if (typeof any != 'object' || any === null || !any.hasOwnProperty('oneofKind')) { - return false; - } - switch (typeof any.oneofKind) { - case "string": - if (any[any.oneofKind] === undefined) - return false; - return Object.keys(any).length == 2; - case "undefined": - return Object.keys(any).length == 1; - default: - return false; - } -} -exports.isOneofGroup = isOneofGroup; -/** - * Returns the value of the given field in a oneof group. - */ -function getOneofValue(oneof, kind) { - return oneof[kind]; -} -exports.getOneofValue = getOneofValue; -function setOneofValue(oneof, kind, value) { - if (oneof.oneofKind !== undefined) { - delete oneof[oneof.oneofKind]; - } - oneof.oneofKind = kind; - if (value !== undefined) { - oneof[kind] = value; - } -} -exports.setOneofValue = setOneofValue; -function setUnknownOneofValue(oneof, kind, value) { - if (oneof.oneofKind !== undefined) { - delete oneof[oneof.oneofKind]; - } - oneof.oneofKind = kind; - if (value !== undefined && kind !== undefined) { - oneof[kind] = value; - } -} -exports.setUnknownOneofValue = setUnknownOneofValue; -/** - * Removes the selected field in a oneof group. - * - * Note that the recommended way to modify a oneof group is to set - * a new object: - * - * ```ts - * message.result = { oneofKind: undefined }; - * ``` - */ -function clearOneofValue(oneof) { - if (oneof.oneofKind !== undefined) { - delete oneof[oneof.oneofKind]; - } - oneof.oneofKind = undefined; -} -exports.clearOneofValue = clearOneofValue; -/** - * Returns the selected value of the given oneof group. - * - * Not that the recommended way to access a oneof group is to check - * the "oneofKind" property and let TypeScript narrow down the union - * type for you: - * - * ```ts - * if (message.result.oneofKind === "error") { - * message.result.error; // string - * } - * ``` - * - * In the rare case you just need the value, and do not care about - * which protobuf field is selected, you can use this function - * for convenience. - */ -function getSelectedOneofValue(oneof) { - if (oneof.oneofKind === undefined) { +exports.getEndpointUrlConfig = void 0; +const shared_ini_file_loader_1 = __nccwpck_require__(43507); +const ENV_ENDPOINT_URL = "AWS_ENDPOINT_URL"; +const CONFIG_ENDPOINT_URL = "endpoint_url"; +const getEndpointUrlConfig = (serviceId) => ({ + environmentVariableSelector: (env) => { + const serviceSuffixParts = serviceId.split(" ").map((w) => w.toUpperCase()); + const serviceEndpointUrl = env[[ENV_ENDPOINT_URL, ...serviceSuffixParts].join("_")]; + if (serviceEndpointUrl) + return serviceEndpointUrl; + const endpointUrl = env[ENV_ENDPOINT_URL]; + if (endpointUrl) + return endpointUrl; return undefined; - } - return oneof[oneof.oneofKind]; -} -exports.getSelectedOneofValue = getSelectedOneofValue; + }, + configFileSelector: (profile, config) => { + if (config && profile.services) { + const servicesSection = config[["services", profile.services].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)]; + if (servicesSection) { + const servicePrefixParts = serviceId.split(" ").map((w) => w.toLowerCase()); + const endpointUrl = servicesSection[[servicePrefixParts.join("_"), CONFIG_ENDPOINT_URL].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)]; + if (endpointUrl) + return endpointUrl; + } + } + const endpointUrl = profile[CONFIG_ENDPOINT_URL]; + if (endpointUrl) + return endpointUrl; + return undefined; + }, + default: undefined, +}); +exports.getEndpointUrlConfig = getEndpointUrlConfig; /***/ }), -/***/ 47777: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 82918: +/***/ ((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 __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +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); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.PbLong = exports.PbULong = exports.detectBi = void 0; -const goog_varint_1 = __nccwpck_require__(30433); -let BI; -function detectBi() { - const dv = new DataView(new ArrayBuffer(8)); - const ok = globalThis.BigInt !== undefined - && typeof dv.getBigInt64 === "function" - && typeof dv.getBigUint64 === "function" - && typeof dv.setBigInt64 === "function" - && typeof dv.setBigUint64 === "function"; - BI = ok ? { - MIN: BigInt("-9223372036854775808"), - MAX: BigInt("9223372036854775807"), - UMIN: BigInt("0"), - UMAX: BigInt("18446744073709551615"), - C: BigInt, - V: dv, - } : undefined; -} -exports.detectBi = detectBi; -detectBi(); -function assertBi(bi) { - if (!bi) - throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support"); -} -// used to validate from(string) input (when bigint is unavailable) -const RE_DECIMAL_STR = /^-?[0-9]+$/; -// constants for binary math -const TWO_PWR_32_DBL = 0x100000000; -const HALF_2_PWR_32 = 0x080000000; -// base class for PbLong and PbULong provides shared code -class SharedPbLong { - /** - * Create a new instance with the given bits. - */ - constructor(lo, hi) { - this.lo = lo | 0; - this.hi = hi | 0; - } - /** - * Is this instance equal to 0? - */ - isZero() { - return this.lo == 0 && this.hi == 0; - } - /** - * Convert to a native number. - */ - toNumber() { - let result = this.hi * TWO_PWR_32_DBL + (this.lo >>> 0); - if (!Number.isSafeInteger(result)) - throw new Error("cannot convert to safe number"); - return result; +// src/index.ts +var src_exports = {}; +__export(src_exports, { + endpointMiddleware: () => endpointMiddleware, + endpointMiddlewareOptions: () => endpointMiddlewareOptions, + getEndpointFromInstructions: () => getEndpointFromInstructions, + getEndpointPlugin: () => getEndpointPlugin, + resolveEndpointConfig: () => resolveEndpointConfig, + resolveParams: () => resolveParams, + toEndpointV1: () => toEndpointV1 +}); +module.exports = __toCommonJS(src_exports); + +// src/service-customizations/s3.ts +var resolveParamsForS3 = /* @__PURE__ */ __name(async (endpointParams) => { + const bucket = endpointParams?.Bucket || ""; + if (typeof endpointParams.Bucket === "string") { + endpointParams.Bucket = bucket.replace(/#/g, encodeURIComponent("#")).replace(/\?/g, encodeURIComponent("?")); + } + if (isArnBucketName(bucket)) { + if (endpointParams.ForcePathStyle === true) { + throw new Error("Path-style addressing cannot be used with ARN buckets"); } -} -/** - * 64-bit unsigned integer as two 32-bit values. - * Converts between `string`, `number` and `bigint` representations. - */ -class PbULong extends SharedPbLong { - /** - * Create instance from a `string`, `number` or `bigint`. - */ - static from(value) { - if (BI) - // noinspection FallThroughInSwitchStatementJS - switch (typeof value) { - case "string": - if (value == "0") - return this.ZERO; - if (value == "") - throw new Error('string is no integer'); - value = BI.C(value); - case "number": - if (value === 0) - return this.ZERO; - value = BI.C(value); - case "bigint": - if (!value) - return this.ZERO; - if (value < BI.UMIN) - throw new Error('signed value for ulong'); - if (value > BI.UMAX) - throw new Error('ulong too large'); - BI.V.setBigUint64(0, value, true); - return new PbULong(BI.V.getInt32(0, true), BI.V.getInt32(4, true)); - } - else - switch (typeof value) { - case "string": - if (value == "0") - return this.ZERO; - value = value.trim(); - if (!RE_DECIMAL_STR.test(value)) - throw new Error('string is no integer'); - let [minus, lo, hi] = goog_varint_1.int64fromString(value); - if (minus) - throw new Error('signed value for ulong'); - return new PbULong(lo, hi); - case "number": - if (value == 0) - return this.ZERO; - if (!Number.isSafeInteger(value)) - throw new Error('number is no integer'); - if (value < 0) - throw new Error('signed value for ulong'); - return new PbULong(value, value / TWO_PWR_32_DBL); - } - throw new Error('unknown value ' + typeof value); + } else if (!isDnsCompatibleBucketName(bucket) || bucket.indexOf(".") !== -1 && !String(endpointParams.Endpoint).startsWith("http:") || bucket.toLowerCase() !== bucket || bucket.length < 3) { + endpointParams.ForcePathStyle = true; + } + if (endpointParams.DisableMultiRegionAccessPoints) { + endpointParams.disableMultiRegionAccessPoints = true; + endpointParams.DisableMRAP = true; + } + return endpointParams; +}, "resolveParamsForS3"); +var DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/; +var IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/; +var DOTS_PATTERN = /\.\./; +var isDnsCompatibleBucketName = /* @__PURE__ */ __name((bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName), "isDnsCompatibleBucketName"); +var isArnBucketName = /* @__PURE__ */ __name((bucketName) => { + const [arn, partition, service, , , bucket] = bucketName.split(":"); + const isArn = arn === "arn" && bucketName.split(":").length >= 6; + const isValidArn = Boolean(isArn && partition && service && bucket); + if (isArn && !isValidArn) { + throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`); + } + return isValidArn; +}, "isArnBucketName"); + +// src/adaptors/createConfigValueProvider.ts +var createConfigValueProvider = /* @__PURE__ */ __name((configKey, canonicalEndpointParamKey, config) => { + const configProvider = /* @__PURE__ */ __name(async () => { + const configValue = config[configKey] ?? config[canonicalEndpointParamKey]; + if (typeof configValue === "function") { + return configValue(); } - /** - * Convert to decimal string. - */ - toString() { - return BI ? this.toBigInt().toString() : goog_varint_1.int64toString(this.lo, this.hi); + return configValue; + }, "configProvider"); + if (configKey === "credentialScope" || canonicalEndpointParamKey === "CredentialScope") { + return async () => { + const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; + const configValue = credentials?.credentialScope ?? credentials?.CredentialScope; + return configValue; + }; + } + if (configKey === "accountId" || canonicalEndpointParamKey === "AccountId") { + return async () => { + const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; + const configValue = credentials?.accountId ?? credentials?.AccountId; + return configValue; + }; + } + if (configKey === "endpoint" || canonicalEndpointParamKey === "endpoint") { + return async () => { + const endpoint = await configProvider(); + if (endpoint && typeof endpoint === "object") { + if ("url" in endpoint) { + return endpoint.url.href; + } + if ("hostname" in endpoint) { + const { protocol, hostname, port, path } = endpoint; + return `${protocol}//${hostname}${port ? ":" + port : ""}${path}`; + } + } + return endpoint; + }; + } + return configProvider; +}, "createConfigValueProvider"); + +// src/adaptors/getEndpointFromInstructions.ts +var import_getEndpointFromConfig = __nccwpck_require__(31518); + +// src/adaptors/toEndpointV1.ts +var import_url_parser = __nccwpck_require__(14681); +var toEndpointV1 = /* @__PURE__ */ __name((endpoint) => { + if (typeof endpoint === "object") { + if ("url" in endpoint) { + return (0, import_url_parser.parseUrl)(endpoint.url); } - /** - * Convert to native bigint. - */ - toBigInt() { - assertBi(BI); - BI.V.setInt32(0, this.lo, true); - BI.V.setInt32(4, this.hi, true); - return BI.V.getBigUint64(0, true); + return endpoint; + } + return (0, import_url_parser.parseUrl)(endpoint); +}, "toEndpointV1"); + +// src/adaptors/getEndpointFromInstructions.ts +var getEndpointFromInstructions = /* @__PURE__ */ __name(async (commandInput, instructionsSupplier, clientConfig, context) => { + if (!clientConfig.endpoint) { + let endpointFromConfig; + if (clientConfig.serviceConfiguredEndpoint) { + endpointFromConfig = await clientConfig.serviceConfiguredEndpoint(); + } else { + endpointFromConfig = await (0, import_getEndpointFromConfig.getEndpointFromConfig)(clientConfig.serviceId); } -} -exports.PbULong = PbULong; -/** - * ulong 0 singleton. - */ -PbULong.ZERO = new PbULong(0, 0); -/** - * 64-bit signed integer as two 32-bit values. - * Converts between `string`, `number` and `bigint` representations. - */ -class PbLong extends SharedPbLong { - /** - * Create instance from a `string`, `number` or `bigint`. - */ - static from(value) { - if (BI) - // noinspection FallThroughInSwitchStatementJS - switch (typeof value) { - case "string": - if (value == "0") - return this.ZERO; - if (value == "") - throw new Error('string is no integer'); - value = BI.C(value); - case "number": - if (value === 0) - return this.ZERO; - value = BI.C(value); - case "bigint": - if (!value) - return this.ZERO; - if (value < BI.MIN) - throw new Error('signed long too small'); - if (value > BI.MAX) - throw new Error('signed long too large'); - BI.V.setBigInt64(0, value, true); - return new PbLong(BI.V.getInt32(0, true), BI.V.getInt32(4, true)); - } - else - switch (typeof value) { - case "string": - if (value == "0") - return this.ZERO; - value = value.trim(); - if (!RE_DECIMAL_STR.test(value)) - throw new Error('string is no integer'); - let [minus, lo, hi] = goog_varint_1.int64fromString(value); - if (minus) { - if (hi > HALF_2_PWR_32 || (hi == HALF_2_PWR_32 && lo != 0)) - throw new Error('signed long too small'); - } - else if (hi >= HALF_2_PWR_32) - throw new Error('signed long too large'); - let pbl = new PbLong(lo, hi); - return minus ? pbl.negate() : pbl; - case "number": - if (value == 0) - return this.ZERO; - if (!Number.isSafeInteger(value)) - throw new Error('number is no integer'); - return value > 0 - ? new PbLong(value, value / TWO_PWR_32_DBL) - : new PbLong(-value, -value / TWO_PWR_32_DBL).negate(); - } - throw new Error('unknown value ' + typeof value); + if (endpointFromConfig) { + clientConfig.endpoint = () => Promise.resolve(toEndpointV1(endpointFromConfig)); } - /** - * Do we have a minus sign? - */ - isNegative() { - return (this.hi & HALF_2_PWR_32) !== 0; + } + const endpointParams = await resolveParams(commandInput, instructionsSupplier, clientConfig); + if (typeof clientConfig.endpointProvider !== "function") { + throw new Error("config.endpointProvider is not set."); + } + const endpoint = clientConfig.endpointProvider(endpointParams, context); + return endpoint; +}, "getEndpointFromInstructions"); +var resolveParams = /* @__PURE__ */ __name(async (commandInput, instructionsSupplier, clientConfig) => { + const endpointParams = {}; + const instructions = instructionsSupplier?.getEndpointParameterInstructions?.() || {}; + for (const [name, instruction] of Object.entries(instructions)) { + switch (instruction.type) { + case "staticContextParams": + endpointParams[name] = instruction.value; + break; + case "contextParams": + endpointParams[name] = commandInput[instruction.name]; + break; + case "clientContextParams": + case "builtInParams": + endpointParams[name] = await createConfigValueProvider(instruction.name, name, clientConfig)(); + break; + case "operationContextParams": + endpointParams[name] = instruction.get(commandInput); + break; + default: + throw new Error("Unrecognized endpoint parameter instruction: " + JSON.stringify(instruction)); } - /** - * Negate two's complement. - * Invert all the bits and add one to the result. - */ - negate() { - let hi = ~this.hi, lo = this.lo; - if (lo) - lo = ~lo + 1; - else - hi += 1; - return new PbLong(lo, hi); + } + if (Object.keys(instructions).length === 0) { + Object.assign(endpointParams, clientConfig); + } + if (String(clientConfig.serviceId).toLowerCase() === "s3") { + await resolveParamsForS3(endpointParams); + } + return endpointParams; +}, "resolveParams"); + +// src/endpointMiddleware.ts +var import_core = __nccwpck_require__(55829); +var import_util_middleware = __nccwpck_require__(2390); +var endpointMiddleware = /* @__PURE__ */ __name(({ + config, + instructions +}) => { + return (next, context) => async (args) => { + if (config.endpoint) { + (0, import_core.setFeature)(context, "ENDPOINT_OVERRIDE", "N"); } - /** - * Convert to decimal string. - */ - toString() { - if (BI) - return this.toBigInt().toString(); - if (this.isNegative()) { - let n = this.negate(); - return '-' + goog_varint_1.int64toString(n.lo, n.hi); + const endpoint = await getEndpointFromInstructions( + args.input, + { + getEndpointParameterInstructions() { + return instructions; } - return goog_varint_1.int64toString(this.lo, this.hi); + }, + { ...config }, + context + ); + context.endpointV2 = endpoint; + context.authSchemes = endpoint.properties?.authSchemes; + const authScheme = context.authSchemes?.[0]; + if (authScheme) { + context["signing_region"] = authScheme.signingRegion; + context["signing_service"] = authScheme.signingName; + const smithyContext = (0, import_util_middleware.getSmithyContext)(context); + const httpAuthOption = smithyContext?.selectedHttpAuthScheme?.httpAuthOption; + if (httpAuthOption) { + httpAuthOption.signingProperties = Object.assign( + httpAuthOption.signingProperties || {}, + { + signing_region: authScheme.signingRegion, + signingRegion: authScheme.signingRegion, + signing_service: authScheme.signingName, + signingName: authScheme.signingName, + signingRegionSet: authScheme.signingRegionSet + }, + authScheme.properties + ); + } } - /** - * Convert to native bigint. - */ - toBigInt() { - assertBi(BI); - BI.V.setInt32(0, this.lo, true); - BI.V.setInt32(4, this.hi, true); - return BI.V.getBigInt64(0, true); + return next({ + ...args + }); + }; +}, "endpointMiddleware"); + +// src/getEndpointPlugin.ts +var import_middleware_serde = __nccwpck_require__(81238); +var endpointMiddlewareOptions = { + step: "serialize", + tags: ["ENDPOINT_PARAMETERS", "ENDPOINT_V2", "ENDPOINT"], + name: "endpointV2Middleware", + override: true, + relation: "before", + toMiddleware: import_middleware_serde.serializerMiddlewareOption.name +}; +var getEndpointPlugin = /* @__PURE__ */ __name((config, instructions) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo( + endpointMiddleware({ + config, + instructions + }), + endpointMiddlewareOptions + ); + } +}), "getEndpointPlugin"); + +// src/resolveEndpointConfig.ts + +var import_getEndpointFromConfig2 = __nccwpck_require__(31518); +var resolveEndpointConfig = /* @__PURE__ */ __name((input) => { + const tls = input.tls ?? true; + const { endpoint, useDualstackEndpoint, useFipsEndpoint } = input; + const customEndpointProvider = endpoint != null ? async () => toEndpointV1(await (0, import_util_middleware.normalizeProvider)(endpoint)()) : void 0; + const isCustomEndpoint = !!endpoint; + const resolvedConfig = Object.assign(input, { + endpoint: customEndpointProvider, + tls, + isCustomEndpoint, + useDualstackEndpoint: (0, import_util_middleware.normalizeProvider)(useDualstackEndpoint ?? false), + useFipsEndpoint: (0, import_util_middleware.normalizeProvider)(useFipsEndpoint ?? false) + }); + let configuredEndpointPromise = void 0; + resolvedConfig.serviceConfiguredEndpoint = async () => { + if (input.serviceId && !configuredEndpointPromise) { + configuredEndpointPromise = (0, import_getEndpointFromConfig2.getEndpointFromConfig)(input.serviceId); } -} -exports.PbLong = PbLong; -/** - * long 0 singleton. - */ -PbLong.ZERO = new PbLong(0, 0); + return configuredEndpointPromise; + }; + return resolvedConfig; +}, "resolveEndpointConfig"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + /***/ }), -/***/ 95290: -/***/ ((__unused_webpack_module, exports) => { +/***/ 96039: +/***/ ((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 __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +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); -// Copyright (c) 2016, Daniel Wirtz All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// * Neither the name of its author, nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.utf8read = void 0; -const fromCharCodes = (chunk) => String.fromCharCode.apply(String, chunk); -/** - * @deprecated This function will no longer be exported with the next major - * release, since protobuf-ts has switch to TextDecoder API. If you need this - * function, please migrate to @protobufjs/utf8. For context, see - * https://github.com/timostamm/protobuf-ts/issues/184 - * - * Reads UTF8 bytes as a string. - * - * See [protobufjs / utf8](https://github.com/protobufjs/protobuf.js/blob/9893e35b854621cce64af4bf6be2cff4fb892796/lib/utf8/index.js#L40) - * - * Copyright (c) 2016, Daniel Wirtz - */ -function utf8read(bytes) { - if (bytes.length < 1) - return ""; - let pos = 0, // position in bytes - parts = [], chunk = [], i = 0, // char offset - t; // temporary - let len = bytes.length; - while (pos < len) { - t = bytes[pos++]; - if (t < 128) - chunk[i++] = t; - else if (t > 191 && t < 224) - chunk[i++] = (t & 31) << 6 | bytes[pos++] & 63; - else if (t > 239 && t < 365) { - t = ((t & 7) << 18 | (bytes[pos++] & 63) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63) - 0x10000; - chunk[i++] = 0xD800 + (t >> 10); - chunk[i++] = 0xDC00 + (t & 1023); - } - else - chunk[i++] = (t & 15) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63; - if (i > 8191) { - parts.push(fromCharCodes(chunk)); - i = 0; - } - } - if (parts.length) { - if (i) - parts.push(fromCharCodes(chunk.slice(0, i))); - return parts.join(""); +// src/index.ts +var src_exports = {}; +__export(src_exports, { + AdaptiveRetryStrategy: () => AdaptiveRetryStrategy, + CONFIG_MAX_ATTEMPTS: () => CONFIG_MAX_ATTEMPTS, + CONFIG_RETRY_MODE: () => CONFIG_RETRY_MODE, + ENV_MAX_ATTEMPTS: () => ENV_MAX_ATTEMPTS, + ENV_RETRY_MODE: () => ENV_RETRY_MODE, + NODE_MAX_ATTEMPT_CONFIG_OPTIONS: () => NODE_MAX_ATTEMPT_CONFIG_OPTIONS, + NODE_RETRY_MODE_CONFIG_OPTIONS: () => NODE_RETRY_MODE_CONFIG_OPTIONS, + StandardRetryStrategy: () => StandardRetryStrategy, + defaultDelayDecider: () => defaultDelayDecider, + defaultRetryDecider: () => defaultRetryDecider, + getOmitRetryHeadersPlugin: () => getOmitRetryHeadersPlugin, + getRetryAfterHint: () => getRetryAfterHint, + getRetryPlugin: () => getRetryPlugin, + omitRetryHeadersMiddleware: () => omitRetryHeadersMiddleware, + omitRetryHeadersMiddlewareOptions: () => omitRetryHeadersMiddlewareOptions, + resolveRetryConfig: () => resolveRetryConfig, + retryMiddleware: () => retryMiddleware, + retryMiddlewareOptions: () => retryMiddlewareOptions +}); +module.exports = __toCommonJS(src_exports); + +// src/AdaptiveRetryStrategy.ts + + +// src/StandardRetryStrategy.ts +var import_protocol_http = __nccwpck_require__(64418); + + +var import_uuid = __nccwpck_require__(7761); + +// src/defaultRetryQuota.ts +var import_util_retry = __nccwpck_require__(84902); +var getDefaultRetryQuota = /* @__PURE__ */ __name((initialRetryTokens, options) => { + const MAX_CAPACITY = initialRetryTokens; + const noRetryIncrement = options?.noRetryIncrement ?? import_util_retry.NO_RETRY_INCREMENT; + const retryCost = options?.retryCost ?? import_util_retry.RETRY_COST; + const timeoutRetryCost = options?.timeoutRetryCost ?? import_util_retry.TIMEOUT_RETRY_COST; + let availableCapacity = initialRetryTokens; + const getCapacityAmount = /* @__PURE__ */ __name((error) => error.name === "TimeoutError" ? timeoutRetryCost : retryCost, "getCapacityAmount"); + const hasRetryTokens = /* @__PURE__ */ __name((error) => getCapacityAmount(error) <= availableCapacity, "hasRetryTokens"); + const retrieveRetryTokens = /* @__PURE__ */ __name((error) => { + if (!hasRetryTokens(error)) { + throw new Error("No retry token available"); } - return fromCharCodes(chunk.slice(0, i)); -} -exports.utf8read = utf8read; + const capacityAmount = getCapacityAmount(error); + availableCapacity -= capacityAmount; + return capacityAmount; + }, "retrieveRetryTokens"); + const releaseRetryTokens = /* @__PURE__ */ __name((capacityReleaseAmount) => { + availableCapacity += capacityReleaseAmount ?? noRetryIncrement; + availableCapacity = Math.min(availableCapacity, MAX_CAPACITY); + }, "releaseRetryTokens"); + return Object.freeze({ + hasRetryTokens, + retrieveRetryTokens, + releaseRetryTokens + }); +}, "getDefaultRetryQuota"); +// src/delayDecider.ts -/***/ }), +var defaultDelayDecider = /* @__PURE__ */ __name((delayBase, attempts) => Math.floor(Math.min(import_util_retry.MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase)), "defaultDelayDecider"); -/***/ 91593: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// src/retryDecider.ts +var import_service_error_classification = __nccwpck_require__(6375); +var defaultRetryDecider = /* @__PURE__ */ __name((error) => { + if (!error) { + return false; + } + return (0, import_service_error_classification.isRetryableByTrait)(error) || (0, import_service_error_classification.isClockSkewError)(error) || (0, import_service_error_classification.isThrottlingError)(error) || (0, import_service_error_classification.isTransientError)(error); +}, "defaultRetryDecider"); -"use strict"; +// src/util.ts +var asSdkError = /* @__PURE__ */ __name((error) => { + if (error instanceof Error) + return error; + if (error instanceof Object) + return Object.assign(new Error(), error); + if (typeof error === "string") + return new Error(error); + return new Error(`AWS SDK error wrapper for ${error}`); +}, "asSdkError"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ReflectionBinaryReader = void 0; -const binary_format_contract_1 = __nccwpck_require__(84921); -const reflection_info_1 = __nccwpck_require__(21370); -const reflection_long_convert_1 = __nccwpck_require__(24612); -const reflection_scalar_default_1 = __nccwpck_require__(74863); -/** - * Reads proto3 messages in binary format using reflection information. - * - * https://developers.google.com/protocol-buffers/docs/encoding - */ -class ReflectionBinaryReader { - constructor(info) { - this.info = info; +// src/StandardRetryStrategy.ts +var StandardRetryStrategy = class { + constructor(maxAttemptsProvider, options) { + this.maxAttemptsProvider = maxAttemptsProvider; + this.mode = import_util_retry.RETRY_MODES.STANDARD; + this.retryDecider = options?.retryDecider ?? defaultRetryDecider; + this.delayDecider = options?.delayDecider ?? defaultDelayDecider; + this.retryQuota = options?.retryQuota ?? getDefaultRetryQuota(import_util_retry.INITIAL_RETRY_TOKENS); + } + static { + __name(this, "StandardRetryStrategy"); + } + shouldRetry(error, attempts, maxAttempts) { + return attempts < maxAttempts && this.retryDecider(error) && this.retryQuota.hasRetryTokens(error); + } + async getMaxAttempts() { + let maxAttempts; + try { + maxAttempts = await this.maxAttemptsProvider(); + } catch (error) { + maxAttempts = import_util_retry.DEFAULT_MAX_ATTEMPTS; } - prepare() { - var _a; - if (!this.fieldNoToField) { - const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; - this.fieldNoToField = new Map(fieldsInput.map(field => [field.no, field])); - } + return maxAttempts; + } + async retry(next, args, options) { + let retryTokenAmount; + let attempts = 0; + let totalDelay = 0; + const maxAttempts = await this.getMaxAttempts(); + const { request } = args; + if (import_protocol_http.HttpRequest.isInstance(request)) { + request.headers[import_util_retry.INVOCATION_ID_HEADER] = (0, import_uuid.v4)(); } - /** - * Reads a message from binary format into the target message. - * - * Repeated fields are appended. Map entries are added, overwriting - * existing keys. - * - * If a message field is already present, it will be merged with the - * new data. - */ - read(reader, message, options, length) { - this.prepare(); - const end = length === undefined ? reader.len : reader.pos + length; - while (reader.pos < end) { - // read the tag and find the field - const [fieldNo, wireType] = reader.tag(), field = this.fieldNoToField.get(fieldNo); - if (!field) { - let u = options.readUnknownField; - if (u == "throw") - throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.info.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? binary_format_contract_1.UnknownFieldHandler.onRead : u)(this.info.typeName, message, fieldNo, wireType, d); - continue; - } - // target object for the field we are reading - let target = message, repeated = field.repeat, localName = field.localName; - // if field is member of oneof ADT, use ADT as target - if (field.oneof) { - target = target[field.oneof]; - // if other oneof member selected, set new ADT - if (target.oneofKind !== localName) - target = message[field.oneof] = { - oneofKind: localName - }; - } - // we have handled oneof above, we just have read the value into `target[localName]` - switch (field.kind) { - case "scalar": - case "enum": - let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; - let L = field.kind == "scalar" ? field.L : undefined; - if (repeated) { - let arr = target[localName]; // safe to assume presence of array, oneof cannot contain repeated values - if (wireType == binary_format_contract_1.WireType.LengthDelimited && T != reflection_info_1.ScalarType.STRING && T != reflection_info_1.ScalarType.BYTES) { - let e = reader.uint32() + reader.pos; - while (reader.pos < e) - arr.push(this.scalar(reader, T, L)); - } - else - arr.push(this.scalar(reader, T, L)); - } - else - target[localName] = this.scalar(reader, T, L); - break; - case "message": - if (repeated) { - let arr = target[localName]; // safe to assume presence of array, oneof cannot contain repeated values - let msg = field.T().internalBinaryRead(reader, reader.uint32(), options); - arr.push(msg); - } - else - target[localName] = field.T().internalBinaryRead(reader, reader.uint32(), options, target[localName]); - break; - case "map": - let [mapKey, mapVal] = this.mapEntry(field, reader, options); - // safe to assume presence of map object, oneof cannot contain repeated values - target[localName][mapKey] = mapVal; - break; - } + while (true) { + try { + if (import_protocol_http.HttpRequest.isInstance(request)) { + request.headers[import_util_retry.REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; } - } - /** - * Read a map field, expecting key field = 1, value field = 2 - */ - mapEntry(field, reader, options) { - let length = reader.uint32(); - let end = reader.pos + length; - let key = undefined; // javascript only allows number or string for object properties - let val = undefined; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case 1: - if (field.K == reflection_info_1.ScalarType.BOOL) - key = reader.bool().toString(); - else - // long types are read as string, number types are okay as number - key = this.scalar(reader, field.K, reflection_info_1.LongType.STRING); - break; - case 2: - switch (field.V.kind) { - case "scalar": - val = this.scalar(reader, field.V.T, field.V.L); - break; - case "enum": - val = reader.int32(); - break; - case "message": - val = field.V.T().internalBinaryRead(reader, reader.uint32(), options); - break; - } - break; - default: - throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) in map entry for ${this.info.typeName}#${field.name}`); - } + if (options?.beforeRequest) { + await options.beforeRequest(); } - if (key === undefined) { - let keyRaw = reflection_scalar_default_1.reflectionScalarDefault(field.K); - key = field.K == reflection_info_1.ScalarType.BOOL ? keyRaw.toString() : keyRaw; + const { response, output } = await next(args); + if (options?.afterRequest) { + options.afterRequest(response); } - if (val === undefined) - switch (field.V.kind) { - case "scalar": - val = reflection_scalar_default_1.reflectionScalarDefault(field.V.T, field.V.L); - break; - case "enum": - val = 0; - break; - case "message": - val = field.V.T().create(); - break; - } - return [key, val]; - } - scalar(reader, type, longType) { - switch (type) { - case reflection_info_1.ScalarType.INT32: - return reader.int32(); - case reflection_info_1.ScalarType.STRING: - return reader.string(); - case reflection_info_1.ScalarType.BOOL: - return reader.bool(); - case reflection_info_1.ScalarType.DOUBLE: - return reader.double(); - case reflection_info_1.ScalarType.FLOAT: - return reader.float(); - case reflection_info_1.ScalarType.INT64: - return reflection_long_convert_1.reflectionLongConvert(reader.int64(), longType); - case reflection_info_1.ScalarType.UINT64: - return reflection_long_convert_1.reflectionLongConvert(reader.uint64(), longType); - case reflection_info_1.ScalarType.FIXED64: - return reflection_long_convert_1.reflectionLongConvert(reader.fixed64(), longType); - case reflection_info_1.ScalarType.FIXED32: - return reader.fixed32(); - case reflection_info_1.ScalarType.BYTES: - return reader.bytes(); - case reflection_info_1.ScalarType.UINT32: - return reader.uint32(); - case reflection_info_1.ScalarType.SFIXED32: - return reader.sfixed32(); - case reflection_info_1.ScalarType.SFIXED64: - return reflection_long_convert_1.reflectionLongConvert(reader.sfixed64(), longType); - case reflection_info_1.ScalarType.SINT32: - return reader.sint32(); - case reflection_info_1.ScalarType.SINT64: - return reflection_long_convert_1.reflectionLongConvert(reader.sint64(), longType); + this.retryQuota.releaseRetryTokens(retryTokenAmount); + output.$metadata.attempts = attempts + 1; + output.$metadata.totalRetryDelay = totalDelay; + return { response, output }; + } catch (e) { + const err = asSdkError(e); + attempts++; + if (this.shouldRetry(err, attempts, maxAttempts)) { + retryTokenAmount = this.retryQuota.retrieveRetryTokens(err); + const delayFromDecider = this.delayDecider( + (0, import_service_error_classification.isThrottlingError)(err) ? import_util_retry.THROTTLING_RETRY_DELAY_BASE : import_util_retry.DEFAULT_RETRY_DELAY_BASE, + attempts + ); + const delayFromResponse = getDelayFromRetryAfterHeader(err.$response); + const delay = Math.max(delayFromResponse || 0, delayFromDecider); + totalDelay += delay; + await new Promise((resolve) => setTimeout(resolve, delay)); + continue; + } + if (!err.$metadata) { + err.$metadata = {}; } + err.$metadata.attempts = attempts; + err.$metadata.totalRetryDelay = totalDelay; + throw err; + } } -} -exports.ReflectionBinaryReader = ReflectionBinaryReader; - - -/***/ }), + } +}; +var getDelayFromRetryAfterHeader = /* @__PURE__ */ __name((response) => { + if (!import_protocol_http.HttpResponse.isInstance(response)) + return; + const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === "retry-after"); + if (!retryAfterHeaderName) + return; + const retryAfter = response.headers[retryAfterHeaderName]; + const retryAfterSeconds = Number(retryAfter); + if (!Number.isNaN(retryAfterSeconds)) + return retryAfterSeconds * 1e3; + const retryAfterDate = new Date(retryAfter); + return retryAfterDate.getTime() - Date.now(); +}, "getDelayFromRetryAfterHeader"); -/***/ 57170: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// src/AdaptiveRetryStrategy.ts +var AdaptiveRetryStrategy = class extends StandardRetryStrategy { + static { + __name(this, "AdaptiveRetryStrategy"); + } + constructor(maxAttemptsProvider, options) { + const { rateLimiter, ...superOptions } = options ?? {}; + super(maxAttemptsProvider, superOptions); + this.rateLimiter = rateLimiter ?? new import_util_retry.DefaultRateLimiter(); + this.mode = import_util_retry.RETRY_MODES.ADAPTIVE; + } + async retry(next, args) { + return super.retry(next, args, { + beforeRequest: async () => { + return this.rateLimiter.getSendToken(); + }, + afterRequest: (response) => { + this.rateLimiter.updateClientSendingRate(response); + } + }); + } +}; -"use strict"; +// src/configurations.ts +var import_util_middleware = __nccwpck_require__(2390); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ReflectionBinaryWriter = void 0; -const binary_format_contract_1 = __nccwpck_require__(84921); -const reflection_info_1 = __nccwpck_require__(21370); -const assert_1 = __nccwpck_require__(54253); -const pb_long_1 = __nccwpck_require__(47777); -/** - * Writes proto3 messages in binary format using reflection information. - * - * https://developers.google.com/protocol-buffers/docs/encoding - */ -class ReflectionBinaryWriter { - constructor(info) { - this.info = info; - } - prepare() { - if (!this.fields) { - const fieldsInput = this.info.fields ? this.info.fields.concat() : []; - this.fields = fieldsInput.sort((a, b) => a.no - b.no); - } +var ENV_MAX_ATTEMPTS = "AWS_MAX_ATTEMPTS"; +var CONFIG_MAX_ATTEMPTS = "max_attempts"; +var NODE_MAX_ATTEMPT_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => { + const value = env[ENV_MAX_ATTEMPTS]; + if (!value) + return void 0; + const maxAttempt = parseInt(value); + if (Number.isNaN(maxAttempt)) { + throw new Error(`Environment variable ${ENV_MAX_ATTEMPTS} mast be a number, got "${value}"`); } - /** - * Writes the message to binary format. - */ - write(message, writer, options) { - this.prepare(); - for (const field of this.fields) { - let value, // this will be our field value, whether it is member of a oneof or not - emitDefault, // whether we emit the default value (only true for oneof members) - repeated = field.repeat, localName = field.localName; - // handle oneof ADT - if (field.oneof) { - const group = message[field.oneof]; - if (group.oneofKind !== localName) - continue; // if field is not selected, skip - value = group[localName]; - emitDefault = true; - } - else { - value = message[localName]; - emitDefault = false; - } - // we have handled oneof above. we just have to honor `emitDefault`. - switch (field.kind) { - case "scalar": - case "enum": - let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; - if (repeated) { - assert_1.assert(Array.isArray(value)); - if (repeated == reflection_info_1.RepeatType.PACKED) - this.packed(writer, T, field.no, value); - else - for (const item of value) - this.scalar(writer, T, field.no, item, true); - } - else if (value === undefined) - assert_1.assert(field.opt); - else - this.scalar(writer, T, field.no, value, emitDefault || field.opt); - break; - case "message": - if (repeated) { - assert_1.assert(Array.isArray(value)); - for (const item of value) - this.message(writer, options, field.T(), field.no, item); - } - else { - this.message(writer, options, field.T(), field.no, value); - } - break; - case "map": - assert_1.assert(typeof value == 'object' && value !== null); - for (const [key, val] of Object.entries(value)) - this.mapEntry(writer, options, field, key, val); - break; - } - } - let u = options.writeUnknownFields; - if (u !== false) - (u === true ? binary_format_contract_1.UnknownFieldHandler.onWrite : u)(this.info.typeName, message, writer); + return maxAttempt; + }, + configFileSelector: (profile) => { + const value = profile[CONFIG_MAX_ATTEMPTS]; + if (!value) + return void 0; + const maxAttempt = parseInt(value); + if (Number.isNaN(maxAttempt)) { + throw new Error(`Shared config file entry ${CONFIG_MAX_ATTEMPTS} mast be a number, got "${value}"`); } - mapEntry(writer, options, field, key, value) { - writer.tag(field.no, binary_format_contract_1.WireType.LengthDelimited); - writer.fork(); - // javascript only allows number or string for object properties - // we convert from our representation to the protobuf type - let keyValue = key; - switch (field.K) { - case reflection_info_1.ScalarType.INT32: - case reflection_info_1.ScalarType.FIXED32: - case reflection_info_1.ScalarType.UINT32: - case reflection_info_1.ScalarType.SFIXED32: - case reflection_info_1.ScalarType.SINT32: - keyValue = Number.parseInt(key); - break; - case reflection_info_1.ScalarType.BOOL: - assert_1.assert(key == 'true' || key == 'false'); - keyValue = key == 'true'; - break; - } - // write key, expecting key field number = 1 - this.scalar(writer, field.K, 1, keyValue, true); - // write value, expecting value field number = 2 - switch (field.V.kind) { - case 'scalar': - this.scalar(writer, field.V.T, 2, value, true); - break; - case 'enum': - this.scalar(writer, reflection_info_1.ScalarType.INT32, 2, value, true); - break; - case 'message': - this.message(writer, options, field.V.T(), 2, value); - break; - } - writer.join(); + return maxAttempt; + }, + default: import_util_retry.DEFAULT_MAX_ATTEMPTS +}; +var resolveRetryConfig = /* @__PURE__ */ __name((input) => { + const { retryStrategy, retryMode: _retryMode, maxAttempts: _maxAttempts } = input; + const maxAttempts = (0, import_util_middleware.normalizeProvider)(_maxAttempts ?? import_util_retry.DEFAULT_MAX_ATTEMPTS); + return Object.assign(input, { + maxAttempts, + retryStrategy: async () => { + if (retryStrategy) { + return retryStrategy; + } + const retryMode = await (0, import_util_middleware.normalizeProvider)(_retryMode)(); + if (retryMode === import_util_retry.RETRY_MODES.ADAPTIVE) { + return new import_util_retry.AdaptiveRetryStrategy(maxAttempts); + } + return new import_util_retry.StandardRetryStrategy(maxAttempts); } - message(writer, options, handler, fieldNo, value) { - if (value === undefined) - return; - handler.internalBinaryWrite(value, writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited).fork(), options); - writer.join(); + }); +}, "resolveRetryConfig"); +var ENV_RETRY_MODE = "AWS_RETRY_MODE"; +var CONFIG_RETRY_MODE = "retry_mode"; +var NODE_RETRY_MODE_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => env[ENV_RETRY_MODE], + configFileSelector: (profile) => profile[CONFIG_RETRY_MODE], + default: import_util_retry.DEFAULT_RETRY_MODE +}; + +// src/omitRetryHeadersMiddleware.ts + + +var omitRetryHeadersMiddleware = /* @__PURE__ */ __name(() => (next) => async (args) => { + const { request } = args; + if (import_protocol_http.HttpRequest.isInstance(request)) { + delete request.headers[import_util_retry.INVOCATION_ID_HEADER]; + delete request.headers[import_util_retry.REQUEST_HEADER]; + } + return next(args); +}, "omitRetryHeadersMiddleware"); +var omitRetryHeadersMiddlewareOptions = { + name: "omitRetryHeadersMiddleware", + tags: ["RETRY", "HEADERS", "OMIT_RETRY_HEADERS"], + relation: "before", + toMiddleware: "awsAuthMiddleware", + override: true +}; +var getOmitRetryHeadersPlugin = /* @__PURE__ */ __name((options) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(omitRetryHeadersMiddleware(), omitRetryHeadersMiddlewareOptions); + } +}), "getOmitRetryHeadersPlugin"); + +// src/retryMiddleware.ts + + +var import_smithy_client = __nccwpck_require__(63570); + + +var import_isStreamingPayload = __nccwpck_require__(18977); +var retryMiddleware = /* @__PURE__ */ __name((options) => (next, context) => async (args) => { + let retryStrategy = await options.retryStrategy(); + const maxAttempts = await options.maxAttempts(); + if (isRetryStrategyV2(retryStrategy)) { + retryStrategy = retryStrategy; + let retryToken = await retryStrategy.acquireInitialRetryToken(context["partition_id"]); + let lastError = new Error(); + let attempts = 0; + let totalRetryDelay = 0; + const { request } = args; + const isRequest = import_protocol_http.HttpRequest.isInstance(request); + if (isRequest) { + request.headers[import_util_retry.INVOCATION_ID_HEADER] = (0, import_uuid.v4)(); } - /** - * Write a single scalar value. - */ - scalar(writer, type, fieldNo, value, emitDefault) { - let [wireType, method, isDefault] = this.scalarInfo(type, value); - if (!isDefault || emitDefault) { - writer.tag(fieldNo, wireType); - writer[method](value); + while (true) { + try { + if (isRequest) { + request.headers[import_util_retry.REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; } - } - /** - * Write an array of scalar values in packed format. - */ - packed(writer, type, fieldNo, value) { - if (!value.length) - return; - assert_1.assert(type !== reflection_info_1.ScalarType.BYTES && type !== reflection_info_1.ScalarType.STRING); - // write tag - writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited); - // begin length-delimited - writer.fork(); - // write values without tags - let [, method,] = this.scalarInfo(type); - for (let i = 0; i < value.length; i++) - writer[method](value[i]); - // end length delimited - writer.join(); - } - /** - * Get information for writing a scalar value. - * - * Returns tuple: - * [0]: appropriate WireType - * [1]: name of the appropriate method of IBinaryWriter - * [2]: whether the given value is a default value - * - * If argument `value` is omitted, [2] is always false. - */ - scalarInfo(type, value) { - let t = binary_format_contract_1.WireType.Varint; - let m; - let i = value === undefined; - let d = value === 0; - switch (type) { - case reflection_info_1.ScalarType.INT32: - m = "int32"; - break; - case reflection_info_1.ScalarType.STRING: - d = i || !value.length; - t = binary_format_contract_1.WireType.LengthDelimited; - m = "string"; - break; - case reflection_info_1.ScalarType.BOOL: - d = value === false; - m = "bool"; - break; - case reflection_info_1.ScalarType.UINT32: - m = "uint32"; - break; - case reflection_info_1.ScalarType.DOUBLE: - t = binary_format_contract_1.WireType.Bit64; - m = "double"; - break; - case reflection_info_1.ScalarType.FLOAT: - t = binary_format_contract_1.WireType.Bit32; - m = "float"; - break; - case reflection_info_1.ScalarType.INT64: - d = i || pb_long_1.PbLong.from(value).isZero(); - m = "int64"; - break; - case reflection_info_1.ScalarType.UINT64: - d = i || pb_long_1.PbULong.from(value).isZero(); - m = "uint64"; - break; - case reflection_info_1.ScalarType.FIXED64: - d = i || pb_long_1.PbULong.from(value).isZero(); - t = binary_format_contract_1.WireType.Bit64; - m = "fixed64"; - break; - case reflection_info_1.ScalarType.BYTES: - d = i || !value.byteLength; - t = binary_format_contract_1.WireType.LengthDelimited; - m = "bytes"; - break; - case reflection_info_1.ScalarType.FIXED32: - t = binary_format_contract_1.WireType.Bit32; - m = "fixed32"; - break; - case reflection_info_1.ScalarType.SFIXED32: - t = binary_format_contract_1.WireType.Bit32; - m = "sfixed32"; - break; - case reflection_info_1.ScalarType.SFIXED64: - d = i || pb_long_1.PbLong.from(value).isZero(); - t = binary_format_contract_1.WireType.Bit64; - m = "sfixed64"; - break; - case reflection_info_1.ScalarType.SINT32: - m = "sint32"; - break; - case reflection_info_1.ScalarType.SINT64: - d = i || pb_long_1.PbLong.from(value).isZero(); - m = "sint64"; - break; + const { response, output } = await next(args); + retryStrategy.recordSuccess(retryToken); + output.$metadata.attempts = attempts + 1; + output.$metadata.totalRetryDelay = totalRetryDelay; + return { response, output }; + } catch (e) { + const retryErrorInfo = getRetryErrorInfo(e); + lastError = asSdkError(e); + if (isRequest && (0, import_isStreamingPayload.isStreamingPayload)(request)) { + (context.logger instanceof import_smithy_client.NoOpLogger ? console : context.logger)?.warn( + "An error was encountered in a non-retryable streaming request." + ); + throw lastError; } - return [t, m, i || d]; + try { + retryToken = await retryStrategy.refreshRetryTokenForRetry(retryToken, retryErrorInfo); + } catch (refreshError) { + if (!lastError.$metadata) { + lastError.$metadata = {}; + } + lastError.$metadata.attempts = attempts + 1; + lastError.$metadata.totalRetryDelay = totalRetryDelay; + throw lastError; + } + attempts = retryToken.getRetryCount(); + const delay = retryToken.getRetryDelay(); + totalRetryDelay += delay; + await new Promise((resolve) => setTimeout(resolve, delay)); + } } -} -exports.ReflectionBinaryWriter = ReflectionBinaryWriter; + } else { + retryStrategy = retryStrategy; + if (retryStrategy?.mode) + context.userAgent = [...context.userAgent || [], ["cfg/retry-mode", retryStrategy.mode]]; + return retryStrategy.retry(next, args); + } +}, "retryMiddleware"); +var isRetryStrategyV2 = /* @__PURE__ */ __name((retryStrategy) => typeof retryStrategy.acquireInitialRetryToken !== "undefined" && typeof retryStrategy.refreshRetryTokenForRetry !== "undefined" && typeof retryStrategy.recordSuccess !== "undefined", "isRetryStrategyV2"); +var getRetryErrorInfo = /* @__PURE__ */ __name((error) => { + const errorInfo = { + error, + errorType: getRetryErrorType(error) + }; + const retryAfterHint = getRetryAfterHint(error.$response); + if (retryAfterHint) { + errorInfo.retryAfterHint = retryAfterHint; + } + return errorInfo; +}, "getRetryErrorInfo"); +var getRetryErrorType = /* @__PURE__ */ __name((error) => { + if ((0, import_service_error_classification.isThrottlingError)(error)) + return "THROTTLING"; + if ((0, import_service_error_classification.isTransientError)(error)) + return "TRANSIENT"; + if ((0, import_service_error_classification.isServerError)(error)) + return "SERVER_ERROR"; + return "CLIENT_ERROR"; +}, "getRetryErrorType"); +var retryMiddlewareOptions = { + name: "retryMiddleware", + tags: ["RETRY"], + step: "finalizeRequest", + priority: "high", + override: true +}; +var getRetryPlugin = /* @__PURE__ */ __name((options) => ({ + applyToStack: (clientStack) => { + clientStack.add(retryMiddleware(options), retryMiddlewareOptions); + } +}), "getRetryPlugin"); +var getRetryAfterHint = /* @__PURE__ */ __name((response) => { + if (!import_protocol_http.HttpResponse.isInstance(response)) + return; + const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === "retry-after"); + if (!retryAfterHeaderName) + return; + const retryAfter = response.headers[retryAfterHeaderName]; + const retryAfterSeconds = Number(retryAfter); + if (!Number.isNaN(retryAfterSeconds)) + return new Date(retryAfterSeconds * 1e3); + const retryAfterDate = new Date(retryAfter); + return retryAfterDate; +}, "getRetryAfterHint"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 18977: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isStreamingPayload = void 0; +const stream_1 = __nccwpck_require__(12781); +const isStreamingPayload = (request) => (request === null || request === void 0 ? void 0 : request.body) instanceof stream_1.Readable || + (typeof ReadableStream !== "undefined" && (request === null || request === void 0 ? void 0 : request.body) instanceof ReadableStream); +exports.isStreamingPayload = isStreamingPayload; + + +/***/ }), + +/***/ 7761: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "NIL", ({ + enumerable: true, + get: function () { + return _nil.default; + } +})); +Object.defineProperty(exports, "parse", ({ + enumerable: true, + get: function () { + return _parse.default; + } +})); +Object.defineProperty(exports, "stringify", ({ + enumerable: true, + get: function () { + return _stringify.default; + } +})); +Object.defineProperty(exports, "v1", ({ + enumerable: true, + get: function () { + return _v.default; + } +})); +Object.defineProperty(exports, "v3", ({ + enumerable: true, + get: function () { + return _v2.default; + } +})); +Object.defineProperty(exports, "v4", ({ + enumerable: true, + get: function () { + return _v3.default; + } +})); +Object.defineProperty(exports, "v5", ({ + enumerable: true, + get: function () { + return _v4.default; + } +})); +Object.defineProperty(exports, "validate", ({ + enumerable: true, + get: function () { + return _validate.default; + } +})); +Object.defineProperty(exports, "version", ({ + enumerable: true, + get: function () { + return _version.default; + } +})); + +var _v = _interopRequireDefault(__nccwpck_require__(36310)); + +var _v2 = _interopRequireDefault(__nccwpck_require__(9465)); + +var _v3 = _interopRequireDefault(__nccwpck_require__(86001)); + +var _v4 = _interopRequireDefault(__nccwpck_require__(38310)); +var _nil = _interopRequireDefault(__nccwpck_require__(3436)); + +var _version = _interopRequireDefault(__nccwpck_require__(17780)); + +var _validate = _interopRequireDefault(__nccwpck_require__(66992)); + +var _stringify = _interopRequireDefault(__nccwpck_require__(79618)); + +var _parse = _interopRequireDefault(__nccwpck_require__(40086)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /***/ }), -/***/ 67317: +/***/ 11380: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.containsMessageType = void 0; -const message_type_contract_1 = __nccwpck_require__(1682); -/** - * Check if the provided object is a proto message. - * - * Note that this is an experimental feature - it is here to stay, but - * implementation details may change without notice. - */ -function containsMessageType(msg) { - return msg[message_type_contract_1.MESSAGE_TYPE] != null; + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function md5(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return _crypto.default.createHash('md5').update(bytes).digest(); } -exports.containsMessageType = containsMessageType; +var _default = md5; +exports["default"] = _default; /***/ }), -/***/ 60390: +/***/ 34672: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.reflectionCreate = void 0; -const reflection_scalar_default_1 = __nccwpck_require__(74863); -const message_type_contract_1 = __nccwpck_require__(1682); -/** - * Creates an instance of the generic message, using the field - * information. - */ -function reflectionCreate(type) { - /** - * This ternary can be removed in the next major version. - * The `Object.create()` code path utilizes a new `messagePrototype` - * property on the `IMessageType` which has this same `MESSAGE_TYPE` - * non-enumerable property on it. Doing it this way means that we only - * pay the cost of `Object.defineProperty()` once per `IMessageType` - * class of once per "instance". The falsy code path is only provided - * for backwards compatibility in cases where the runtime library is - * updated without also updating the generated code. - */ - const msg = type.messagePrototype - ? Object.create(type.messagePrototype) - : Object.defineProperty({}, message_type_contract_1.MESSAGE_TYPE, { value: type }); - for (let field of type.fields) { - let name = field.localName; - if (field.opt) - continue; - if (field.oneof) - msg[field.oneof] = { oneofKind: undefined }; - else if (field.repeat) - msg[name] = []; - else - switch (field.kind) { - case "scalar": - msg[name] = reflection_scalar_default_1.reflectionScalarDefault(field.T, field.L); - break; - case "enum": - // we require 0 to be default value for all enums - msg[name] = 0; - break; - case "map": - msg[name] = {}; - break; - } - } - return msg; -} -exports.reflectionCreate = reflectionCreate; +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var _default = { + randomUUID: _crypto.default.randomUUID +}; +exports["default"] = _default; /***/ }), -/***/ 39473: +/***/ 3436: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _default = '00000000-0000-0000-0000-000000000000'; +exports["default"] = _default; + +/***/ }), + +/***/ 40086: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.reflectionEquals = void 0; -const reflection_info_1 = __nccwpck_require__(21370); -/** - * Determines whether two message of the same type have the same field values. - * Checks for deep equality, traversing repeated fields, oneof groups, maps - * and messages recursively. - * Will also return true if both messages are `undefined`. - */ -function reflectionEquals(info, a, b) { - if (a === b) - return true; - if (!a || !b) - return false; - for (let field of info.fields) { - let localName = field.localName; - let val_a = field.oneof ? a[field.oneof][localName] : a[localName]; - let val_b = field.oneof ? b[field.oneof][localName] : b[localName]; - switch (field.kind) { - case "enum": - case "scalar": - let t = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; - if (!(field.repeat - ? repeatedPrimitiveEq(t, val_a, val_b) - : primitiveEq(t, val_a, val_b))) - return false; - break; - case "map": - if (!(field.V.kind == "message" - ? repeatedMsgEq(field.V.T(), objectValues(val_a), objectValues(val_b)) - : repeatedPrimitiveEq(field.V.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.V.T, objectValues(val_a), objectValues(val_b)))) - return false; - break; - case "message": - let T = field.T(); - if (!(field.repeat - ? repeatedMsgEq(T, val_a, val_b) - : T.equals(val_a, val_b))) - return false; - break; - } - } - return true; -} -exports.reflectionEquals = reflectionEquals; -const objectValues = Object.values; -function primitiveEq(type, a, b) { - if (a === b) - return true; - if (type !== reflection_info_1.ScalarType.BYTES) - return false; - let ba = a; - let bb = b; - if (ba.length !== bb.length) - return false; - for (let i = 0; i < ba.length; i++) - if (ba[i] != bb[i]) - return false; - return true; + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _validate = _interopRequireDefault(__nccwpck_require__(66992)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function parse(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ + + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; } -function repeatedPrimitiveEq(type, a, b) { - if (a.length !== b.length) - return false; - for (let i = 0; i < a.length; i++) - if (!primitiveEq(type, a[i], b[i])) - return false; - return true; + +var _default = parse; +exports["default"] = _default; + +/***/ }), + +/***/ 3194: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; +exports["default"] = _default; + +/***/ }), + +/***/ 68136: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = rng; + +var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate + +let poolPtr = rnds8Pool.length; + +function rng() { + if (poolPtr > rnds8Pool.length - 16) { + _crypto.default.randomFillSync(rnds8Pool); + + poolPtr = 0; + } + + return rnds8Pool.slice(poolPtr, poolPtr += 16); } -function repeatedMsgEq(type, a, b) { - if (a.length !== b.length) - return false; - for (let i = 0; i < a.length; i++) - if (!type.equals(a[i], b[i])) - return false; - return true; + +/***/ }), + +/***/ 46679: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function sha1(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return _crypto.default.createHash('sha1').update(bytes).digest(); } +var _default = sha1; +exports["default"] = _default; /***/ }), -/***/ 21370: +/***/ 79618: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.readMessageOption = exports.readFieldOption = exports.readFieldOptions = exports.normalizeFieldInfo = exports.RepeatType = exports.LongType = exports.ScalarType = void 0; -const lower_camel_case_1 = __nccwpck_require__(34772); -/** - * Scalar value types. This is a subset of field types declared by protobuf - * enum google.protobuf.FieldDescriptorProto.Type The types GROUP and MESSAGE - * are omitted, but the numerical values are identical. - */ -var ScalarType; -(function (ScalarType) { - // 0 is reserved for errors. - // Order is weird for historical reasons. - ScalarType[ScalarType["DOUBLE"] = 1] = "DOUBLE"; - ScalarType[ScalarType["FLOAT"] = 2] = "FLOAT"; - // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if - // negative values are likely. - ScalarType[ScalarType["INT64"] = 3] = "INT64"; - ScalarType[ScalarType["UINT64"] = 4] = "UINT64"; - // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if - // negative values are likely. - ScalarType[ScalarType["INT32"] = 5] = "INT32"; - ScalarType[ScalarType["FIXED64"] = 6] = "FIXED64"; - ScalarType[ScalarType["FIXED32"] = 7] = "FIXED32"; - ScalarType[ScalarType["BOOL"] = 8] = "BOOL"; - ScalarType[ScalarType["STRING"] = 9] = "STRING"; - // Tag-delimited aggregate. - // Group type is deprecated and not supported in proto3. However, Proto3 - // implementations should still be able to parse the group wire format and - // treat group fields as unknown fields. - // TYPE_GROUP = 10, - // TYPE_MESSAGE = 11, // Length-delimited aggregate. - // New in version 2. - ScalarType[ScalarType["BYTES"] = 12] = "BYTES"; - ScalarType[ScalarType["UINT32"] = 13] = "UINT32"; - // TYPE_ENUM = 14, - ScalarType[ScalarType["SFIXED32"] = 15] = "SFIXED32"; - ScalarType[ScalarType["SFIXED64"] = 16] = "SFIXED64"; - ScalarType[ScalarType["SINT32"] = 17] = "SINT32"; - ScalarType[ScalarType["SINT64"] = 18] = "SINT64"; -})(ScalarType = exports.ScalarType || (exports.ScalarType = {})); -/** - * JavaScript representation of 64 bit integral types. Equivalent to the - * field option "jstype". - * - * By default, protobuf-ts represents 64 bit types as `bigint`. - * - * You can change the default behaviour by enabling the plugin parameter - * `long_type_string`, which will represent 64 bit types as `string`. - * - * Alternatively, you can change the behaviour for individual fields - * with the field option "jstype": - * - * ```protobuf - * uint64 my_field = 1 [jstype = JS_STRING]; - * uint64 other_field = 2 [jstype = JS_NUMBER]; - * ``` - */ -var LongType; -(function (LongType) { - /** - * Use JavaScript `bigint`. - * - * Field option `[jstype = JS_NORMAL]`. - */ - LongType[LongType["BIGINT"] = 0] = "BIGINT"; - /** - * Use JavaScript `string`. - * - * Field option `[jstype = JS_STRING]`. - */ - LongType[LongType["STRING"] = 1] = "STRING"; - /** - * Use JavaScript `number`. - * - * Large values will loose precision. - * - * Field option `[jstype = JS_NUMBER]`. - */ - LongType[LongType["NUMBER"] = 2] = "NUMBER"; -})(LongType = exports.LongType || (exports.LongType = {})); -/** - * Protobuf 2.1.0 introduced packed repeated fields. - * Setting the field option `[packed = true]` enables packing. - * - * In proto3, all repeated fields are packed by default. - * Setting the field option `[packed = false]` disables packing. - * - * Packed repeated fields are encoded with a single tag, - * then a length-delimiter, then the element values. - * - * Unpacked repeated fields are encoded with a tag and - * value for each element. - * - * `bytes` and `string` cannot be packed. - */ -var RepeatType; -(function (RepeatType) { - /** - * The field is not repeated. - */ - RepeatType[RepeatType["NO"] = 0] = "NO"; - /** - * The field is repeated and should be packed. - * Invalid for `bytes` and `string`, they cannot be packed. - */ - RepeatType[RepeatType["PACKED"] = 1] = "PACKED"; - /** - * The field is repeated but should not be packed. - * The only valid repeat type for repeated `bytes` and `string`. - */ - RepeatType[RepeatType["UNPACKED"] = 2] = "UNPACKED"; -})(RepeatType = exports.RepeatType || (exports.RepeatType = {})); -/** - * Turns PartialFieldInfo into FieldInfo. - */ -function normalizeFieldInfo(field) { - var _a, _b, _c, _d; - field.localName = (_a = field.localName) !== null && _a !== void 0 ? _a : lower_camel_case_1.lowerCamelCase(field.name); - field.jsonName = (_b = field.jsonName) !== null && _b !== void 0 ? _b : lower_camel_case_1.lowerCamelCase(field.name); - field.repeat = (_c = field.repeat) !== null && _c !== void 0 ? _c : RepeatType.NO; - field.opt = (_d = field.opt) !== null && _d !== void 0 ? _d : (field.repeat ? false : field.oneof ? false : field.kind == "message"); - return field; -} -exports.normalizeFieldInfo = normalizeFieldInfo; + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +exports.unsafeStringify = unsafeStringify; + +var _validate = _interopRequireDefault(__nccwpck_require__(66992)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + /** - * Read custom field options from a generated message type. - * - * @deprecated use readFieldOption() + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX */ -function readFieldOptions(messageType, fieldName, extensionName, extensionType) { - var _a; - const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; - return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : undefined; +const byteToHex = []; + +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); } -exports.readFieldOptions = readFieldOptions; -function readFieldOption(messageType, fieldName, extensionName, extensionType) { - var _a; - const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; - if (!options) { - return undefined; - } - const optionVal = options[extensionName]; - if (optionVal === undefined) { - return optionVal; - } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; + +function unsafeStringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]; } -exports.readFieldOption = readFieldOption; -function readMessageOption(messageType, extensionName, extensionType) { - const options = messageType.options; - const optionVal = options[extensionName]; - if (optionVal === undefined) { - return optionVal; - } - return extensionType ? extensionType.fromJson(optionVal) : optionVal; + +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + + if (!(0, _validate.default)(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + + return uuid; } -exports.readMessageOption = readMessageOption; +var _default = stringify; +exports["default"] = _default; /***/ }), -/***/ 229: +/***/ 36310: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ReflectionJsonReader = void 0; -const json_typings_1 = __nccwpck_require__(70661); -const base64_1 = __nccwpck_require__(20196); -const reflection_info_1 = __nccwpck_require__(21370); -const pb_long_1 = __nccwpck_require__(47777); -const assert_1 = __nccwpck_require__(54253); -const reflection_long_convert_1 = __nccwpck_require__(24612); -/** - * Reads proto3 messages in canonical JSON format using reflection information. - * - * https://developers.google.com/protocol-buffers/docs/proto3#json - */ -class ReflectionJsonReader { - constructor(info) { - this.info = info; - } - prepare() { - var _a; - if (this.fMap === undefined) { - this.fMap = {}; - const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; - for (const field of fieldsInput) { - this.fMap[field.name] = field; - this.fMap[field.jsonName] = field; - this.fMap[field.localName] = field; - } - } + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _rng = _interopRequireDefault(__nccwpck_require__(68136)); + +var _stringify = __nccwpck_require__(79618); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html +let _nodeId; + +let _clockseq; // Previous uuid creation time + + +let _lastMSecs = 0; +let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + +function v1(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node || _nodeId; + let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || _rng.default)(); + + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; } - // Cannot parse JSON for #. - assert(condition, fieldName, jsonValue) { - if (!condition) { - let what = json_typings_1.typeofJsonValue(jsonValue); - if (what == "number" || what == "boolean") - what = jsonValue.toString(); - throw new Error(`Cannot parse JSON ${what} for ${this.info.typeName}#${fieldName}`); - } + + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; } - /** - * Reads a message from canonical JSON format into the target message. - * - * Repeated fields are appended. Map entries are added, overwriting - * existing keys. - * - * If a message field is already present, it will be merged with the - * new data. - */ - read(input, message, options) { - this.prepare(); - const oneofsHandled = []; - for (const [jsonKey, jsonValue] of Object.entries(input)) { - const field = this.fMap[jsonKey]; - if (!field) { - if (!options.ignoreUnknownFields) - throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${jsonKey}`); - continue; - } - const localName = field.localName; - // handle oneof ADT - let target; // this will be the target for the field value, whether it is member of a oneof or not - if (field.oneof) { - if (jsonValue === null && (field.kind !== 'enum' || field.T()[0] !== 'google.protobuf.NullValue')) { - continue; - } - // since json objects are unordered by specification, it is not possible to take the last of multiple oneofs - if (oneofsHandled.includes(field.oneof)) - throw new Error(`Multiple members of the oneof group "${field.oneof}" of ${this.info.typeName} are present in JSON.`); - oneofsHandled.push(field.oneof); - target = message[field.oneof] = { - oneofKind: localName - }; - } - else { - target = message; - } - // we have handled oneof above. we just have read the value into `target`. - if (field.kind == 'map') { - if (jsonValue === null) { - continue; - } - // check input - this.assert(json_typings_1.isJsonObject(jsonValue), field.name, jsonValue); - // our target to put map entries into - const fieldObj = target[localName]; - // read entries - for (const [jsonObjKey, jsonObjValue] of Object.entries(jsonValue)) { - this.assert(jsonObjValue !== null, field.name + " map value", null); - // read value - let val; - switch (field.V.kind) { - case "message": - val = field.V.T().internalJsonRead(jsonObjValue, options); - break; - case "enum": - val = this.enum(field.V.T(), jsonObjValue, field.name, options.ignoreUnknownFields); - if (val === false) - continue; - break; - case "scalar": - val = this.scalar(jsonObjValue, field.V.T, field.V.L, field.name); - break; - } - this.assert(val !== undefined, field.name + " map value", jsonObjValue); - // read key - let key = jsonObjKey; - if (field.K == reflection_info_1.ScalarType.BOOL) - key = key == "true" ? true : key == "false" ? false : key; - key = this.scalar(key, field.K, reflection_info_1.LongType.STRING, field.name).toString(); - fieldObj[key] = val; - } - } - else if (field.repeat) { - if (jsonValue === null) - continue; - // check input - this.assert(Array.isArray(jsonValue), field.name, jsonValue); - // our target to put array entries into - const fieldArr = target[localName]; - // read array entries - for (const jsonItem of jsonValue) { - this.assert(jsonItem !== null, field.name, null); - let val; - switch (field.kind) { - case "message": - val = field.T().internalJsonRead(jsonItem, options); - break; - case "enum": - val = this.enum(field.T(), jsonItem, field.name, options.ignoreUnknownFields); - if (val === false) - continue; - break; - case "scalar": - val = this.scalar(jsonItem, field.T, field.L, field.name); - break; - } - this.assert(val !== undefined, field.name, jsonValue); - fieldArr.push(val); - } - } - else { - switch (field.kind) { - case "message": - if (jsonValue === null && field.T().typeName != 'google.protobuf.Value') { - this.assert(field.oneof === undefined, field.name + " (oneof member)", null); - continue; - } - target[localName] = field.T().internalJsonRead(jsonValue, options, target[localName]); - break; - case "enum": - let val = this.enum(field.T(), jsonValue, field.name, options.ignoreUnknownFields); - if (val === false) - continue; - target[localName] = val; - break; - case "scalar": - target[localName] = this.scalar(jsonValue, field.T, field.L, field.name); - break; - } - } - } + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + + + let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + + + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested + + + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + + msecs += 12219292800000; // `time_low` + + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` + + const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` + + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + + b[i++] = clockseq & 0xff; // `node` + + for (let n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf || (0, _stringify.unsafeStringify)(b); +} + +var _default = v1; +exports["default"] = _default; + +/***/ }), + +/***/ 9465: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _v = _interopRequireDefault(__nccwpck_require__(2568)); + +var _md = _interopRequireDefault(__nccwpck_require__(11380)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v3 = (0, _v.default)('v3', 0x30, _md.default); +var _default = v3; +exports["default"] = _default; + +/***/ }), + +/***/ 2568: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.URL = exports.DNS = void 0; +exports["default"] = v35; + +var _stringify = __nccwpck_require__(79618); + +var _parse = _interopRequireDefault(__nccwpck_require__(40086)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + const bytes = []; + + for (let i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } + + return bytes; +} + +const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +exports.DNS = DNS; +const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +exports.URL = URL; + +function v35(name, version, hashfunc) { + function generateUUID(value, namespace, buf, offset) { + var _namespace; + + if (typeof value === 'string') { + value = stringToBytes(value); } - /** - * Returns `false` for unrecognized string representations. - * - * google.protobuf.NullValue accepts only JSON `null` (or the old `"NULL_VALUE"`). - */ - enum(type, json, fieldName, ignoreUnknownFields) { - if (type[0] == 'google.protobuf.NullValue') - assert_1.assert(json === null || json === "NULL_VALUE", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type[0]} only accepts null.`); - if (json === null) - // we require 0 to be default value for all enums - return 0; - switch (typeof json) { - case "number": - assert_1.assert(Number.isInteger(json), `Unable to parse field ${this.info.typeName}#${fieldName}, enum can only be integral number, got ${json}.`); - return json; - case "string": - let localEnumName = json; - if (type[2] && json.substring(0, type[2].length) === type[2]) - // lookup without the shared prefix - localEnumName = json.substring(type[2].length); - let enumNumber = type[1][localEnumName]; - if (typeof enumNumber === 'undefined' && ignoreUnknownFields) { - return false; - } - assert_1.assert(typeof enumNumber == "number", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type[0]} has no value for "${json}".`); - return enumNumber; - } - assert_1.assert(false, `Unable to parse field ${this.info.typeName}#${fieldName}, cannot parse enum value from ${typeof json}".`); + + if (typeof namespace === 'string') { + namespace = (0, _parse.default)(namespace); } - scalar(json, type, longType, fieldName) { - let e; - try { - switch (type) { - // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". - // Either numbers or strings are accepted. Exponent notation is also accepted. - case reflection_info_1.ScalarType.DOUBLE: - case reflection_info_1.ScalarType.FLOAT: - if (json === null) - return .0; - if (json === "NaN") - return Number.NaN; - if (json === "Infinity") - return Number.POSITIVE_INFINITY; - if (json === "-Infinity") - return Number.NEGATIVE_INFINITY; - if (json === "") { - e = "empty string"; - break; - } - if (typeof json == "string" && json.trim().length !== json.length) { - e = "extra whitespace"; - break; - } - if (typeof json != "string" && typeof json != "number") { - break; - } - let float = Number(json); - if (Number.isNaN(float)) { - e = "not a number"; - break; - } - if (!Number.isFinite(float)) { - // infinity and -infinity are handled by string representation above, so this is an error - e = "too large or small"; - break; - } - if (type == reflection_info_1.ScalarType.FLOAT) - assert_1.assertFloat32(float); - return float; - // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT32: - case reflection_info_1.ScalarType.FIXED32: - case reflection_info_1.ScalarType.SFIXED32: - case reflection_info_1.ScalarType.SINT32: - case reflection_info_1.ScalarType.UINT32: - if (json === null) - return 0; - let int32; - if (typeof json == "number") - int32 = json; - else if (json === "") - e = "empty string"; - else if (typeof json == "string") { - if (json.trim().length !== json.length) - e = "extra whitespace"; - else - int32 = Number(json); - } - if (int32 === undefined) - break; - if (type == reflection_info_1.ScalarType.UINT32) - assert_1.assertUInt32(int32); - else - assert_1.assertInt32(int32); - return int32; - // int64, fixed64, uint64: JSON value will be a decimal string. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - if (json === null) - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); - if (typeof json != "number" && typeof json != "string") - break; - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.from(json), longType); - case reflection_info_1.ScalarType.FIXED64: - case reflection_info_1.ScalarType.UINT64: - if (json === null) - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); - if (typeof json != "number" && typeof json != "string") - break; - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.from(json), longType); - // bool: - case reflection_info_1.ScalarType.BOOL: - if (json === null) - return false; - if (typeof json !== "boolean") - break; - return json; - // string: - case reflection_info_1.ScalarType.STRING: - if (json === null) - return ""; - if (typeof json !== "string") { - e = "extra whitespace"; - break; - } - try { - encodeURIComponent(json); - } - catch (e) { - e = "invalid UTF8"; - break; - } - return json; - // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. - // Either standard or URL-safe base64 encoding with/without paddings are accepted. - case reflection_info_1.ScalarType.BYTES: - if (json === null || json === "") - return new Uint8Array(0); - if (typeof json !== 'string') - break; - return base64_1.base64decode(json); - } - } - catch (error) { - e = error.message; - } - this.assert(false, fieldName + (e ? " - " + e : ""), json); + + if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) { + throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); + } // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` + + + let bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + + return buf; } -} -exports.ReflectionJsonReader = ReflectionJsonReader; + return (0, _stringify.unsafeStringify)(bytes); + } // Function#name is not settable on some platforms (#270) + + + try { + generateUUID.name = name; // eslint-disable-next-line no-empty + } catch (err) {} // For CommonJS default export support + + + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; +} /***/ }), -/***/ 68980: +/***/ 86001: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ReflectionJsonWriter = void 0; -const base64_1 = __nccwpck_require__(20196); -const pb_long_1 = __nccwpck_require__(47777); -const reflection_info_1 = __nccwpck_require__(21370); -const assert_1 = __nccwpck_require__(54253); -/** - * Writes proto3 messages in canonical JSON format using reflection - * information. - * - * https://developers.google.com/protocol-buffers/docs/proto3#json - */ -class ReflectionJsonWriter { - constructor(info) { - var _a; - this.fields = (_a = info.fields) !== null && _a !== void 0 ? _a : []; - } - /** - * Converts the message to a JSON object, based on the field descriptors. - */ - write(message, options) { - const json = {}, source = message; - for (const field of this.fields) { - // field is not part of a oneof, simply write as is - if (!field.oneof) { - let jsonValue = this.field(field, source[field.localName], options); - if (jsonValue !== undefined) - json[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue; - continue; - } - // field is part of a oneof - const group = source[field.oneof]; - if (group.oneofKind !== field.localName) - continue; // not selected, skip - const opt = field.kind == 'scalar' || field.kind == 'enum' - ? Object.assign(Object.assign({}, options), { emitDefaultValues: true }) : options; - let jsonValue = this.field(field, group[field.localName], opt); - assert_1.assert(jsonValue !== undefined); - json[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue; - } - return json; - } - field(field, value, options) { - let jsonValue = undefined; - if (field.kind == 'map') { - assert_1.assert(typeof value == "object" && value !== null); - const jsonObj = {}; - switch (field.V.kind) { - case "scalar": - for (const [entryKey, entryValue] of Object.entries(value)) { - const val = this.scalar(field.V.T, entryValue, field.name, false, true); - assert_1.assert(val !== undefined); - jsonObj[entryKey.toString()] = val; // JSON standard allows only (double quoted) string as property key - } - break; - case "message": - const messageType = field.V.T(); - for (const [entryKey, entryValue] of Object.entries(value)) { - const val = this.message(messageType, entryValue, field.name, options); - assert_1.assert(val !== undefined); - jsonObj[entryKey.toString()] = val; // JSON standard allows only (double quoted) string as property key - } - break; - case "enum": - const enumInfo = field.V.T(); - for (const [entryKey, entryValue] of Object.entries(value)) { - assert_1.assert(entryValue === undefined || typeof entryValue == 'number'); - const val = this.enum(enumInfo, entryValue, field.name, false, true, options.enumAsInteger); - assert_1.assert(val !== undefined); - jsonObj[entryKey.toString()] = val; // JSON standard allows only (double quoted) string as property key - } - break; - } - if (options.emitDefaultValues || Object.keys(jsonObj).length > 0) - jsonValue = jsonObj; - } - else if (field.repeat) { - assert_1.assert(Array.isArray(value)); - const jsonArr = []; - switch (field.kind) { - case "scalar": - for (let i = 0; i < value.length; i++) { - const val = this.scalar(field.T, value[i], field.name, field.opt, true); - assert_1.assert(val !== undefined); - jsonArr.push(val); - } - break; - case "enum": - const enumInfo = field.T(); - for (let i = 0; i < value.length; i++) { - assert_1.assert(value[i] === undefined || typeof value[i] == 'number'); - const val = this.enum(enumInfo, value[i], field.name, field.opt, true, options.enumAsInteger); - assert_1.assert(val !== undefined); - jsonArr.push(val); - } - break; - case "message": - const messageType = field.T(); - for (let i = 0; i < value.length; i++) { - const val = this.message(messageType, value[i], field.name, options); - assert_1.assert(val !== undefined); - jsonArr.push(val); - } - break; - } - // add converted array to json output - if (options.emitDefaultValues || jsonArr.length > 0 || options.emitDefaultValues) - jsonValue = jsonArr; - } - else { - switch (field.kind) { - case "scalar": - jsonValue = this.scalar(field.T, value, field.name, field.opt, options.emitDefaultValues); - break; - case "enum": - jsonValue = this.enum(field.T(), value, field.name, field.opt, options.emitDefaultValues, options.enumAsInteger); - break; - case "message": - jsonValue = this.message(field.T(), value, field.name, options); - break; - } - } - return jsonValue; - } - /** - * Returns `null` as the default for google.protobuf.NullValue. - */ - enum(type, value, fieldName, optional, emitDefaultValues, enumAsInteger) { - if (type[0] == 'google.protobuf.NullValue') - return !emitDefaultValues && !optional ? undefined : null; - if (value === undefined) { - assert_1.assert(optional); - return undefined; - } - if (value === 0 && !emitDefaultValues && !optional) - // we require 0 to be default value for all enums - return undefined; - assert_1.assert(typeof value == 'number'); - assert_1.assert(Number.isInteger(value)); - if (enumAsInteger || !type[1].hasOwnProperty(value)) - // if we don't now the enum value, just return the number - return value; - if (type[2]) - // restore the dropped prefix - return type[2] + type[1][value]; - return type[1][value]; - } - message(type, value, fieldName, options) { - if (value === undefined) - return options.emitDefaultValues ? null : undefined; - return type.internalJsonWrite(value, options); - } - scalar(type, value, fieldName, optional, emitDefaultValues) { - if (value === undefined) { - assert_1.assert(optional); - return undefined; - } - const ed = emitDefaultValues || optional; - // noinspection FallThroughInSwitchStatementJS - switch (type) { - // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT32: - case reflection_info_1.ScalarType.SFIXED32: - case reflection_info_1.ScalarType.SINT32: - if (value === 0) - return ed ? 0 : undefined; - assert_1.assertInt32(value); - return value; - case reflection_info_1.ScalarType.FIXED32: - case reflection_info_1.ScalarType.UINT32: - if (value === 0) - return ed ? 0 : undefined; - assert_1.assertUInt32(value); - return value; - // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". - // Either numbers or strings are accepted. Exponent notation is also accepted. - case reflection_info_1.ScalarType.FLOAT: - assert_1.assertFloat32(value); - case reflection_info_1.ScalarType.DOUBLE: - if (value === 0) - return ed ? 0 : undefined; - assert_1.assert(typeof value == 'number'); - if (Number.isNaN(value)) - return 'NaN'; - if (value === Number.POSITIVE_INFINITY) - return 'Infinity'; - if (value === Number.NEGATIVE_INFINITY) - return '-Infinity'; - return value; - // string: - case reflection_info_1.ScalarType.STRING: - if (value === "") - return ed ? '' : undefined; - assert_1.assert(typeof value == 'string'); - return value; - // bool: - case reflection_info_1.ScalarType.BOOL: - if (value === false) - return ed ? false : undefined; - assert_1.assert(typeof value == 'boolean'); - return value; - // JSON value will be a decimal string. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.UINT64: - case reflection_info_1.ScalarType.FIXED64: - assert_1.assert(typeof value == 'number' || typeof value == 'string' || typeof value == 'bigint'); - let ulong = pb_long_1.PbULong.from(value); - if (ulong.isZero() && !ed) - return undefined; - return ulong.toString(); - // JSON value will be a decimal string. Either numbers or strings are accepted. - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - assert_1.assert(typeof value == 'number' || typeof value == 'string' || typeof value == 'bigint'); - let long = pb_long_1.PbLong.from(value); - if (long.isZero() && !ed) - return undefined; - return long.toString(); - // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. - // Either standard or URL-safe base64 encoding with/without paddings are accepted. - case reflection_info_1.ScalarType.BYTES: - assert_1.assert(value instanceof Uint8Array); - if (!value.byteLength) - return ed ? "" : undefined; - return base64_1.base64encode(value); - } + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _native = _interopRequireDefault(__nccwpck_require__(34672)); + +var _rng = _interopRequireDefault(__nccwpck_require__(68136)); + +var _stringify = __nccwpck_require__(79618); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function v4(options, buf, offset) { + if (_native.default.randomUUID && !buf && !options) { + return _native.default.randomUUID(); + } + + options = options || {}; + + const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + + + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; } + + return buf; + } + + return (0, _stringify.unsafeStringify)(rnds); } -exports.ReflectionJsonWriter = ReflectionJsonWriter; +var _default = v4; +exports["default"] = _default; /***/ }), -/***/ 24612: +/***/ 38310: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.reflectionLongConvert = void 0; -const reflection_info_1 = __nccwpck_require__(21370); -/** - * Utility method to convert a PbLong or PbUlong to a JavaScript - * representation during runtime. - * - * Works with generated field information, `undefined` is equivalent - * to `STRING`. - */ -function reflectionLongConvert(long, type) { - switch (type) { - case reflection_info_1.LongType.BIGINT: - return long.toBigInt(); - case reflection_info_1.LongType.NUMBER: - return long.toNumber(); - default: - // case undefined: - // case LongType.STRING: - return long.toString(); - } -} -exports.reflectionLongConvert = reflectionLongConvert; +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _v = _interopRequireDefault(__nccwpck_require__(2568)); + +var _sha = _interopRequireDefault(__nccwpck_require__(46679)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v5 = (0, _v.default)('v5', 0x50, _sha.default); +var _default = v5; +exports["default"] = _default; /***/ }), -/***/ 7869: -/***/ ((__unused_webpack_module, exports) => { +/***/ 66992: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.reflectionMergePartial = void 0; -/** - * Copy partial data into the target message. - * - * If a singular scalar or enum field is present in the source, it - * replaces the field in the target. - * - * If a singular message field is present in the source, it is merged - * with the target field by calling mergePartial() of the responsible - * message type. - * - * If a repeated field is present in the source, its values replace - * all values in the target array, removing extraneous values. - * Repeated message fields are copied, not merged. - * - * If a map field is present in the source, entries are added to the - * target map, replacing entries with the same key. Entries that only - * exist in the target remain. Entries with message values are copied, - * not merged. - * - * Note that this function differs from protobuf merge semantics, - * which appends repeated fields. - */ -function reflectionMergePartial(info, target, source) { - let fieldValue, // the field value we are working with - input = source, output; // where we want our field value to go - for (let field of info.fields) { - let name = field.localName; - if (field.oneof) { - const group = input[field.oneof]; // this is the oneof`s group in the source - if ((group === null || group === void 0 ? void 0 : group.oneofKind) == undefined) { // the user is free to omit - continue; // we skip this field, and all other members too - } - fieldValue = group[name]; // our value comes from the the oneof group of the source - output = target[field.oneof]; // and our output is the oneof group of the target - output.oneofKind = group.oneofKind; // always update discriminator - if (fieldValue == undefined) { - delete output[name]; // remove any existing value - continue; // skip further work on field - } - } - else { - fieldValue = input[name]; // we are using the source directly - output = target; // we want our field value to go directly into the target - if (fieldValue == undefined) { - continue; // skip further work on field, existing value is used as is - } - } - if (field.repeat) - output[name].length = fieldValue.length; // resize target array to match source array - // now we just work with `fieldValue` and `output` to merge the value - switch (field.kind) { - case "scalar": - case "enum": - if (field.repeat) - for (let i = 0; i < fieldValue.length; i++) - output[name][i] = fieldValue[i]; // not a reference type - else - output[name] = fieldValue; // not a reference type - break; - case "message": - let T = field.T(); - if (field.repeat) - for (let i = 0; i < fieldValue.length; i++) - output[name][i] = T.create(fieldValue[i]); - else if (output[name] === undefined) - output[name] = T.create(fieldValue); // nothing to merge with - else - T.mergePartial(output[name], fieldValue); - break; - case "map": - // Map and repeated fields are simply overwritten, not appended or merged - switch (field.V.kind) { - case "scalar": - case "enum": - Object.assign(output[name], fieldValue); // elements are not reference types - break; - case "message": - let T = field.V.T(); - for (let k of Object.keys(fieldValue)) - output[name][k] = T.create(fieldValue[k]); - break; - } - break; - } - } + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _regex = _interopRequireDefault(__nccwpck_require__(3194)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function validate(uuid) { + return typeof uuid === 'string' && _regex.default.test(uuid); } -exports.reflectionMergePartial = reflectionMergePartial; +var _default = validate; +exports["default"] = _default; /***/ }), -/***/ 74863: +/***/ 17780: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.reflectionScalarDefault = void 0; -const reflection_info_1 = __nccwpck_require__(21370); -const reflection_long_convert_1 = __nccwpck_require__(24612); -const pb_long_1 = __nccwpck_require__(47777); -/** - * Creates the default value for a scalar type. - */ -function reflectionScalarDefault(type, longType = reflection_info_1.LongType.STRING) { - switch (type) { - case reflection_info_1.ScalarType.BOOL: - return false; - case reflection_info_1.ScalarType.UINT64: - case reflection_info_1.ScalarType.FIXED64: - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); - case reflection_info_1.ScalarType.DOUBLE: - case reflection_info_1.ScalarType.FLOAT: - return 0.0; - case reflection_info_1.ScalarType.BYTES: - return new Uint8Array(0); - case reflection_info_1.ScalarType.STRING: - return ""; - default: - // case ScalarType.INT32: - // case ScalarType.UINT32: - // case ScalarType.SINT32: - // case ScalarType.FIXED32: - // case ScalarType.SFIXED32: - return 0; + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _validate = _interopRequireDefault(__nccwpck_require__(66992)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function version(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + return parseInt(uuid.slice(14, 15), 16); +} + +var _default = version; +exports["default"] = _default; + +/***/ }), + +/***/ 81238: +/***/ ((module) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +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); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + deserializerMiddleware: () => deserializerMiddleware, + deserializerMiddlewareOption: () => deserializerMiddlewareOption, + getSerdePlugin: () => getSerdePlugin, + serializerMiddleware: () => serializerMiddleware, + serializerMiddlewareOption: () => serializerMiddlewareOption +}); +module.exports = __toCommonJS(src_exports); + +// src/deserializerMiddleware.ts +var deserializerMiddleware = /* @__PURE__ */ __name((options, deserializer) => (next, context) => async (args) => { + const { response } = await next(args); + try { + const parsed = await deserializer(response, options); + return { + response, + output: parsed + }; + } catch (error) { + Object.defineProperty(error, "$response", { + value: response + }); + if (!("$metadata" in error)) { + const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; + try { + error.message += "\n " + hint; + } catch (e) { + if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { + console.warn(hint); + } else { + context.logger?.warn?.(hint); + } + } + if (typeof error.$responseBodyText !== "undefined") { + if (error.$response) { + error.$response.body = error.$responseBodyText; + } + } + } + throw error; + } +}, "deserializerMiddleware"); + +// src/serializerMiddleware.ts +var serializerMiddleware = /* @__PURE__ */ __name((options, serializer) => (next, context) => async (args) => { + const endpoint = context.endpointV2?.url && options.urlParser ? async () => options.urlParser(context.endpointV2.url) : options.endpoint; + if (!endpoint) { + throw new Error("No valid endpoint provider available."); + } + const request = await serializer(args.input, { ...options, endpoint }); + return next({ + ...args, + request + }); +}, "serializerMiddleware"); + +// src/serdePlugin.ts +var deserializerMiddlewareOption = { + name: "deserializerMiddleware", + step: "deserialize", + tags: ["DESERIALIZER"], + override: true +}; +var serializerMiddlewareOption = { + name: "serializerMiddleware", + step: "serialize", + tags: ["SERIALIZER"], + override: true +}; +function getSerdePlugin(config, serializer, deserializer) { + return { + applyToStack: (commandStack) => { + commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption); + commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption); } + }; } -exports.reflectionScalarDefault = reflectionScalarDefault; +__name(getSerdePlugin, "getSerdePlugin"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + /***/ }), -/***/ 20903: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 97911: +/***/ ((module) => { -"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +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); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ReflectionTypeCheck = void 0; -const reflection_info_1 = __nccwpck_require__(21370); -const oneof_1 = __nccwpck_require__(78531); -// noinspection JSMethodCanBeStatic -class ReflectionTypeCheck { - constructor(info) { - var _a; - this.fields = (_a = info.fields) !== null && _a !== void 0 ? _a : []; +// src/index.ts +var src_exports = {}; +__export(src_exports, { + constructStack: () => constructStack +}); +module.exports = __toCommonJS(src_exports); + +// src/MiddlewareStack.ts +var getAllAliases = /* @__PURE__ */ __name((name, aliases) => { + const _aliases = []; + if (name) { + _aliases.push(name); + } + if (aliases) { + for (const alias of aliases) { + _aliases.push(alias); } - prepare() { - if (this.data) - return; - const req = [], known = [], oneofs = []; - for (let field of this.fields) { - if (field.oneof) { - if (!oneofs.includes(field.oneof)) { - oneofs.push(field.oneof); - req.push(field.oneof); - known.push(field.oneof); - } - } - else { - known.push(field.localName); - switch (field.kind) { - case "scalar": - case "enum": - if (!field.opt || field.repeat) - req.push(field.localName); - break; - case "message": - if (field.repeat) - req.push(field.localName); - break; - case "map": - req.push(field.localName); - break; - } - } + } + return _aliases; +}, "getAllAliases"); +var getMiddlewareNameWithAliases = /* @__PURE__ */ __name((name, aliases) => { + return `${name || "anonymous"}${aliases && aliases.length > 0 ? ` (a.k.a. ${aliases.join(",")})` : ""}`; +}, "getMiddlewareNameWithAliases"); +var constructStack = /* @__PURE__ */ __name(() => { + let absoluteEntries = []; + let relativeEntries = []; + let identifyOnResolve = false; + const entriesNameSet = /* @__PURE__ */ new Set(); + const sort = /* @__PURE__ */ __name((entries) => entries.sort( + (a, b) => stepWeights[b.step] - stepWeights[a.step] || priorityWeights[b.priority || "normal"] - priorityWeights[a.priority || "normal"] + ), "sort"); + const removeByName = /* @__PURE__ */ __name((toRemove) => { + let isRemoved = false; + const filterCb = /* @__PURE__ */ __name((entry) => { + const aliases = getAllAliases(entry.name, entry.aliases); + if (aliases.includes(toRemove)) { + isRemoved = true; + for (const alias of aliases) { + entriesNameSet.delete(alias); } - this.data = { req, known, oneofs: Object.values(oneofs) }; - } - /** - * Is the argument a valid message as specified by the - * reflection information? - * - * Checks all field types recursively. The `depth` - * specifies how deep into the structure the check will be. - * - * With a depth of 0, only the presence of fields - * is checked. - * - * With a depth of 1 or more, the field types are checked. - * - * With a depth of 2 or more, the members of map, repeated - * and message fields are checked. - * - * Message fields will be checked recursively with depth - 1. - * - * The number of map entries / repeated values being checked - * is < depth. - */ - is(message, depth, allowExcessProperties = false) { - if (depth < 0) - return true; - if (message === null || message === undefined || typeof message != 'object') - return false; - this.prepare(); - let keys = Object.keys(message), data = this.data; - // if a required field is missing in arg, this cannot be a T - if (keys.length < data.req.length || data.req.some(n => !keys.includes(n))) - return false; - if (!allowExcessProperties) { - // if the arg contains a key we dont know, this is not a literal T - if (keys.some(k => !data.known.includes(k))) - return false; + return false; + } + return true; + }, "filterCb"); + absoluteEntries = absoluteEntries.filter(filterCb); + relativeEntries = relativeEntries.filter(filterCb); + return isRemoved; + }, "removeByName"); + const removeByReference = /* @__PURE__ */ __name((toRemove) => { + let isRemoved = false; + const filterCb = /* @__PURE__ */ __name((entry) => { + if (entry.middleware === toRemove) { + isRemoved = true; + for (const alias of getAllAliases(entry.name, entry.aliases)) { + entriesNameSet.delete(alias); } - // "With a depth of 0, only the presence and absence of fields is checked." - // "With a depth of 1 or more, the field types are checked." - if (depth < 1) { - return true; + return false; + } + return true; + }, "filterCb"); + absoluteEntries = absoluteEntries.filter(filterCb); + relativeEntries = relativeEntries.filter(filterCb); + return isRemoved; + }, "removeByReference"); + const cloneTo = /* @__PURE__ */ __name((toStack) => { + absoluteEntries.forEach((entry) => { + toStack.add(entry.middleware, { ...entry }); + }); + relativeEntries.forEach((entry) => { + toStack.addRelativeTo(entry.middleware, { ...entry }); + }); + toStack.identifyOnResolve?.(stack.identifyOnResolve()); + return toStack; + }, "cloneTo"); + const expandRelativeMiddlewareList = /* @__PURE__ */ __name((from) => { + const expandedMiddlewareList = []; + from.before.forEach((entry) => { + if (entry.before.length === 0 && entry.after.length === 0) { + expandedMiddlewareList.push(entry); + } else { + expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); + } + }); + expandedMiddlewareList.push(from); + from.after.reverse().forEach((entry) => { + if (entry.before.length === 0 && entry.after.length === 0) { + expandedMiddlewareList.push(entry); + } else { + expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); + } + }); + return expandedMiddlewareList; + }, "expandRelativeMiddlewareList"); + const getMiddlewareList = /* @__PURE__ */ __name((debug = false) => { + const normalizedAbsoluteEntries = []; + const normalizedRelativeEntries = []; + const normalizedEntriesNameMap = {}; + absoluteEntries.forEach((entry) => { + const normalizedEntry = { + ...entry, + before: [], + after: [] + }; + for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { + normalizedEntriesNameMap[alias] = normalizedEntry; + } + normalizedAbsoluteEntries.push(normalizedEntry); + }); + relativeEntries.forEach((entry) => { + const normalizedEntry = { + ...entry, + before: [], + after: [] + }; + for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { + normalizedEntriesNameMap[alias] = normalizedEntry; + } + normalizedRelativeEntries.push(normalizedEntry); + }); + normalizedRelativeEntries.forEach((entry) => { + if (entry.toMiddleware) { + const toMiddleware = normalizedEntriesNameMap[entry.toMiddleware]; + if (toMiddleware === void 0) { + if (debug) { + return; + } + throw new Error( + `${entry.toMiddleware} is not found when adding ${getMiddlewareNameWithAliases(entry.name, entry.aliases)} middleware ${entry.relation} ${entry.toMiddleware}` + ); } - // check oneof group - for (const name of data.oneofs) { - const group = message[name]; - if (!oneof_1.isOneofGroup(group)) - return false; - if (group.oneofKind === undefined) - continue; - const field = this.fields.find(f => f.localName === group.oneofKind); - if (!field) - return false; // we found no field, but have a kind, something is wrong - if (!this.field(group[group.oneofKind], field, allowExcessProperties, depth)) - return false; + if (entry.relation === "after") { + toMiddleware.after.push(entry); } - // check types - for (const field of this.fields) { - if (field.oneof !== undefined) - continue; - if (!this.field(message[field.localName], field, allowExcessProperties, depth)) - return false; + if (entry.relation === "before") { + toMiddleware.before.push(entry); } - return true; - } - field(arg, field, allowExcessProperties, depth) { - let repeated = field.repeat; - switch (field.kind) { - case "scalar": - if (arg === undefined) - return field.opt; - if (repeated) - return this.scalars(arg, field.T, depth, field.L); - return this.scalar(arg, field.T, field.L); - case "enum": - if (arg === undefined) - return field.opt; - if (repeated) - return this.scalars(arg, reflection_info_1.ScalarType.INT32, depth); - return this.scalar(arg, reflection_info_1.ScalarType.INT32); - case "message": - if (arg === undefined) - return true; - if (repeated) - return this.messages(arg, field.T(), allowExcessProperties, depth); - return this.message(arg, field.T(), allowExcessProperties, depth); - case "map": - if (typeof arg != 'object' || arg === null) - return false; - if (depth < 2) - return true; - if (!this.mapKeys(arg, field.K, depth)) - return false; - switch (field.V.kind) { - case "scalar": - return this.scalars(Object.values(arg), field.V.T, depth, field.V.L); - case "enum": - return this.scalars(Object.values(arg), reflection_info_1.ScalarType.INT32, depth); - case "message": - return this.messages(Object.values(arg), field.V.T(), allowExcessProperties, depth); - } - break; + } + }); + const mainChain = sort(normalizedAbsoluteEntries).map(expandRelativeMiddlewareList).reduce( + (wholeList, expandedMiddlewareList) => { + wholeList.push(...expandedMiddlewareList); + return wholeList; + }, + [] + ); + return mainChain; + }, "getMiddlewareList"); + const stack = { + add: (middleware, options = {}) => { + const { name, override, aliases: _aliases } = options; + const entry = { + step: "initialize", + priority: "normal", + middleware, + ...options + }; + const aliases = getAllAliases(name, _aliases); + if (aliases.length > 0) { + if (aliases.some((alias) => entriesNameSet.has(alias))) { + if (!override) + throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); + for (const alias of aliases) { + const toOverrideIndex = absoluteEntries.findIndex( + (entry2) => entry2.name === alias || entry2.aliases?.some((a) => a === alias) + ); + if (toOverrideIndex === -1) { + continue; + } + const toOverride = absoluteEntries[toOverrideIndex]; + if (toOverride.step !== entry.step || entry.priority !== toOverride.priority) { + throw new Error( + `"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware with ${toOverride.priority} priority in ${toOverride.step} step cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware with ${entry.priority} priority in ${entry.step} step.` + ); + } + absoluteEntries.splice(toOverrideIndex, 1); + } } - return true; - } - message(arg, type, allowExcessProperties, depth) { - if (allowExcessProperties) { - return type.isAssignable(arg, depth); + for (const alias of aliases) { + entriesNameSet.add(alias); } - return type.is(arg, depth); - } - messages(arg, type, allowExcessProperties, depth) { - if (!Array.isArray(arg)) - return false; - if (depth < 2) - return true; - if (allowExcessProperties) { - for (let i = 0; i < arg.length && i < depth; i++) - if (!type.isAssignable(arg[i], depth - 1)) - return false; + } + absoluteEntries.push(entry); + }, + addRelativeTo: (middleware, options) => { + const { name, override, aliases: _aliases } = options; + const entry = { + middleware, + ...options + }; + const aliases = getAllAliases(name, _aliases); + if (aliases.length > 0) { + if (aliases.some((alias) => entriesNameSet.has(alias))) { + if (!override) + throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); + for (const alias of aliases) { + const toOverrideIndex = relativeEntries.findIndex( + (entry2) => entry2.name === alias || entry2.aliases?.some((a) => a === alias) + ); + if (toOverrideIndex === -1) { + continue; + } + const toOverride = relativeEntries[toOverrideIndex]; + if (toOverride.toMiddleware !== entry.toMiddleware || toOverride.relation !== entry.relation) { + throw new Error( + `"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware ${toOverride.relation} "${toOverride.toMiddleware}" middleware cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware ${entry.relation} "${entry.toMiddleware}" middleware.` + ); + } + relativeEntries.splice(toOverrideIndex, 1); + } } - else { - for (let i = 0; i < arg.length && i < depth; i++) - if (!type.is(arg[i], depth - 1)) - return false; + for (const alias of aliases) { + entriesNameSet.add(alias); } - return true; - } - scalar(arg, type, longType) { - let argType = typeof arg; - switch (type) { - case reflection_info_1.ScalarType.UINT64: - case reflection_info_1.ScalarType.FIXED64: - case reflection_info_1.ScalarType.INT64: - case reflection_info_1.ScalarType.SFIXED64: - case reflection_info_1.ScalarType.SINT64: - switch (longType) { - case reflection_info_1.LongType.BIGINT: - return argType == "bigint"; - case reflection_info_1.LongType.NUMBER: - return argType == "number" && !isNaN(arg); - default: - return argType == "string"; - } - case reflection_info_1.ScalarType.BOOL: - return argType == 'boolean'; - case reflection_info_1.ScalarType.STRING: - return argType == 'string'; - case reflection_info_1.ScalarType.BYTES: - return arg instanceof Uint8Array; - case reflection_info_1.ScalarType.DOUBLE: - case reflection_info_1.ScalarType.FLOAT: - return argType == 'number' && !isNaN(arg); - default: - // case ScalarType.UINT32: - // case ScalarType.FIXED32: - // case ScalarType.INT32: - // case ScalarType.SINT32: - // case ScalarType.SFIXED32: - return argType == 'number' && Number.isInteger(arg); + } + relativeEntries.push(entry); + }, + clone: () => cloneTo(constructStack()), + use: (plugin) => { + plugin.applyToStack(stack); + }, + remove: (toRemove) => { + if (typeof toRemove === "string") + return removeByName(toRemove); + else + return removeByReference(toRemove); + }, + removeByTag: (toRemove) => { + let isRemoved = false; + const filterCb = /* @__PURE__ */ __name((entry) => { + const { tags, name, aliases: _aliases } = entry; + if (tags && tags.includes(toRemove)) { + const aliases = getAllAliases(name, _aliases); + for (const alias of aliases) { + entriesNameSet.delete(alias); + } + isRemoved = true; + return false; } - } - scalars(arg, type, depth, longType) { - if (!Array.isArray(arg)) - return false; - if (depth < 2) - return true; - if (Array.isArray(arg)) - for (let i = 0; i < arg.length && i < depth; i++) - if (!this.scalar(arg[i], type, longType)) - return false; return true; + }, "filterCb"); + absoluteEntries = absoluteEntries.filter(filterCb); + relativeEntries = relativeEntries.filter(filterCb); + return isRemoved; + }, + concat: (from) => { + const cloned = cloneTo(constructStack()); + cloned.use(from); + cloned.identifyOnResolve( + identifyOnResolve || cloned.identifyOnResolve() || (from.identifyOnResolve?.() ?? false) + ); + return cloned; + }, + applyToStack: cloneTo, + identify: () => { + return getMiddlewareList(true).map((mw) => { + const step = mw.step ?? mw.relation + " " + mw.toMiddleware; + return getMiddlewareNameWithAliases(mw.name, mw.aliases) + " - " + step; + }); + }, + identifyOnResolve(toggle) { + if (typeof toggle === "boolean") + identifyOnResolve = toggle; + return identifyOnResolve; + }, + resolve: (handler, context) => { + for (const middleware of getMiddlewareList().map((entry) => entry.middleware).reverse()) { + handler = middleware(handler, context); + } + if (identifyOnResolve) { + console.log(stack.identify()); + } + return handler; } - mapKeys(map, type, depth) { - let keys = Object.keys(map); - switch (type) { - case reflection_info_1.ScalarType.INT32: - case reflection_info_1.ScalarType.FIXED32: - case reflection_info_1.ScalarType.SFIXED32: - case reflection_info_1.ScalarType.SINT32: - case reflection_info_1.ScalarType.UINT32: - return this.scalars(keys.slice(0, depth).map(k => parseInt(k)), type, depth); - case reflection_info_1.ScalarType.BOOL: - return this.scalars(keys.slice(0, depth).map(k => k == 'true' ? true : k == 'false' ? false : k), type, depth); - default: - return this.scalars(keys, type, depth, reflection_info_1.LongType.STRING); - } - } -} -exports.ReflectionTypeCheck = ReflectionTypeCheck; + }; + return stack; +}, "constructStack"); +var stepWeights = { + initialize: 5, + serialize: 4, + build: 3, + finalizeRequest: 2, + deserialize: 1 +}; +var priorityWeights = { + high: 3, + normal: 2, + low: 1 +}; +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + /***/ }), -/***/ 53098: +/***/ 33461: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; @@ -239135,191 +235540,83 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var src_exports = {}; __export(src_exports, { - CONFIG_USE_DUALSTACK_ENDPOINT: () => CONFIG_USE_DUALSTACK_ENDPOINT, - CONFIG_USE_FIPS_ENDPOINT: () => CONFIG_USE_FIPS_ENDPOINT, - DEFAULT_USE_DUALSTACK_ENDPOINT: () => DEFAULT_USE_DUALSTACK_ENDPOINT, - DEFAULT_USE_FIPS_ENDPOINT: () => DEFAULT_USE_FIPS_ENDPOINT, - ENV_USE_DUALSTACK_ENDPOINT: () => ENV_USE_DUALSTACK_ENDPOINT, - ENV_USE_FIPS_ENDPOINT: () => ENV_USE_FIPS_ENDPOINT, - NODE_REGION_CONFIG_FILE_OPTIONS: () => NODE_REGION_CONFIG_FILE_OPTIONS, - NODE_REGION_CONFIG_OPTIONS: () => NODE_REGION_CONFIG_OPTIONS, - NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS: () => NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, - NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS: () => NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, - REGION_ENV_NAME: () => REGION_ENV_NAME, - REGION_INI_NAME: () => REGION_INI_NAME, - getRegionInfo: () => getRegionInfo, - resolveCustomEndpointsConfig: () => resolveCustomEndpointsConfig, - resolveEndpointsConfig: () => resolveEndpointsConfig, - resolveRegionConfig: () => resolveRegionConfig + loadConfig: () => loadConfig }); module.exports = __toCommonJS(src_exports); -// src/endpointsConfig/NodeUseDualstackEndpointConfigOptions.ts -var import_util_config_provider = __nccwpck_require__(83375); -var ENV_USE_DUALSTACK_ENDPOINT = "AWS_USE_DUALSTACK_ENDPOINT"; -var CONFIG_USE_DUALSTACK_ENDPOINT = "use_dualstack_endpoint"; -var DEFAULT_USE_DUALSTACK_ENDPOINT = false; -var NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = { - environmentVariableSelector: (env) => (0, import_util_config_provider.booleanSelector)(env, ENV_USE_DUALSTACK_ENDPOINT, import_util_config_provider.SelectorType.ENV), - configFileSelector: (profile) => (0, import_util_config_provider.booleanSelector)(profile, CONFIG_USE_DUALSTACK_ENDPOINT, import_util_config_provider.SelectorType.CONFIG), - default: false -}; - -// src/endpointsConfig/NodeUseFipsEndpointConfigOptions.ts - -var ENV_USE_FIPS_ENDPOINT = "AWS_USE_FIPS_ENDPOINT"; -var CONFIG_USE_FIPS_ENDPOINT = "use_fips_endpoint"; -var DEFAULT_USE_FIPS_ENDPOINT = false; -var NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = { - environmentVariableSelector: (env) => (0, import_util_config_provider.booleanSelector)(env, ENV_USE_FIPS_ENDPOINT, import_util_config_provider.SelectorType.ENV), - configFileSelector: (profile) => (0, import_util_config_provider.booleanSelector)(profile, CONFIG_USE_FIPS_ENDPOINT, import_util_config_provider.SelectorType.CONFIG), - default: false -}; - -// src/endpointsConfig/resolveCustomEndpointsConfig.ts -var import_util_middleware = __nccwpck_require__(2390); -var resolveCustomEndpointsConfig = /* @__PURE__ */ __name((input) => { - const { tls, endpoint, urlParser, useDualstackEndpoint } = input; - return Object.assign(input, { - tls: tls ?? true, - endpoint: (0, import_util_middleware.normalizeProvider)(typeof endpoint === "string" ? urlParser(endpoint) : endpoint), - isCustomEndpoint: true, - useDualstackEndpoint: (0, import_util_middleware.normalizeProvider)(useDualstackEndpoint ?? false) - }); -}, "resolveCustomEndpointsConfig"); +// src/configLoader.ts -// src/endpointsConfig/resolveEndpointsConfig.ts +// src/fromEnv.ts +var import_property_provider = __nccwpck_require__(79721); -// src/endpointsConfig/utils/getEndpointFromRegion.ts -var getEndpointFromRegion = /* @__PURE__ */ __name(async (input) => { - const { tls = true } = input; - const region = await input.region(); - const dnsHostRegex = new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/); - if (!dnsHostRegex.test(region)) { - throw new Error("Invalid region in client config"); +// src/getSelectorName.ts +function getSelectorName(functionString) { + try { + const constants = new Set(Array.from(functionString.match(/([A-Z_]){3,}/g) ?? [])); + constants.delete("CONFIG"); + constants.delete("CONFIG_PREFIX_SEPARATOR"); + constants.delete("ENV"); + return [...constants].join(", "); + } catch (e) { + return functionString; } - const useDualstackEndpoint = await input.useDualstackEndpoint(); - const useFipsEndpoint = await input.useFipsEndpoint(); - const { hostname } = await input.regionInfoProvider(region, { useDualstackEndpoint, useFipsEndpoint }) ?? {}; - if (!hostname) { - throw new Error("Cannot resolve hostname from client config"); +} +__name(getSelectorName, "getSelectorName"); + +// src/fromEnv.ts +var fromEnv = /* @__PURE__ */ __name((envVarSelector, logger) => async () => { + try { + const config = envVarSelector(process.env); + if (config === void 0) { + throw new Error(); + } + return config; + } catch (e) { + throw new import_property_provider.CredentialsProviderError( + e.message || `Not found in ENV: ${getSelectorName(envVarSelector.toString())}`, + { logger } + ); } - return input.urlParser(`${tls ? "https:" : "http:"}//${hostname}`); -}, "getEndpointFromRegion"); +}, "fromEnv"); -// src/endpointsConfig/resolveEndpointsConfig.ts -var resolveEndpointsConfig = /* @__PURE__ */ __name((input) => { - const useDualstackEndpoint = (0, import_util_middleware.normalizeProvider)(input.useDualstackEndpoint ?? false); - const { endpoint, useFipsEndpoint, urlParser, tls } = input; - return Object.assign(input, { - tls: tls ?? true, - endpoint: endpoint ? (0, import_util_middleware.normalizeProvider)(typeof endpoint === "string" ? urlParser(endpoint) : endpoint) : () => getEndpointFromRegion({ ...input, useDualstackEndpoint, useFipsEndpoint }), - isCustomEndpoint: !!endpoint, - useDualstackEndpoint - }); -}, "resolveEndpointsConfig"); +// src/fromSharedConfigFiles.ts -// src/regionConfig/config.ts -var REGION_ENV_NAME = "AWS_REGION"; -var REGION_INI_NAME = "region"; -var NODE_REGION_CONFIG_OPTIONS = { - environmentVariableSelector: (env) => env[REGION_ENV_NAME], - configFileSelector: (profile) => profile[REGION_INI_NAME], - default: () => { - throw new Error("Region is missing"); +var import_shared_ini_file_loader = __nccwpck_require__(43507); +var fromSharedConfigFiles = /* @__PURE__ */ __name((configSelector, { preferredFile = "config", ...init } = {}) => async () => { + const profile = (0, import_shared_ini_file_loader.getProfileName)(init); + const { configFile, credentialsFile } = await (0, import_shared_ini_file_loader.loadSharedConfigFiles)(init); + const profileFromCredentials = credentialsFile[profile] || {}; + const profileFromConfig = configFile[profile] || {}; + const mergedProfile = preferredFile === "config" ? { ...profileFromCredentials, ...profileFromConfig } : { ...profileFromConfig, ...profileFromCredentials }; + try { + const cfgFile = preferredFile === "config" ? configFile : credentialsFile; + const configValue = configSelector(mergedProfile, cfgFile); + if (configValue === void 0) { + throw new Error(); + } + return configValue; + } catch (e) { + throw new import_property_provider.CredentialsProviderError( + e.message || `Not found in config files w/ profile [${profile}]: ${getSelectorName(configSelector.toString())}`, + { logger: init.logger } + ); } -}; -var NODE_REGION_CONFIG_FILE_OPTIONS = { - preferredFile: "credentials" -}; - -// src/regionConfig/isFipsRegion.ts -var isFipsRegion = /* @__PURE__ */ __name((region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")), "isFipsRegion"); +}, "fromSharedConfigFiles"); -// src/regionConfig/getRealRegion.ts -var getRealRegion = /* @__PURE__ */ __name((region) => isFipsRegion(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region, "getRealRegion"); +// src/fromStatic.ts -// src/regionConfig/resolveRegionConfig.ts -var resolveRegionConfig = /* @__PURE__ */ __name((input) => { - const { region, useFipsEndpoint } = input; - if (!region) { - throw new Error("Region is missing"); - } - return Object.assign(input, { - region: async () => { - if (typeof region === "string") { - return getRealRegion(region); - } - const providedRegion = await region(); - return getRealRegion(providedRegion); - }, - useFipsEndpoint: async () => { - const providedRegion = typeof region === "string" ? region : await region(); - if (isFipsRegion(providedRegion)) { - return true; - } - return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint(); - } - }); -}, "resolveRegionConfig"); +var isFunction = /* @__PURE__ */ __name((func) => typeof func === "function", "isFunction"); +var fromStatic = /* @__PURE__ */ __name((defaultValue) => isFunction(defaultValue) ? async () => await defaultValue() : (0, import_property_provider.fromStatic)(defaultValue), "fromStatic"); -// src/regionInfo/getHostnameFromVariants.ts -var getHostnameFromVariants = /* @__PURE__ */ __name((variants = [], { useFipsEndpoint, useDualstackEndpoint }) => variants.find( - ({ tags }) => useFipsEndpoint === tags.includes("fips") && useDualstackEndpoint === tags.includes("dualstack") -)?.hostname, "getHostnameFromVariants"); - -// src/regionInfo/getResolvedHostname.ts -var getResolvedHostname = /* @__PURE__ */ __name((resolvedRegion, { regionHostname, partitionHostname }) => regionHostname ? regionHostname : partitionHostname ? partitionHostname.replace("{region}", resolvedRegion) : void 0, "getResolvedHostname"); - -// src/regionInfo/getResolvedPartition.ts -var getResolvedPartition = /* @__PURE__ */ __name((region, { partitionHash }) => Object.keys(partitionHash || {}).find((key) => partitionHash[key].regions.includes(region)) ?? "aws", "getResolvedPartition"); - -// src/regionInfo/getResolvedSigningRegion.ts -var getResolvedSigningRegion = /* @__PURE__ */ __name((hostname, { signingRegion, regionRegex, useFipsEndpoint }) => { - if (signingRegion) { - return signingRegion; - } else if (useFipsEndpoint) { - const regionRegexJs = regionRegex.replace("\\\\", "\\").replace(/^\^/g, "\\.").replace(/\$$/g, "\\."); - const regionRegexmatchArray = hostname.match(regionRegexJs); - if (regionRegexmatchArray) { - return regionRegexmatchArray[0].slice(1, -1); - } - } -}, "getResolvedSigningRegion"); - -// src/regionInfo/getRegionInfo.ts -var getRegionInfo = /* @__PURE__ */ __name((region, { - useFipsEndpoint = false, - useDualstackEndpoint = false, - signingService, - regionHash, - partitionHash -}) => { - const partition = getResolvedPartition(region, { partitionHash }); - const resolvedRegion = region in regionHash ? region : partitionHash[partition]?.endpoint ?? region; - const hostnameOptions = { useFipsEndpoint, useDualstackEndpoint }; - const regionHostname = getHostnameFromVariants(regionHash[resolvedRegion]?.variants, hostnameOptions); - const partitionHostname = getHostnameFromVariants(partitionHash[partition]?.variants, hostnameOptions); - const hostname = getResolvedHostname(resolvedRegion, { regionHostname, partitionHostname }); - if (hostname === void 0) { - throw new Error(`Endpoint resolution failed for: ${{ resolvedRegion, useFipsEndpoint, useDualstackEndpoint }}`); - } - const signingRegion = getResolvedSigningRegion(hostname, { - signingRegion: regionHash[resolvedRegion]?.signingRegion, - regionRegex: partitionHash[partition].regionRegex, - useFipsEndpoint - }); - return { - partition, - signingService, - hostname, - ...signingRegion && { signingRegion }, - ...regionHash[resolvedRegion]?.signingService && { - signingService: regionHash[resolvedRegion].signingService - } - }; -}, "getRegionInfo"); +// src/configLoader.ts +var loadConfig = /* @__PURE__ */ __name(({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => (0, import_property_provider.memoize)( + (0, import_property_provider.chain)( + fromEnv(environmentVariableSelector), + fromSharedConfigFiles(configFileSelector, configuration), + fromStatic(defaultValue) + ) +), "loadConfig"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -239328,12 +235625,14 @@ var getRegionInfo = /* @__PURE__ */ __name((region, { /***/ }), -/***/ 55829: +/***/ 20258: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +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 __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { @@ -239348,354 +235647,918 @@ var __copyProps = (to, from, except, desc) => { } 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); // src/index.ts var src_exports = {}; __export(src_exports, { - DefaultIdentityProviderConfig: () => DefaultIdentityProviderConfig, - EXPIRATION_MS: () => EXPIRATION_MS, - HttpApiKeyAuthSigner: () => HttpApiKeyAuthSigner, - HttpBearerAuthSigner: () => HttpBearerAuthSigner, - NoAuthSigner: () => NoAuthSigner, - createIsIdentityExpiredFunction: () => createIsIdentityExpiredFunction, - createPaginator: () => createPaginator, - doesIdentityRequireRefresh: () => doesIdentityRequireRefresh, - getHttpAuthSchemeEndpointRuleSetPlugin: () => getHttpAuthSchemeEndpointRuleSetPlugin, - getHttpAuthSchemePlugin: () => getHttpAuthSchemePlugin, - getHttpSigningPlugin: () => getHttpSigningPlugin, - getSmithyContext: () => getSmithyContext, - httpAuthSchemeEndpointRuleSetMiddlewareOptions: () => httpAuthSchemeEndpointRuleSetMiddlewareOptions, - httpAuthSchemeMiddleware: () => httpAuthSchemeMiddleware, - httpAuthSchemeMiddlewareOptions: () => httpAuthSchemeMiddlewareOptions, - httpSigningMiddleware: () => httpSigningMiddleware, - httpSigningMiddlewareOptions: () => httpSigningMiddlewareOptions, - isIdentityExpired: () => isIdentityExpired, - memoizeIdentityProvider: () => memoizeIdentityProvider, - normalizeProvider: () => normalizeProvider, - requestBuilder: () => import_protocols.requestBuilder, - setFeature: () => setFeature + DEFAULT_REQUEST_TIMEOUT: () => DEFAULT_REQUEST_TIMEOUT, + NodeHttp2Handler: () => NodeHttp2Handler, + NodeHttpHandler: () => NodeHttpHandler, + streamCollector: () => streamCollector }); module.exports = __toCommonJS(src_exports); -// src/getSmithyContext.ts -var import_types = __nccwpck_require__(55756); -var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); +// src/node-http-handler.ts +var import_protocol_http = __nccwpck_require__(64418); +var import_querystring_builder = __nccwpck_require__(68031); +var import_http = __nccwpck_require__(13685); +var import_https = __nccwpck_require__(95687); -// src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts -var import_util_middleware = __nccwpck_require__(2390); -function convertHttpAuthSchemesToMap(httpAuthSchemes) { - const map = /* @__PURE__ */ new Map(); - for (const scheme of httpAuthSchemes) { - map.set(scheme.schemeId, scheme); +// src/constants.ts +var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"]; + +// src/get-transformed-headers.ts +var getTransformedHeaders = /* @__PURE__ */ __name((headers) => { + const transformedHeaders = {}; + for (const name of Object.keys(headers)) { + const headerValues = headers[name]; + transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues; } - return map; -} -__name(convertHttpAuthSchemesToMap, "convertHttpAuthSchemesToMap"); -var httpAuthSchemeMiddleware = /* @__PURE__ */ __name((config, mwOptions) => (next, context) => async (args) => { - const options = config.httpAuthSchemeProvider( - await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input) + return transformedHeaders; +}, "getTransformedHeaders"); + +// src/timing.ts +var timing = { + setTimeout: (cb, ms) => setTimeout(cb, ms), + clearTimeout: (timeoutId) => clearTimeout(timeoutId) +}; + +// src/set-connection-timeout.ts +var DEFER_EVENT_LISTENER_TIME = 1e3; +var setConnectionTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = 0) => { + if (!timeoutInMs) { + return -1; + } + const registerTimeout = /* @__PURE__ */ __name((offset) => { + const timeoutId = timing.setTimeout(() => { + request.destroy(); + reject( + Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), { + name: "TimeoutError" + }) + ); + }, timeoutInMs - offset); + const doWithSocket = /* @__PURE__ */ __name((socket) => { + if (socket?.connecting) { + socket.on("connect", () => { + timing.clearTimeout(timeoutId); + }); + } else { + timing.clearTimeout(timeoutId); + } + }, "doWithSocket"); + if (request.socket) { + doWithSocket(request.socket); + } else { + request.on("socket", doWithSocket); + } + }, "registerTimeout"); + if (timeoutInMs < 2e3) { + registerTimeout(0); + return 0; + } + return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME); +}, "setConnectionTimeout"); + +// src/set-socket-keep-alive.ts +var DEFER_EVENT_LISTENER_TIME2 = 3e3; +var setSocketKeepAlive = /* @__PURE__ */ __name((request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME2) => { + if (keepAlive !== true) { + return -1; + } + const registerListener = /* @__PURE__ */ __name(() => { + if (request.socket) { + request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); + } else { + request.on("socket", (socket) => { + socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); + }); + } + }, "registerListener"); + if (deferTimeMs === 0) { + registerListener(); + return 0; + } + return timing.setTimeout(registerListener, deferTimeMs); +}, "setSocketKeepAlive"); + +// src/set-socket-timeout.ts +var DEFER_EVENT_LISTENER_TIME3 = 3e3; +var setSocketTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = DEFAULT_REQUEST_TIMEOUT) => { + const registerTimeout = /* @__PURE__ */ __name((offset) => { + const timeout = timeoutInMs - offset; + const onTimeout = /* @__PURE__ */ __name(() => { + request.destroy(); + reject(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" })); + }, "onTimeout"); + if (request.socket) { + request.socket.setTimeout(timeout, onTimeout); + request.on("close", () => request.socket?.removeListener("timeout", onTimeout)); + } else { + request.setTimeout(timeout, onTimeout); + } + }, "registerTimeout"); + if (0 < timeoutInMs && timeoutInMs < 6e3) { + registerTimeout(0); + return 0; + } + return timing.setTimeout( + registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME3), + DEFER_EVENT_LISTENER_TIME3 ); - const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes); - const smithyContext = (0, import_util_middleware.getSmithyContext)(context); - const failureReasons = []; - for (const option of options) { - const scheme = authSchemes.get(option.schemeId); - if (!scheme) { - failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`); - continue; +}, "setSocketTimeout"); + +// src/write-request-body.ts +var import_stream = __nccwpck_require__(12781); +var MIN_WAIT_TIME = 6e3; +async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME) { + const headers = request.headers ?? {}; + const expect = headers["Expect"] || headers["expect"]; + let timeoutId = -1; + let sendBody = true; + if (expect === "100-continue") { + sendBody = await Promise.race([ + new Promise((resolve) => { + timeoutId = Number(timing.setTimeout(() => resolve(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs))); + }), + new Promise((resolve) => { + httpRequest.on("continue", () => { + timing.clearTimeout(timeoutId); + resolve(true); + }); + httpRequest.on("response", () => { + timing.clearTimeout(timeoutId); + resolve(false); + }); + httpRequest.on("error", () => { + timing.clearTimeout(timeoutId); + resolve(false); + }); + }) + ]); + } + if (sendBody) { + writeBody(httpRequest, request.body); + } +} +__name(writeRequestBody, "writeRequestBody"); +function writeBody(httpRequest, body) { + if (body instanceof import_stream.Readable) { + body.pipe(httpRequest); + return; + } + if (body) { + if (Buffer.isBuffer(body) || typeof body === "string") { + httpRequest.end(body); + return; } - const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config)); - if (!identityProvider) { - failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`); - continue; + const uint8 = body; + if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") { + httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength)); + return; } - const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context) || {}; - option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties); - option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties); - smithyContext.selectedHttpAuthScheme = { - httpAuthOption: option, - identity: await identityProvider(option.identityProperties), - signer: scheme.signer + httpRequest.end(Buffer.from(body)); + return; + } + httpRequest.end(); +} +__name(writeBody, "writeBody"); + +// src/node-http-handler.ts +var DEFAULT_REQUEST_TIMEOUT = 0; +var NodeHttpHandler = class _NodeHttpHandler { + constructor(options) { + this.socketWarningTimestamp = 0; + // Node http handler is hard-coded to http/1.1: https://github.com/nodejs/node/blob/ff5664b83b89c55e4ab5d5f60068fb457f1f5872/lib/_http_server.js#L286 + this.metadata = { handlerProtocol: "http/1.1" }; + this.configProvider = new Promise((resolve, reject) => { + if (typeof options === "function") { + options().then((_options) => { + resolve(this.resolveDefaultConfig(_options)); + }).catch(reject); + } else { + resolve(this.resolveDefaultConfig(options)); + } + }); + } + static { + __name(this, "NodeHttpHandler"); + } + /** + * @returns the input if it is an HttpHandler of any class, + * or instantiates a new instance of this handler. + */ + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; + } + return new _NodeHttpHandler(instanceOrOptions); + } + /** + * @internal + * + * @param agent - http(s) agent in use by the NodeHttpHandler instance. + * @param socketWarningTimestamp - last socket usage check timestamp. + * @param logger - channel for the warning. + * @returns timestamp of last emitted warning. + */ + static checkSocketUsage(agent, socketWarningTimestamp, logger = console) { + const { sockets, requests, maxSockets } = agent; + if (typeof maxSockets !== "number" || maxSockets === Infinity) { + return socketWarningTimestamp; + } + const interval = 15e3; + if (Date.now() - interval < socketWarningTimestamp) { + return socketWarningTimestamp; + } + if (sockets && requests) { + for (const origin in sockets) { + const socketsInUse = sockets[origin]?.length ?? 0; + const requestsEnqueued = requests[origin]?.length ?? 0; + if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) { + logger?.warn?.( + `@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued. +See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html +or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.` + ); + return Date.now(); + } + } + } + return socketWarningTimestamp; + } + resolveDefaultConfig(options) { + const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent } = options || {}; + const keepAlive = true; + const maxSockets = 50; + return { + connectionTimeout, + requestTimeout: requestTimeout ?? socketTimeout, + socketAcquisitionWarningTimeout, + httpAgent: (() => { + if (httpAgent instanceof import_http.Agent || typeof httpAgent?.destroy === "function") { + return httpAgent; + } + return new import_http.Agent({ keepAlive, maxSockets, ...httpAgent }); + })(), + httpsAgent: (() => { + if (httpsAgent instanceof import_https.Agent || typeof httpsAgent?.destroy === "function") { + return httpsAgent; + } + return new import_https.Agent({ keepAlive, maxSockets, ...httpsAgent }); + })(), + logger: console }; - break; } - if (!smithyContext.selectedHttpAuthScheme) { - throw new Error(failureReasons.join("\n")); + destroy() { + this.config?.httpAgent?.destroy(); + this.config?.httpsAgent?.destroy(); + } + async handle(request, { abortSignal } = {}) { + if (!this.config) { + this.config = await this.configProvider; + } + return new Promise((_resolve, _reject) => { + let writeRequestBodyPromise = void 0; + const timeouts = []; + const resolve = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + timeouts.forEach(timing.clearTimeout); + _resolve(arg); + }, "resolve"); + const reject = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + timeouts.forEach(timing.clearTimeout); + _reject(arg); + }, "reject"); + if (!this.config) { + throw new Error("Node HTTP request handler config is not resolved"); + } + if (abortSignal?.aborted) { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + return; + } + const isSSL = request.protocol === "https:"; + const agent = isSSL ? this.config.httpsAgent : this.config.httpAgent; + timeouts.push( + timing.setTimeout( + () => { + this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage( + agent, + this.socketWarningTimestamp, + this.config.logger + ); + }, + this.config.socketAcquisitionWarningTimeout ?? (this.config.requestTimeout ?? 2e3) + (this.config.connectionTimeout ?? 1e3) + ) + ); + const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); + let auth = void 0; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}`; + } + let path = request.path; + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + let hostname = request.hostname ?? ""; + if (hostname[0] === "[" && hostname.endsWith("]")) { + hostname = request.hostname.slice(1, -1); + } else { + hostname = request.hostname; + } + const nodeHttpsOptions = { + headers: request.headers, + host: hostname, + method: request.method, + path, + port: request.port, + agent, + auth + }; + const requestFunc = isSSL ? import_https.request : import_http.request; + const req = requestFunc(nodeHttpsOptions, (res) => { + const httpResponse = new import_protocol_http.HttpResponse({ + statusCode: res.statusCode || -1, + reason: res.statusMessage, + headers: getTransformedHeaders(res.headers), + body: res + }); + resolve({ response: httpResponse }); + }); + req.on("error", (err) => { + if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) { + reject(Object.assign(err, { name: "TimeoutError" })); + } else { + reject(err); + } + }); + if (abortSignal) { + const onAbort = /* @__PURE__ */ __name(() => { + req.destroy(); + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + }, "onAbort"); + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + req.once("close", () => signal.removeEventListener("abort", onAbort)); + } else { + abortSignal.onabort = onAbort; + } + } + timeouts.push(setConnectionTimeout(req, reject, this.config.connectionTimeout)); + timeouts.push(setSocketTimeout(req, reject, this.config.requestTimeout)); + const httpAgent = nodeHttpsOptions.agent; + if (typeof httpAgent === "object" && "keepAlive" in httpAgent) { + timeouts.push( + setSocketKeepAlive(req, { + // @ts-expect-error keepAlive is not public on httpAgent. + keepAlive: httpAgent.keepAlive, + // @ts-expect-error keepAliveMsecs is not public on httpAgent. + keepAliveMsecs: httpAgent.keepAliveMsecs + }) + ); + } + writeRequestBodyPromise = writeRequestBody(req, request, this.config.requestTimeout).catch((e) => { + timeouts.forEach(timing.clearTimeout); + return _reject(e); + }); + }); + } + updateHttpClientConfig(key, value) { + this.config = void 0; + this.configProvider = this.configProvider.then((config) => { + return { + ...config, + [key]: value + }; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; } - return next(args); -}, "httpAuthSchemeMiddleware"); - -// src/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.ts -var httpAuthSchemeEndpointRuleSetMiddlewareOptions = { - step: "serialize", - tags: ["HTTP_AUTH_SCHEME"], - name: "httpAuthSchemeMiddleware", - override: true, - relation: "before", - toMiddleware: "endpointV2Middleware" }; -var getHttpAuthSchemeEndpointRuleSetPlugin = /* @__PURE__ */ __name((config, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider -}) => ({ - applyToStack: (clientStack) => { - clientStack.addRelativeTo( - httpAuthSchemeMiddleware(config, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider - }), - httpAuthSchemeEndpointRuleSetMiddlewareOptions - ); + +// src/node-http2-handler.ts + + +var import_http22 = __nccwpck_require__(85158); + +// src/node-http2-connection-manager.ts +var import_http2 = __toESM(__nccwpck_require__(85158)); + +// src/node-http2-connection-pool.ts +var NodeHttp2ConnectionPool = class { + constructor(sessions) { + this.sessions = []; + this.sessions = sessions ?? []; } -}), "getHttpAuthSchemeEndpointRuleSetPlugin"); + static { + __name(this, "NodeHttp2ConnectionPool"); + } + poll() { + if (this.sessions.length > 0) { + return this.sessions.shift(); + } + } + offerLast(session) { + this.sessions.push(session); + } + contains(session) { + return this.sessions.includes(session); + } + remove(session) { + this.sessions = this.sessions.filter((s) => s !== session); + } + [Symbol.iterator]() { + return this.sessions[Symbol.iterator](); + } + destroy(connection) { + for (const session of this.sessions) { + if (session === connection) { + if (!session.destroyed) { + session.destroy(); + } + } + } + } +}; -// src/middleware-http-auth-scheme/getHttpAuthSchemePlugin.ts -var import_middleware_serde = __nccwpck_require__(81238); -var httpAuthSchemeMiddlewareOptions = { - step: "serialize", - tags: ["HTTP_AUTH_SCHEME"], - name: "httpAuthSchemeMiddleware", - override: true, - relation: "before", - toMiddleware: import_middleware_serde.serializerMiddlewareOption.name +// src/node-http2-connection-manager.ts +var NodeHttp2ConnectionManager = class { + constructor(config) { + this.sessionCache = /* @__PURE__ */ new Map(); + this.config = config; + if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) { + throw new RangeError("maxConcurrency must be greater than zero."); + } + } + static { + __name(this, "NodeHttp2ConnectionManager"); + } + lease(requestContext, connectionConfiguration) { + const url = this.getUrlString(requestContext); + const existingPool = this.sessionCache.get(url); + if (existingPool) { + const existingSession = existingPool.poll(); + if (existingSession && !this.config.disableConcurrency) { + return existingSession; + } + } + const session = import_http2.default.connect(url); + if (this.config.maxConcurrency) { + session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => { + if (err) { + throw new Error( + "Fail to set maxConcurrentStreams to " + this.config.maxConcurrency + "when creating new session for " + requestContext.destination.toString() + ); + } + }); + } + session.unref(); + const destroySessionCb = /* @__PURE__ */ __name(() => { + session.destroy(); + this.deleteSession(url, session); + }, "destroySessionCb"); + session.on("goaway", destroySessionCb); + session.on("error", destroySessionCb); + session.on("frameError", destroySessionCb); + session.on("close", () => this.deleteSession(url, session)); + if (connectionConfiguration.requestTimeout) { + session.setTimeout(connectionConfiguration.requestTimeout, destroySessionCb); + } + const connectionPool = this.sessionCache.get(url) || new NodeHttp2ConnectionPool(); + connectionPool.offerLast(session); + this.sessionCache.set(url, connectionPool); + return session; + } + /** + * Delete a session from the connection pool. + * @param authority The authority of the session to delete. + * @param session The session to delete. + */ + deleteSession(authority, session) { + const existingConnectionPool = this.sessionCache.get(authority); + if (!existingConnectionPool) { + return; + } + if (!existingConnectionPool.contains(session)) { + return; + } + existingConnectionPool.remove(session); + this.sessionCache.set(authority, existingConnectionPool); + } + release(requestContext, session) { + const cacheKey = this.getUrlString(requestContext); + this.sessionCache.get(cacheKey)?.offerLast(session); + } + destroy() { + for (const [key, connectionPool] of this.sessionCache) { + for (const session of connectionPool) { + if (!session.destroyed) { + session.destroy(); + } + connectionPool.remove(session); + } + this.sessionCache.delete(key); + } + } + setMaxConcurrentStreams(maxConcurrentStreams) { + if (maxConcurrentStreams && maxConcurrentStreams <= 0) { + throw new RangeError("maxConcurrentStreams must be greater than zero."); + } + this.config.maxConcurrency = maxConcurrentStreams; + } + setDisableConcurrentStreams(disableConcurrentStreams) { + this.config.disableConcurrency = disableConcurrentStreams; + } + getUrlString(request) { + return request.destination.toString(); + } }; -var getHttpAuthSchemePlugin = /* @__PURE__ */ __name((config, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider -}) => ({ - applyToStack: (clientStack) => { - clientStack.addRelativeTo( - httpAuthSchemeMiddleware(config, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider - }), - httpAuthSchemeMiddlewareOptions - ); + +// src/node-http2-handler.ts +var NodeHttp2Handler = class _NodeHttp2Handler { + constructor(options) { + this.metadata = { handlerProtocol: "h2" }; + this.connectionManager = new NodeHttp2ConnectionManager({}); + this.configProvider = new Promise((resolve, reject) => { + if (typeof options === "function") { + options().then((opts) => { + resolve(opts || {}); + }).catch(reject); + } else { + resolve(options || {}); + } + }); + } + static { + __name(this, "NodeHttp2Handler"); + } + /** + * @returns the input if it is an HttpHandler of any class, + * or instantiates a new instance of this handler. + */ + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; + } + return new _NodeHttp2Handler(instanceOrOptions); + } + destroy() { + this.connectionManager.destroy(); + } + async handle(request, { abortSignal } = {}) { + if (!this.config) { + this.config = await this.configProvider; + this.connectionManager.setDisableConcurrentStreams(this.config.disableConcurrentStreams || false); + if (this.config.maxConcurrentStreams) { + this.connectionManager.setMaxConcurrentStreams(this.config.maxConcurrentStreams); + } + } + const { requestTimeout, disableConcurrentStreams } = this.config; + return new Promise((_resolve, _reject) => { + let fulfilled = false; + let writeRequestBodyPromise = void 0; + const resolve = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + _resolve(arg); + }, "resolve"); + const reject = /* @__PURE__ */ __name(async (arg) => { + await writeRequestBodyPromise; + _reject(arg); + }, "reject"); + if (abortSignal?.aborted) { + fulfilled = true; + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + return; + } + const { hostname, method, port, protocol, query } = request; + let auth = ""; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}@`; + } + const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : ""}`; + const requestContext = { destination: new URL(authority) }; + const session = this.connectionManager.lease(requestContext, { + requestTimeout: this.config?.sessionTimeout, + disableConcurrentStreams: disableConcurrentStreams || false + }); + const rejectWithDestroy = /* @__PURE__ */ __name((err) => { + if (disableConcurrentStreams) { + this.destroySession(session); + } + fulfilled = true; + reject(err); + }, "rejectWithDestroy"); + const queryString = (0, import_querystring_builder.buildQueryString)(query || {}); + let path = request.path; + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + const req = session.request({ + ...request.headers, + [import_http22.constants.HTTP2_HEADER_PATH]: path, + [import_http22.constants.HTTP2_HEADER_METHOD]: method + }); + session.ref(); + req.on("response", (headers) => { + const httpResponse = new import_protocol_http.HttpResponse({ + statusCode: headers[":status"] || -1, + headers: getTransformedHeaders(headers), + body: req + }); + fulfilled = true; + resolve({ response: httpResponse }); + if (disableConcurrentStreams) { + session.close(); + this.connectionManager.deleteSession(authority, session); + } + }); + if (requestTimeout) { + req.setTimeout(requestTimeout, () => { + req.close(); + const timeoutError = new Error(`Stream timed out because of no activity for ${requestTimeout} ms`); + timeoutError.name = "TimeoutError"; + rejectWithDestroy(timeoutError); + }); + } + if (abortSignal) { + const onAbort = /* @__PURE__ */ __name(() => { + req.close(); + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + rejectWithDestroy(abortError); + }, "onAbort"); + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + req.once("close", () => signal.removeEventListener("abort", onAbort)); + } else { + abortSignal.onabort = onAbort; + } + } + req.on("frameError", (type, code, id) => { + rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`)); + }); + req.on("error", rejectWithDestroy); + req.on("aborted", () => { + rejectWithDestroy( + new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${req.rstCode}.`) + ); + }); + req.on("close", () => { + session.unref(); + if (disableConcurrentStreams) { + session.destroy(); + } + if (!fulfilled) { + rejectWithDestroy(new Error("Unexpected error: http2 request did not get a response")); + } + }); + writeRequestBodyPromise = writeRequestBody(req, request, requestTimeout); + }); + } + updateHttpClientConfig(key, value) { + this.config = void 0; + this.configProvider = this.configProvider.then((config) => { + return { + ...config, + [key]: value + }; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } + /** + * Destroys a session. + * @param session - the session to destroy. + */ + destroySession(session) { + if (!session.destroyed) { + session.destroy(); + } } -}), "getHttpAuthSchemePlugin"); +}; -// src/middleware-http-signing/httpSigningMiddleware.ts -var import_protocol_http = __nccwpck_require__(64418); +// src/stream-collector/collector.ts -var defaultErrorHandler = /* @__PURE__ */ __name((signingProperties) => (error) => { - throw error; -}, "defaultErrorHandler"); -var defaultSuccessHandler = /* @__PURE__ */ __name((httpResponse, signingProperties) => { -}, "defaultSuccessHandler"); -var httpSigningMiddleware = /* @__PURE__ */ __name((config) => (next, context) => async (args) => { - if (!import_protocol_http.HttpRequest.isInstance(args.request)) { - return next(args); +var Collector = class extends import_stream.Writable { + constructor() { + super(...arguments); + this.bufferedBytes = []; } - const smithyContext = (0, import_util_middleware.getSmithyContext)(context); - const scheme = smithyContext.selectedHttpAuthScheme; - if (!scheme) { - throw new Error(`No HttpAuthScheme was selected: unable to sign request`); + static { + __name(this, "Collector"); } - const { - httpAuthOption: { signingProperties = {} }, - identity, - signer - } = scheme; - const output = await next({ - ...args, - request: await signer.sign(args.request, identity, signingProperties) - }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties)); - (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties); - return output; -}, "httpSigningMiddleware"); - -// src/middleware-http-signing/getHttpSigningMiddleware.ts -var httpSigningMiddlewareOptions = { - step: "finalizeRequest", - tags: ["HTTP_SIGNING"], - name: "httpSigningMiddleware", - aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"], - override: true, - relation: "after", - toMiddleware: "retryMiddleware" -}; -var getHttpSigningPlugin = /* @__PURE__ */ __name((config) => ({ - applyToStack: (clientStack) => { - clientStack.addRelativeTo(httpSigningMiddleware(config), httpSigningMiddlewareOptions); + _write(chunk, encoding, callback) { + this.bufferedBytes.push(chunk); + callback(); } -}), "getHttpSigningPlugin"); - -// src/normalizeProvider.ts -var normalizeProvider = /* @__PURE__ */ __name((input) => { - if (typeof input === "function") - return input; - const promisified = Promise.resolve(input); - return () => promisified; -}, "normalizeProvider"); +}; -// src/pagination/createPaginator.ts -var makePagedClientRequest = /* @__PURE__ */ __name(async (CommandCtor, client, input, withCommand = (_) => _, ...args) => { - let command = new CommandCtor(input); - command = withCommand(command) ?? command; - return await client.send(command, ...args); -}, "makePagedClientRequest"); -function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) { - return /* @__PURE__ */ __name(async function* paginateOperation(config, input, ...additionalArguments) { - const _input = input; - let token = config.startingToken ?? _input[inputTokenName]; - let hasNext = true; - let page; - while (hasNext) { - _input[inputTokenName] = token; - if (pageSizeTokenName) { - _input[pageSizeTokenName] = _input[pageSizeTokenName] ?? config.pageSize; - } - if (config.client instanceof ClientCtor) { - page = await makePagedClientRequest( - CommandCtor, - config.client, - input, - config.withCommand, - ...additionalArguments - ); - } else { - throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`); - } - yield page; - const prevToken = token; - token = get(page, outputTokenName); - hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); - } - return void 0; - }, "paginateOperation"); -} -__name(createPaginator, "createPaginator"); -var get = /* @__PURE__ */ __name((fromObject, path) => { - let cursor = fromObject; - const pathComponents = path.split("."); - for (const step of pathComponents) { - if (!cursor || typeof cursor !== "object") { - return void 0; +// src/stream-collector/index.ts +var streamCollector = /* @__PURE__ */ __name((stream) => { + if (isReadableStreamInstance(stream)) { + return collectReadableStream(stream); + } + return new Promise((resolve, reject) => { + const collector = new Collector(); + stream.pipe(collector); + stream.on("error", (err) => { + collector.end(); + reject(err); + }); + collector.on("error", reject); + collector.on("finish", function() { + const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes)); + resolve(bytes); + }); + }); +}, "streamCollector"); +var isReadableStreamInstance = /* @__PURE__ */ __name((stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream, "isReadableStreamInstance"); +async function collectReadableStream(stream) { + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + let length = 0; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + length += value.length; } - cursor = cursor[step]; + isDone = done; } - return cursor; -}, "get"); + const collected = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + collected.set(chunk, offset); + offset += chunk.length; + } + return collected; +} +__name(collectReadableStream, "collectReadableStream"); +// Annotate the CommonJS export names for ESM import in node: -// src/protocols/requestBuilder.ts -var import_protocols = __nccwpck_require__(2241); +0 && (0); -// src/setFeature.ts -function setFeature(context, feature, value) { - if (!context.__smithy_context) { - context.__smithy_context = { - features: {} - }; - } else if (!context.__smithy_context.features) { - context.__smithy_context.features = {}; + + +/***/ }), + +/***/ 79721: +/***/ ((module) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +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 }); } - context.__smithy_context.features[feature] = value; -} -__name(setFeature, "setFeature"); + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/util-identity-and-auth/DefaultIdentityProviderConfig.ts -var DefaultIdentityProviderConfig = class { - /** - * Creates an IdentityProviderConfig with a record of scheme IDs to identity providers. - * - * @param config scheme IDs and identity providers to configure - */ - constructor(config) { - this.authSchemes = /* @__PURE__ */ new Map(); - for (const [key, value] of Object.entries(config)) { - if (value !== void 0) { - this.authSchemes.set(key, value); - } +// src/index.ts +var src_exports = {}; +__export(src_exports, { + CredentialsProviderError: () => CredentialsProviderError, + ProviderError: () => ProviderError, + TokenProviderError: () => TokenProviderError, + chain: () => chain, + fromStatic: () => fromStatic, + memoize: () => memoize +}); +module.exports = __toCommonJS(src_exports); + +// src/ProviderError.ts +var ProviderError = class _ProviderError extends Error { + constructor(message, options = true) { + let logger; + let tryNextLink = true; + if (typeof options === "boolean") { + logger = void 0; + tryNextLink = options; + } else if (options != null && typeof options === "object") { + logger = options.logger; + tryNextLink = options.tryNextLink ?? true; } + super(message); + this.name = "ProviderError"; + this.tryNextLink = tryNextLink; + Object.setPrototypeOf(this, _ProviderError.prototype); + logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); } static { - __name(this, "DefaultIdentityProviderConfig"); + __name(this, "ProviderError"); } - getIdentityProvider(schemeId) { - return this.authSchemes.get(schemeId); + /** + * @deprecated use new operator. + */ + static from(error, options = true) { + return Object.assign(new this(error.message, options), error); } }; -// src/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.ts - - -var HttpApiKeyAuthSigner = class { - static { - __name(this, "HttpApiKeyAuthSigner"); +// src/CredentialsProviderError.ts +var CredentialsProviderError = class _CredentialsProviderError extends ProviderError { + /** + * @override + */ + constructor(message, options = true) { + super(message, options); + this.name = "CredentialsProviderError"; + Object.setPrototypeOf(this, _CredentialsProviderError.prototype); } - async sign(httpRequest, identity, signingProperties) { - if (!signingProperties) { - throw new Error( - "request could not be signed with `apiKey` since the `name` and `in` signer properties are missing" - ); - } - if (!signingProperties.name) { - throw new Error("request could not be signed with `apiKey` since the `name` signer property is missing"); - } - if (!signingProperties.in) { - throw new Error("request could not be signed with `apiKey` since the `in` signer property is missing"); - } - if (!identity.apiKey) { - throw new Error("request could not be signed with `apiKey` since the `apiKey` is not defined"); - } - const clonedRequest = import_protocol_http.HttpRequest.clone(httpRequest); - if (signingProperties.in === import_types.HttpApiKeyAuthLocation.QUERY) { - clonedRequest.query[signingProperties.name] = identity.apiKey; - } else if (signingProperties.in === import_types.HttpApiKeyAuthLocation.HEADER) { - clonedRequest.headers[signingProperties.name] = signingProperties.scheme ? `${signingProperties.scheme} ${identity.apiKey}` : identity.apiKey; - } else { - throw new Error( - "request can only be signed with `apiKey` locations `query` or `header`, but found: `" + signingProperties.in + "`" - ); - } - return clonedRequest; + static { + __name(this, "CredentialsProviderError"); } }; -// src/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.ts - -var HttpBearerAuthSigner = class { - static { - __name(this, "HttpBearerAuthSigner"); +// src/TokenProviderError.ts +var TokenProviderError = class _TokenProviderError extends ProviderError { + /** + * @override + */ + constructor(message, options = true) { + super(message, options); + this.name = "TokenProviderError"; + Object.setPrototypeOf(this, _TokenProviderError.prototype); } - async sign(httpRequest, identity, signingProperties) { - const clonedRequest = import_protocol_http.HttpRequest.clone(httpRequest); - if (!identity.token) { - throw new Error("request could not be signed with `token` since the `token` is not defined"); - } - clonedRequest.headers["Authorization"] = `Bearer ${identity.token}`; - return clonedRequest; + static { + __name(this, "TokenProviderError"); } }; -// src/util-identity-and-auth/httpAuthSchemes/noAuth.ts -var NoAuthSigner = class { - static { - __name(this, "NoAuthSigner"); +// src/chain.ts +var chain = /* @__PURE__ */ __name((...providers) => async () => { + if (providers.length === 0) { + throw new ProviderError("No providers in chain"); } - async sign(httpRequest, identity, signingProperties) { - return httpRequest; + let lastProviderError; + for (const provider of providers) { + try { + const credentials = await provider(); + return credentials; + } catch (err) { + lastProviderError = err; + if (err?.tryNextLink) { + continue; + } + throw err; + } } -}; + throw lastProviderError; +}, "chain"); -// src/util-identity-and-auth/memoizeIdentityProvider.ts -var createIsIdentityExpiredFunction = /* @__PURE__ */ __name((expirationMs) => (identity) => doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs, "createIsIdentityExpiredFunction"); -var EXPIRATION_MS = 3e5; -var isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS); -var doesIdentityRequireRefresh = /* @__PURE__ */ __name((identity) => identity.expiration !== void 0, "doesIdentityRequireRefresh"); -var memoizeIdentityProvider = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { - if (provider === void 0) { - return void 0; - } - const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider; +// src/fromStatic.ts +var fromStatic = /* @__PURE__ */ __name((staticValue) => () => Promise.resolve(staticValue), "fromStatic"); + +// src/memoize.ts +var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { let resolved; let pending; let hasResult; let isConstant = false; - const coalesceProvider = /* @__PURE__ */ __name(async (options) => { + const coalesceProvider = /* @__PURE__ */ __name(async () => { if (!pending) { - pending = normalizedProvider(options); + pending = provider(); } try { resolved = await pending; @@ -239709,29 +236572,29 @@ var memoizeIdentityProvider = /* @__PURE__ */ __name((provider, isExpired, requi if (isExpired === void 0) { return async (options) => { if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(options); + resolved = await coalesceProvider(); } return resolved; }; } return async (options) => { if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(options); + resolved = await coalesceProvider(); } if (isConstant) { return resolved; } - if (!requiresRefresh(resolved)) { + if (requiresRefresh && !requiresRefresh(resolved)) { isConstant = true; return resolved; } if (isExpired(resolved)) { - await coalesceProvider(options); + await coalesceProvider(); return resolved; } return resolved; }; -}, "memoizeIdentityProvider"); +}, "memoize"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -239740,13 +236603,14 @@ var memoizeIdentityProvider = /* @__PURE__ */ __name((provider, isExpired, requi /***/ }), -/***/ 2241: +/***/ 64418: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -239761,151 +236625,246 @@ var __copyProps = (to, from, except, desc) => { }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/submodules/protocols/index.ts -var protocols_exports = {}; -__export(protocols_exports, { - RequestBuilder: () => RequestBuilder, - collectBody: () => collectBody, - extendedEncodeURIComponent: () => extendedEncodeURIComponent, - requestBuilder: () => requestBuilder, - resolvedPath: () => resolvedPath +// src/index.ts +var src_exports = {}; +__export(src_exports, { + Field: () => Field, + Fields: () => Fields, + HttpRequest: () => HttpRequest, + HttpResponse: () => HttpResponse, + IHttpRequest: () => import_types.HttpRequest, + getHttpHandlerExtensionConfiguration: () => getHttpHandlerExtensionConfiguration, + isValidHostname: () => isValidHostname, + resolveHttpHandlerRuntimeConfig: () => resolveHttpHandlerRuntimeConfig }); -module.exports = __toCommonJS(protocols_exports); +module.exports = __toCommonJS(src_exports); -// src/submodules/protocols/collect-stream-body.ts -var import_util_stream = __nccwpck_require__(96607); -var collectBody = async (streamBody = new Uint8Array(), context) => { - if (streamBody instanceof Uint8Array) { - return import_util_stream.Uint8ArrayBlobAdapter.mutate(streamBody); +// src/extensions/httpExtensionConfiguration.ts +var getHttpHandlerExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + } + }; +}, "getHttpHandlerExtensionConfiguration"); +var resolveHttpHandlerRuntimeConfig = /* @__PURE__ */ __name((httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler() + }; +}, "resolveHttpHandlerRuntimeConfig"); + +// src/Field.ts +var import_types = __nccwpck_require__(55756); +var Field = class { + static { + __name(this, "Field"); } - if (!streamBody) { - return import_util_stream.Uint8ArrayBlobAdapter.mutate(new Uint8Array()); + constructor({ name, kind = import_types.FieldPosition.HEADER, values = [] }) { + this.name = name; + this.kind = kind; + this.values = values; } - const fromContext = context.streamCollector(streamBody); - return import_util_stream.Uint8ArrayBlobAdapter.mutate(await fromContext); -}; - -// src/submodules/protocols/extended-encode-uri-component.ts -function extendedEncodeURIComponent(str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { - return "%" + c.charCodeAt(0).toString(16).toUpperCase(); - }); -} - -// src/submodules/protocols/requestBuilder.ts -var import_protocol_http = __nccwpck_require__(64418); - -// src/submodules/protocols/resolve-path.ts -var resolvedPath = (resolvedPath2, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => { - if (input != null && input[memberName] !== void 0) { - const labelValue = labelValueProvider(); - if (labelValue.length <= 0) { - throw new Error("Empty value provided for input HTTP label: " + memberName + "."); - } - resolvedPath2 = resolvedPath2.replace( - uriLabel, - isGreedyLabel ? labelValue.split("/").map((segment) => extendedEncodeURIComponent(segment)).join("/") : extendedEncodeURIComponent(labelValue) - ); - } else { - throw new Error("No value provided for input HTTP label: " + memberName + "."); + /** + * Appends a value to the field. + * + * @param value The value to append. + */ + add(value) { + this.values.push(value); + } + /** + * Overwrite existing field values. + * + * @param values The new field values. + */ + set(values) { + this.values = values; + } + /** + * Remove all matching entries from list. + * + * @param value Value to remove. + */ + remove(value) { + this.values = this.values.filter((v) => v !== value); + } + /** + * Get comma-delimited string. + * + * @returns String representation of {@link Field}. + */ + toString() { + return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", "); + } + /** + * Get string values as a list + * + * @returns Values in {@link Field} as a list. + */ + get() { + return this.values; } - return resolvedPath2; }; -// src/submodules/protocols/requestBuilder.ts -function requestBuilder(input, context) { - return new RequestBuilder(input, context); -} -var RequestBuilder = class { - constructor(input, context) { - this.input = input; - this.context = context; - this.query = {}; - this.method = ""; - this.headers = {}; - this.path = ""; - this.body = null; - this.hostname = ""; - this.resolvePathStack = []; +// src/Fields.ts +var Fields = class { + constructor({ fields = [], encoding = "utf-8" }) { + this.entries = {}; + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; } - async build() { - const { hostname, protocol = "https", port, path: basePath } = await this.context.endpoint(); - this.path = basePath; - for (const resolvePath of this.resolvePathStack) { - resolvePath(this.path); - } - return new import_protocol_http.HttpRequest({ - protocol, - hostname: this.hostname || hostname, - port, - method: this.method, - path: this.path, - query: this.query, - body: this.body, - headers: this.headers - }); + static { + __name(this, "Fields"); } /** - * Brevity setter for "hostname". + * Set entry for a {@link Field} name. The `name` + * attribute will be used to key the collection. + * + * @param field The {@link Field} to set. */ - hn(hostname) { - this.hostname = hostname; - return this; + setField(field) { + this.entries[field.name.toLowerCase()] = field; } /** - * Brevity initial builder for "basepath". + * Retrieve {@link Field} entry by name. + * + * @param name The name of the {@link Field} entry + * to retrieve + * @returns The {@link Field} if it exists. */ - bp(uriLabel) { - this.resolvePathStack.push((basePath) => { - this.path = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + uriLabel; - }); - return this; + getField(name) { + return this.entries[name.toLowerCase()]; } /** - * Brevity incremental builder for "path". + * Delete entry from collection. + * + * @param name Name of the entry to delete. */ - p(memberName, labelValueProvider, uriLabel, isGreedyLabel) { - this.resolvePathStack.push((path) => { - this.path = resolvedPath(path, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel); - }); - return this; + removeField(name) { + delete this.entries[name.toLowerCase()]; } /** - * Brevity setter for "headers". + * Helper function for retrieving specific types of fields. + * Used to grab all headers or all trailers. + * + * @param kind {@link FieldPosition} of entries to retrieve. + * @returns The {@link Field} entries with the specified + * {@link FieldPosition}. */ - h(headers) { - this.headers = headers; - return this; + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } +}; + +// src/httpRequest.ts + +var HttpRequest = class _HttpRequest { + static { + __name(this, "HttpRequest"); + } + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:"; + this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; } /** - * Brevity setter for "query". + * Note: this does not deep-clone the body. */ - q(query) { - this.query = query; - return this; + static clone(request) { + const cloned = new _HttpRequest({ + ...request, + headers: { ...request.headers } + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; } /** - * Brevity setter for "body". + * This method only actually asserts that request is the interface {@link IHttpRequest}, + * and not necessarily this concrete class. Left in place for API stability. + * + * Do not call instance methods on the input of this function, and + * do not assume it has the HttpRequest prototype. */ - b(body) { - this.body = body; - return this; + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object"; } /** - * Brevity setter for "method". + * @deprecated use static HttpRequest.clone(request) instead. It's not safe to call + * this method because {@link HttpRequest.isInstance} incorrectly + * asserts that IHttpRequest (interface) objects are of type HttpRequest (class). */ - m(method) { - this.method = method; - return this; + clone() { + return _HttpRequest.clone(this); + } +}; +function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param + }; + }, {}); +} +__name(cloneQuery, "cloneQuery"); + +// src/httpResponse.ts +var HttpResponse = class { + static { + __name(this, "HttpResponse"); + } + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; } }; + +// src/isValidHostname.ts +function isValidHostname(hostname) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname); +} +__name(isValidHostname, "isValidHostname"); // Annotate the CommonJS export names for ESM import in node: + 0 && (0); + /***/ }), -/***/ 7477: +/***/ 68031: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; @@ -239930,413 +236889,452 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var src_exports = {}; __export(src_exports, { - DEFAULT_MAX_RETRIES: () => DEFAULT_MAX_RETRIES, - DEFAULT_TIMEOUT: () => DEFAULT_TIMEOUT, - ENV_CMDS_AUTH_TOKEN: () => ENV_CMDS_AUTH_TOKEN, - ENV_CMDS_FULL_URI: () => ENV_CMDS_FULL_URI, - ENV_CMDS_RELATIVE_URI: () => ENV_CMDS_RELATIVE_URI, - Endpoint: () => Endpoint, - fromContainerMetadata: () => fromContainerMetadata, - fromInstanceMetadata: () => fromInstanceMetadata, - getInstanceMetadataEndpoint: () => getInstanceMetadataEndpoint, - httpRequest: () => httpRequest, - providerConfigFromInit: () => providerConfigFromInit + buildQueryString: () => buildQueryString }); module.exports = __toCommonJS(src_exports); +var import_util_uri_escape = __nccwpck_require__(54197); +function buildQueryString(query) { + const parts = []; + for (let key of Object.keys(query).sort()) { + const value = query[key]; + key = (0, import_util_uri_escape.escapeUri)(key); + if (Array.isArray(value)) { + for (let i = 0, iLen = value.length; i < iLen; i++) { + parts.push(`${key}=${(0, import_util_uri_escape.escapeUri)(value[i])}`); + } + } else { + let qsEntry = key; + if (value || typeof value === "string") { + qsEntry += `=${(0, import_util_uri_escape.escapeUri)(value)}`; + } + parts.push(qsEntry); + } + } + return parts.join("&"); +} +__name(buildQueryString, "buildQueryString"); +// Annotate the CommonJS export names for ESM import in node: -// src/fromContainerMetadata.ts +0 && (0); -var import_url = __nccwpck_require__(57310); -// src/remoteProvider/httpRequest.ts -var import_property_provider = __nccwpck_require__(79721); -var import_buffer = __nccwpck_require__(14300); -var import_http = __nccwpck_require__(13685); -function httpRequest(options) { - return new Promise((resolve, reject) => { - const req = (0, import_http.request)({ - method: "GET", - ...options, - // Node.js http module doesn't accept hostname with square brackets - // Refs: https://github.com/nodejs/node/issues/39738 - hostname: options.hostname?.replace(/^\[(.+)\]$/, "$1") - }); - req.on("error", (err) => { - reject(Object.assign(new import_property_provider.ProviderError("Unable to connect to instance metadata service"), err)); - req.destroy(); - }); - req.on("timeout", () => { - reject(new import_property_provider.ProviderError("TimeoutError from instance metadata service")); - req.destroy(); - }); - req.on("response", (res) => { - const { statusCode = 400 } = res; - if (statusCode < 200 || 300 <= statusCode) { - reject( - Object.assign(new import_property_provider.ProviderError("Error response received from instance metadata service"), { statusCode }) - ); - req.destroy(); - } - const chunks = []; - res.on("data", (chunk) => { - chunks.push(chunk); - }); - res.on("end", () => { - resolve(import_buffer.Buffer.concat(chunks)); - req.destroy(); - }); - }); - req.end(); - }); -} -__name(httpRequest, "httpRequest"); -// src/remoteProvider/ImdsCredentials.ts -var isImdsCredentials = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.AccessKeyId === "string" && typeof arg.SecretAccessKey === "string" && typeof arg.Token === "string" && typeof arg.Expiration === "string", "isImdsCredentials"); -var fromImdsCredentials = /* @__PURE__ */ __name((creds) => ({ - accessKeyId: creds.AccessKeyId, - secretAccessKey: creds.SecretAccessKey, - sessionToken: creds.Token, - expiration: new Date(creds.Expiration), - ...creds.AccountId && { accountId: creds.AccountId } -}), "fromImdsCredentials"); +/***/ }), -// src/remoteProvider/RemoteProviderInit.ts -var DEFAULT_TIMEOUT = 1e3; -var DEFAULT_MAX_RETRIES = 0; -var providerConfigFromInit = /* @__PURE__ */ __name(({ - maxRetries = DEFAULT_MAX_RETRIES, - timeout = DEFAULT_TIMEOUT -}) => ({ maxRetries, timeout }), "providerConfigFromInit"); +/***/ 4769: +/***/ ((module) => { -// src/remoteProvider/retry.ts -var retry = /* @__PURE__ */ __name((toRetry, maxRetries) => { - let promise = toRetry(); - for (let i = 0; i < maxRetries; i++) { - promise = promise.catch(toRetry); +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +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 promise; -}, "retry"); + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/fromContainerMetadata.ts -var ENV_CMDS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; -var ENV_CMDS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; -var ENV_CMDS_AUTH_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; -var fromContainerMetadata = /* @__PURE__ */ __name((init = {}) => { - const { timeout, maxRetries } = providerConfigFromInit(init); - return () => retry(async () => { - const requestOptions = await getCmdsUri({ logger: init.logger }); - const credsResponse = JSON.parse(await requestFromEcsImds(timeout, requestOptions)); - if (!isImdsCredentials(credsResponse)) { - throw new import_property_provider.CredentialsProviderError("Invalid response received from instance metadata service.", { - logger: init.logger - }); +// src/index.ts +var src_exports = {}; +__export(src_exports, { + parseQueryString: () => parseQueryString +}); +module.exports = __toCommonJS(src_exports); +function parseQueryString(querystring) { + const query = {}; + querystring = querystring.replace(/^\?/, ""); + if (querystring) { + for (const pair of querystring.split("&")) { + let [key, value = null] = pair.split("="); + key = decodeURIComponent(key); + if (value) { + value = decodeURIComponent(value); + } + if (!(key in query)) { + query[key] = value; + } else if (Array.isArray(query[key])) { + query[key].push(value); + } else { + query[key] = [query[key], value]; + } } - return fromImdsCredentials(credsResponse); - }, maxRetries); -}, "fromContainerMetadata"); -var requestFromEcsImds = /* @__PURE__ */ __name(async (timeout, options) => { - if (process.env[ENV_CMDS_AUTH_TOKEN]) { - options.headers = { - ...options.headers, - Authorization: process.env[ENV_CMDS_AUTH_TOKEN] - }; } - const buffer = await httpRequest({ - ...options, - timeout - }); - return buffer.toString(); -}, "requestFromEcsImds"); -var CMDS_IP = "169.254.170.2"; -var GREENGRASS_HOSTS = { - localhost: true, - "127.0.0.1": true -}; -var GREENGRASS_PROTOCOLS = { - "http:": true, - "https:": true + return query; +} +__name(parseQueryString, "parseQueryString"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 6375: +/***/ ((module) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); }; -var getCmdsUri = /* @__PURE__ */ __name(async ({ logger }) => { - if (process.env[ENV_CMDS_RELATIVE_URI]) { - return { - hostname: CMDS_IP, - path: process.env[ENV_CMDS_RELATIVE_URI] - }; +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 }); } - if (process.env[ENV_CMDS_FULL_URI]) { - const parsed = (0, import_url.parse)(process.env[ENV_CMDS_FULL_URI]); - if (!parsed.hostname || !(parsed.hostname in GREENGRASS_HOSTS)) { - throw new import_property_provider.CredentialsProviderError(`${parsed.hostname} is not a valid container metadata service hostname`, { - tryNextLink: false, - logger - }); - } - if (!parsed.protocol || !(parsed.protocol in GREENGRASS_PROTOCOLS)) { - throw new import_property_provider.CredentialsProviderError(`${parsed.protocol} is not a valid container metadata service protocol`, { - tryNextLink: false, - logger - }); + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + isClockSkewCorrectedError: () => isClockSkewCorrectedError, + isClockSkewError: () => isClockSkewError, + isRetryableByTrait: () => isRetryableByTrait, + isServerError: () => isServerError, + isThrottlingError: () => isThrottlingError, + isTransientError: () => isTransientError +}); +module.exports = __toCommonJS(src_exports); + +// src/constants.ts +var CLOCK_SKEW_ERROR_CODES = [ + "AuthFailure", + "InvalidSignatureException", + "RequestExpired", + "RequestInTheFuture", + "RequestTimeTooSkewed", + "SignatureDoesNotMatch" +]; +var THROTTLING_ERROR_CODES = [ + "BandwidthLimitExceeded", + "EC2ThrottledException", + "LimitExceededException", + "PriorRequestNotComplete", + "ProvisionedThroughputExceededException", + "RequestLimitExceeded", + "RequestThrottled", + "RequestThrottledException", + "SlowDown", + "ThrottledException", + "Throttling", + "ThrottlingException", + "TooManyRequestsException", + "TransactionInProgressException" + // DynamoDB +]; +var TRANSIENT_ERROR_CODES = ["TimeoutError", "RequestTimeout", "RequestTimeoutException"]; +var TRANSIENT_ERROR_STATUS_CODES = [500, 502, 503, 504]; +var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT"]; + +// src/index.ts +var isRetryableByTrait = /* @__PURE__ */ __name((error) => error.$retryable !== void 0, "isRetryableByTrait"); +var isClockSkewError = /* @__PURE__ */ __name((error) => CLOCK_SKEW_ERROR_CODES.includes(error.name), "isClockSkewError"); +var isClockSkewCorrectedError = /* @__PURE__ */ __name((error) => error.$metadata?.clockSkewCorrected, "isClockSkewCorrectedError"); +var isThrottlingError = /* @__PURE__ */ __name((error) => error.$metadata?.httpStatusCode === 429 || THROTTLING_ERROR_CODES.includes(error.name) || error.$retryable?.throttling == true, "isThrottlingError"); +var isTransientError = /* @__PURE__ */ __name((error, depth = 0) => isClockSkewCorrectedError(error) || TRANSIENT_ERROR_CODES.includes(error.name) || NODEJS_TIMEOUT_ERROR_CODES.includes(error?.code || "") || TRANSIENT_ERROR_STATUS_CODES.includes(error.$metadata?.httpStatusCode || 0) || error.cause !== void 0 && depth <= 10 && isTransientError(error.cause, depth + 1), "isTransientError"); +var isServerError = /* @__PURE__ */ __name((error) => { + if (error.$metadata?.httpStatusCode !== void 0) { + const statusCode = error.$metadata.httpStatusCode; + if (500 <= statusCode && statusCode <= 599 && !isTransientError(error)) { + return true; } - return { - ...parsed, - port: parsed.port ? parseInt(parsed.port, 10) : void 0 - }; + return false; } - throw new import_property_provider.CredentialsProviderError( - `The container metadata credential provider cannot be used unless the ${ENV_CMDS_RELATIVE_URI} or ${ENV_CMDS_FULL_URI} environment variable is set`, - { - tryNextLink: false, - logger + return false; +}, "isServerError"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 68340: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getHomeDir = void 0; +const os_1 = __nccwpck_require__(22037); +const path_1 = __nccwpck_require__(71017); +const homeDirCache = {}; +const getHomeDirCacheKey = () => { + if (process && process.geteuid) { + return `${process.geteuid()}`; } - ); -}, "getCmdsUri"); + return "DEFAULT"; +}; +const getHomeDir = () => { + const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${path_1.sep}` } = process.env; + if (HOME) + return HOME; + if (USERPROFILE) + return USERPROFILE; + if (HOMEPATH) + return `${HOMEDRIVE}${HOMEPATH}`; + const homeDirCacheKey = getHomeDirCacheKey(); + if (!homeDirCache[homeDirCacheKey]) + homeDirCache[homeDirCacheKey] = (0, os_1.homedir)(); + return homeDirCache[homeDirCacheKey]; +}; +exports.getHomeDir = getHomeDir; + + +/***/ }), + +/***/ 24740: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getSSOTokenFilepath = void 0; +const crypto_1 = __nccwpck_require__(6113); +const path_1 = __nccwpck_require__(71017); +const getHomeDir_1 = __nccwpck_require__(68340); +const getSSOTokenFilepath = (id) => { + const hasher = (0, crypto_1.createHash)("sha1"); + const cacheName = hasher.update(id).digest("hex"); + return (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "sso", "cache", `${cacheName}.json`); +}; +exports.getSSOTokenFilepath = getSSOTokenFilepath; -// src/fromInstanceMetadata.ts +/***/ }), +/***/ 69678: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// src/error/InstanceMetadataV1FallbackError.ts +"use strict"; -var InstanceMetadataV1FallbackError = class _InstanceMetadataV1FallbackError extends import_property_provider.CredentialsProviderError { - constructor(message, tryNextLink = true) { - super(message, tryNextLink); - this.tryNextLink = tryNextLink; - this.name = "InstanceMetadataV1FallbackError"; - Object.setPrototypeOf(this, _InstanceMetadataV1FallbackError.prototype); - } - static { - __name(this, "InstanceMetadataV1FallbackError"); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getSSOTokenFromFile = void 0; +const fs_1 = __nccwpck_require__(57147); +const getSSOTokenFilepath_1 = __nccwpck_require__(24740); +const { readFile } = fs_1.promises; +const getSSOTokenFromFile = async (id) => { + const ssoTokenFilepath = (0, getSSOTokenFilepath_1.getSSOTokenFilepath)(id); + const ssoTokenText = await readFile(ssoTokenFilepath, "utf8"); + return JSON.parse(ssoTokenText); }; +exports.getSSOTokenFromFile = getSSOTokenFromFile; -// src/utils/getInstanceMetadataEndpoint.ts -var import_node_config_provider = __nccwpck_require__(33461); -var import_url_parser = __nccwpck_require__(14681); -// src/config/Endpoint.ts -var Endpoint = /* @__PURE__ */ ((Endpoint2) => { - Endpoint2["IPv4"] = "http://169.254.169.254"; - Endpoint2["IPv6"] = "http://[fd00:ec2::254]"; - return Endpoint2; -})(Endpoint || {}); +/***/ }), -// src/config/EndpointConfigOptions.ts -var ENV_ENDPOINT_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT"; -var CONFIG_ENDPOINT_NAME = "ec2_metadata_service_endpoint"; -var ENDPOINT_CONFIG_OPTIONS = { - environmentVariableSelector: (env) => env[ENV_ENDPOINT_NAME], - configFileSelector: (profile) => profile[CONFIG_ENDPOINT_NAME], - default: void 0 +/***/ 43507: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +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 __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/config/EndpointMode.ts -var EndpointMode = /* @__PURE__ */ ((EndpointMode2) => { - EndpointMode2["IPv4"] = "IPv4"; - EndpointMode2["IPv6"] = "IPv6"; - return EndpointMode2; -})(EndpointMode || {}); +// src/index.ts +var src_exports = {}; +__export(src_exports, { + CONFIG_PREFIX_SEPARATOR: () => CONFIG_PREFIX_SEPARATOR, + DEFAULT_PROFILE: () => DEFAULT_PROFILE, + ENV_PROFILE: () => ENV_PROFILE, + getProfileName: () => getProfileName, + loadSharedConfigFiles: () => loadSharedConfigFiles, + loadSsoSessionData: () => loadSsoSessionData, + parseKnownFiles: () => parseKnownFiles +}); +module.exports = __toCommonJS(src_exports); +__reExport(src_exports, __nccwpck_require__(68340), module.exports); -// src/config/EndpointModeConfigOptions.ts -var ENV_ENDPOINT_MODE_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE"; -var CONFIG_ENDPOINT_MODE_NAME = "ec2_metadata_service_endpoint_mode"; -var ENDPOINT_MODE_CONFIG_OPTIONS = { - environmentVariableSelector: (env) => env[ENV_ENDPOINT_MODE_NAME], - configFileSelector: (profile) => profile[CONFIG_ENDPOINT_MODE_NAME], - default: "IPv4" /* IPv4 */ -}; +// src/getProfileName.ts +var ENV_PROFILE = "AWS_PROFILE"; +var DEFAULT_PROFILE = "default"; +var getProfileName = /* @__PURE__ */ __name((init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE, "getProfileName"); -// src/utils/getInstanceMetadataEndpoint.ts -var getInstanceMetadataEndpoint = /* @__PURE__ */ __name(async () => (0, import_url_parser.parseUrl)(await getFromEndpointConfig() || await getFromEndpointModeConfig()), "getInstanceMetadataEndpoint"); -var getFromEndpointConfig = /* @__PURE__ */ __name(async () => (0, import_node_config_provider.loadConfig)(ENDPOINT_CONFIG_OPTIONS)(), "getFromEndpointConfig"); -var getFromEndpointModeConfig = /* @__PURE__ */ __name(async () => { - const endpointMode = await (0, import_node_config_provider.loadConfig)(ENDPOINT_MODE_CONFIG_OPTIONS)(); - switch (endpointMode) { - case "IPv4" /* IPv4 */: - return "http://169.254.169.254" /* IPv4 */; - case "IPv6" /* IPv6 */: - return "http://[fd00:ec2::254]" /* IPv6 */; - default: - throw new Error(`Unsupported endpoint mode: ${endpointMode}. Select from ${Object.values(EndpointMode)}`); +// src/index.ts +__reExport(src_exports, __nccwpck_require__(24740), module.exports); +__reExport(src_exports, __nccwpck_require__(69678), module.exports); + +// src/loadSharedConfigFiles.ts + + +// src/getConfigData.ts +var import_types = __nccwpck_require__(55756); +var getConfigData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + if (indexOfSeparator === -1) { + return false; } -}, "getFromEndpointModeConfig"); + return Object.values(import_types.IniSectionType).includes(key.substring(0, indexOfSeparator)); +}).reduce( + (acc, [key, value]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + const updatedKey = key.substring(0, indexOfSeparator) === import_types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; + acc[updatedKey] = value; + return acc; + }, + { + // Populate default profile, if present. + ...data.default && { default: data.default } + } +), "getConfigData"); -// src/utils/getExtendedInstanceMetadataCredentials.ts -var STATIC_STABILITY_REFRESH_INTERVAL_SECONDS = 5 * 60; -var STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS = 5 * 60; -var STATIC_STABILITY_DOC_URL = "https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html"; -var getExtendedInstanceMetadataCredentials = /* @__PURE__ */ __name((credentials, logger) => { - const refreshInterval = STATIC_STABILITY_REFRESH_INTERVAL_SECONDS + Math.floor(Math.random() * STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS); - const newExpiration = new Date(Date.now() + refreshInterval * 1e3); - logger.warn( - `Attempting credential expiration extension due to a credential service availability issue. A refresh of these credentials will be attempted after ${new Date(newExpiration)}. -For more information, please visit: ` + STATIC_STABILITY_DOC_URL - ); - const originalExpiration = credentials.originalExpiration ?? credentials.expiration; - return { - ...credentials, - ...originalExpiration ? { originalExpiration } : {}, - expiration: newExpiration - }; -}, "getExtendedInstanceMetadataCredentials"); +// src/getConfigFilepath.ts +var import_path = __nccwpck_require__(71017); +var import_getHomeDir = __nccwpck_require__(68340); +var ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; +var getConfigFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CONFIG_PATH] || (0, import_path.join)((0, import_getHomeDir.getHomeDir)(), ".aws", "config"), "getConfigFilepath"); -// src/utils/staticStabilityProvider.ts -var staticStabilityProvider = /* @__PURE__ */ __name((provider, options = {}) => { - const logger = options?.logger || console; - let pastCredentials; - return async () => { - let credentials; - try { - credentials = await provider(); - if (credentials.expiration && credentials.expiration.getTime() < Date.now()) { - credentials = getExtendedInstanceMetadataCredentials(credentials, logger); - } - } catch (e) { - if (pastCredentials) { - logger.warn("Credential renew failed: ", e); - credentials = getExtendedInstanceMetadataCredentials(pastCredentials, logger); - } else { - throw e; - } - } - pastCredentials = credentials; - return credentials; - }; -}, "staticStabilityProvider"); +// src/getCredentialsFilepath.ts -// src/fromInstanceMetadata.ts -var IMDS_PATH = "/latest/meta-data/iam/security-credentials/"; -var IMDS_TOKEN_PATH = "/latest/api/token"; -var AWS_EC2_METADATA_V1_DISABLED = "AWS_EC2_METADATA_V1_DISABLED"; -var PROFILE_AWS_EC2_METADATA_V1_DISABLED = "ec2_metadata_v1_disabled"; -var X_AWS_EC2_METADATA_TOKEN = "x-aws-ec2-metadata-token"; -var fromInstanceMetadata = /* @__PURE__ */ __name((init = {}) => staticStabilityProvider(getInstanceMetadataProvider(init), { logger: init.logger }), "fromInstanceMetadata"); -var getInstanceMetadataProvider = /* @__PURE__ */ __name((init = {}) => { - let disableFetchToken = false; - const { logger, profile } = init; - const { timeout, maxRetries } = providerConfigFromInit(init); - const getCredentials = /* @__PURE__ */ __name(async (maxRetries2, options) => { - const isImdsV1Fallback = disableFetchToken || options.headers?.[X_AWS_EC2_METADATA_TOKEN] == null; - if (isImdsV1Fallback) { - let fallbackBlockedFromProfile = false; - let fallbackBlockedFromProcessEnv = false; - const configValue = await (0, import_node_config_provider.loadConfig)( - { - environmentVariableSelector: (env) => { - const envValue = env[AWS_EC2_METADATA_V1_DISABLED]; - fallbackBlockedFromProcessEnv = !!envValue && envValue !== "false"; - if (envValue === void 0) { - throw new import_property_provider.CredentialsProviderError( - `${AWS_EC2_METADATA_V1_DISABLED} not set in env, checking config file next.`, - { logger: init.logger } - ); - } - return fallbackBlockedFromProcessEnv; - }, - configFileSelector: (profile2) => { - const profileValue = profile2[PROFILE_AWS_EC2_METADATA_V1_DISABLED]; - fallbackBlockedFromProfile = !!profileValue && profileValue !== "false"; - return fallbackBlockedFromProfile; - }, - default: false - }, - { - profile - } - )(); - if (init.ec2MetadataV1Disabled || configValue) { - const causes = []; - if (init.ec2MetadataV1Disabled) - causes.push("credential provider initialization (runtime option ec2MetadataV1Disabled)"); - if (fallbackBlockedFromProfile) - causes.push(`config file profile (${PROFILE_AWS_EC2_METADATA_V1_DISABLED})`); - if (fallbackBlockedFromProcessEnv) - causes.push(`process environment variable (${AWS_EC2_METADATA_V1_DISABLED})`); - throw new InstanceMetadataV1FallbackError( - `AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${causes.join( - ", " - )}].` - ); - } - } - const imdsProfile = (await retry(async () => { - let profile2; - try { - profile2 = await getProfile(options); - } catch (err) { - if (err.statusCode === 401) { - disableFetchToken = false; +var import_getHomeDir2 = __nccwpck_require__(68340); +var ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; +var getCredentialsFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CREDENTIALS_PATH] || (0, import_path.join)((0, import_getHomeDir2.getHomeDir)(), ".aws", "credentials"), "getCredentialsFilepath"); + +// src/loadSharedConfigFiles.ts +var import_getHomeDir3 = __nccwpck_require__(68340); + +// src/parseIni.ts + +var prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/; +var profileNameBlockList = ["__proto__", "profile __proto__"]; +var parseIni = /* @__PURE__ */ __name((iniData) => { + const map = {}; + let currentSection; + let currentSubSection; + for (const iniLine of iniData.split(/\r?\n/)) { + const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); + const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; + if (isSection) { + currentSection = void 0; + currentSubSection = void 0; + const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); + const matches = prefixKeyRegex.exec(sectionName); + if (matches) { + const [, prefix, , name] = matches; + if (Object.values(import_types.IniSectionType).includes(prefix)) { + currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR); } - throw err; + } else { + currentSection = sectionName; } - return profile2; - }, maxRetries2)).trim(); - return retry(async () => { - let creds; - try { - creds = await getCredentialsFromProfile(imdsProfile, options, init); - } catch (err) { - if (err.statusCode === 401) { - disableFetchToken = false; - } - throw err; + if (profileNameBlockList.includes(sectionName)) { + throw new Error(`Found invalid profile name "${sectionName}"`); } - return creds; - }, maxRetries2); - }, "getCredentials"); - return async () => { - const endpoint = await getInstanceMetadataEndpoint(); - if (disableFetchToken) { - logger?.debug("AWS SDK Instance Metadata", "using v1 fallback (no token fetch)"); - return getCredentials(maxRetries, { ...endpoint, timeout }); - } else { - let token; - try { - token = (await getMetadataToken({ ...endpoint, timeout })).toString(); - } catch (error) { - if (error?.statusCode === 400) { - throw Object.assign(error, { - message: "EC2 Metadata token request returned error" - }); - } else if (error.message === "TimeoutError" || [403, 404, 405].includes(error.statusCode)) { - disableFetchToken = true; + } else if (currentSection) { + const indexOfEqualsSign = trimmedLine.indexOf("="); + if (![0, -1].includes(indexOfEqualsSign)) { + const [name, value] = [ + trimmedLine.substring(0, indexOfEqualsSign).trim(), + trimmedLine.substring(indexOfEqualsSign + 1).trim() + ]; + if (value === "") { + currentSubSection = name; + } else { + if (currentSubSection && iniLine.trimStart() === iniLine) { + currentSubSection = void 0; + } + map[currentSection] = map[currentSection] || {}; + const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; + map[currentSection][key] = value; } - logger?.debug("AWS SDK Instance Metadata", "using v1 fallback (initial)"); - return getCredentials(maxRetries, { ...endpoint, timeout }); } - return getCredentials(maxRetries, { - ...endpoint, - headers: { - [X_AWS_EC2_METADATA_TOKEN]: token - }, - timeout - }); } - }; -}, "getInstanceMetadataProvider"); -var getMetadataToken = /* @__PURE__ */ __name(async (options) => httpRequest({ - ...options, - path: IMDS_TOKEN_PATH, - method: "PUT", - headers: { - "x-aws-ec2-metadata-token-ttl-seconds": "21600" } -}), "getMetadataToken"); -var getProfile = /* @__PURE__ */ __name(async (options) => (await httpRequest({ ...options, path: IMDS_PATH })).toString(), "getProfile"); -var getCredentialsFromProfile = /* @__PURE__ */ __name(async (profile, options, init) => { - const credentialsResponse = JSON.parse( - (await httpRequest({ - ...options, - path: IMDS_PATH + profile - })).toString() - ); - if (!isImdsCredentials(credentialsResponse)) { - throw new import_property_provider.CredentialsProviderError("Invalid response received from instance metadata service.", { - logger: init.logger - }); + return map; +}, "parseIni"); + +// src/loadSharedConfigFiles.ts +var import_slurpFile = __nccwpck_require__(19155); +var swallowError = /* @__PURE__ */ __name(() => ({}), "swallowError"); +var CONFIG_PREFIX_SEPARATOR = "."; +var loadSharedConfigFiles = /* @__PURE__ */ __name(async (init = {}) => { + const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init; + const homeDir = (0, import_getHomeDir3.getHomeDir)(); + const relativeHomeDirPrefix = "~/"; + let resolvedFilepath = filepath; + if (filepath.startsWith(relativeHomeDirPrefix)) { + resolvedFilepath = (0, import_path.join)(homeDir, filepath.slice(2)); } - return fromImdsCredentials(credentialsResponse); -}, "getCredentialsFromProfile"); + let resolvedConfigFilepath = configFilepath; + if (configFilepath.startsWith(relativeHomeDirPrefix)) { + resolvedConfigFilepath = (0, import_path.join)(homeDir, configFilepath.slice(2)); + } + const parsedFiles = await Promise.all([ + (0, import_slurpFile.slurpFile)(resolvedConfigFilepath, { + ignoreCache: init.ignoreCache + }).then(parseIni).then(getConfigData).catch(swallowError), + (0, import_slurpFile.slurpFile)(resolvedFilepath, { + ignoreCache: init.ignoreCache + }).then(parseIni).catch(swallowError) + ]); + return { + configFile: parsedFiles[0], + credentialsFile: parsedFiles[1] + }; +}, "loadSharedConfigFiles"); + +// src/getSsoSessionData.ts + +var getSsoSessionData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => key.startsWith(import_types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}), "getSsoSessionData"); + +// src/loadSsoSessionData.ts +var import_slurpFile2 = __nccwpck_require__(19155); +var swallowError2 = /* @__PURE__ */ __name(() => ({}), "swallowError"); +var loadSsoSessionData = /* @__PURE__ */ __name(async (init = {}) => (0, import_slurpFile2.slurpFile)(init.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError2), "loadSsoSessionData"); + +// src/mergeConfigFiles.ts +var mergeConfigFiles = /* @__PURE__ */ __name((...files) => { + const merged = {}; + for (const file of files) { + for (const [key, values] of Object.entries(file)) { + if (merged[key] !== void 0) { + Object.assign(merged[key], values); + } else { + merged[key] = values; + } + } + } + return merged; +}, "mergeConfigFiles"); + +// src/parseKnownFiles.ts +var parseKnownFiles = /* @__PURE__ */ __name(async (init) => { + const parsedFiles = await loadSharedConfigFiles(init); + return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); +}, "parseKnownFiles"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -240345,7 +237343,28 @@ var getCredentialsFromProfile = /* @__PURE__ */ __name(async (profile, options, /***/ }), -/***/ 56459: +/***/ 19155: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.slurpFile = void 0; +const fs_1 = __nccwpck_require__(57147); +const { readFile } = fs_1.promises; +const filePromisesHash = {}; +const slurpFile = (path, options) => { + if (!filePromisesHash[path] || (options === null || options === void 0 ? void 0 : options.ignoreCache)) { + filePromisesHash[path] = readFile(path, "utf8"); + } + return filePromisesHash[path]; +}; +exports.slurpFile = slurpFile; + + +/***/ }), + +/***/ 11528: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; @@ -240370,87 +237389,169 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var src_exports = {}; __export(src_exports, { - EventStreamCodec: () => EventStreamCodec, - HeaderMarshaller: () => HeaderMarshaller, - Int64: () => Int64, - MessageDecoderStream: () => MessageDecoderStream, - MessageEncoderStream: () => MessageEncoderStream, - SmithyMessageDecoderStream: () => SmithyMessageDecoderStream, - SmithyMessageEncoderStream: () => SmithyMessageEncoderStream + SignatureV4: () => SignatureV4, + clearCredentialCache: () => clearCredentialCache, + createScope: () => createScope, + getCanonicalHeaders: () => getCanonicalHeaders, + getCanonicalQuery: () => getCanonicalQuery, + getPayloadHash: () => getPayloadHash, + getSigningKey: () => getSigningKey, + moveHeadersToQuery: () => moveHeadersToQuery, + prepareRequest: () => prepareRequest }); module.exports = __toCommonJS(src_exports); -// src/EventStreamCodec.ts -var import_crc322 = __nccwpck_require__(48408); +// src/SignatureV4.ts -// src/HeaderMarshaller.ts +var import_util_middleware = __nccwpck_require__(2390); +var import_util_utf84 = __nccwpck_require__(41895); -// src/Int64.ts +// src/constants.ts +var ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm"; +var CREDENTIAL_QUERY_PARAM = "X-Amz-Credential"; +var AMZ_DATE_QUERY_PARAM = "X-Amz-Date"; +var SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders"; +var EXPIRES_QUERY_PARAM = "X-Amz-Expires"; +var SIGNATURE_QUERY_PARAM = "X-Amz-Signature"; +var TOKEN_QUERY_PARAM = "X-Amz-Security-Token"; +var AUTH_HEADER = "authorization"; +var AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase(); +var DATE_HEADER = "date"; +var GENERATED_HEADERS = [AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER]; +var SIGNATURE_HEADER = SIGNATURE_QUERY_PARAM.toLowerCase(); +var SHA256_HEADER = "x-amz-content-sha256"; +var TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase(); +var ALWAYS_UNSIGNABLE_HEADERS = { + authorization: true, + "cache-control": true, + connection: true, + expect: true, + from: true, + "keep-alive": true, + "max-forwards": true, + pragma: true, + referer: true, + te: true, + trailer: true, + "transfer-encoding": true, + upgrade: true, + "user-agent": true, + "x-amzn-trace-id": true +}; +var PROXY_HEADER_PATTERN = /^proxy-/; +var SEC_HEADER_PATTERN = /^sec-/; +var ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256"; +var EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD"; +var UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD"; +var MAX_CACHE_SIZE = 50; +var KEY_TYPE_IDENTIFIER = "aws4_request"; +var MAX_PRESIGNED_TTL = 60 * 60 * 24 * 7; + +// src/credentialDerivation.ts var import_util_hex_encoding = __nccwpck_require__(45364); -var Int64 = class _Int64 { - constructor(bytes) { - this.bytes = bytes; - if (bytes.byteLength !== 8) { - throw new Error("Int64 buffers must be exactly 8 bytes"); - } +var import_util_utf8 = __nccwpck_require__(41895); +var signingKeyCache = {}; +var cacheQueue = []; +var createScope = /* @__PURE__ */ __name((shortDate, region, service) => `${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`, "createScope"); +var getSigningKey = /* @__PURE__ */ __name(async (sha256Constructor, credentials, shortDate, region, service) => { + const credsHash = await hmac(sha256Constructor, credentials.secretAccessKey, credentials.accessKeyId); + const cacheKey = `${shortDate}:${region}:${service}:${(0, import_util_hex_encoding.toHex)(credsHash)}:${credentials.sessionToken}`; + if (cacheKey in signingKeyCache) { + return signingKeyCache[cacheKey]; } - static { - __name(this, "Int64"); + cacheQueue.push(cacheKey); + while (cacheQueue.length > MAX_CACHE_SIZE) { + delete signingKeyCache[cacheQueue.shift()]; } - static fromNumber(number) { - if (number > 9223372036854776e3 || number < -9223372036854776e3) { - throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`); - } - const bytes = new Uint8Array(8); - for (let i = 7, remaining = Math.abs(Math.round(number)); i > -1 && remaining > 0; i--, remaining /= 256) { - bytes[i] = remaining; + let key = `AWS4${credentials.secretAccessKey}`; + for (const signable of [shortDate, region, service, KEY_TYPE_IDENTIFIER]) { + key = await hmac(sha256Constructor, key, signable); + } + return signingKeyCache[cacheKey] = key; +}, "getSigningKey"); +var clearCredentialCache = /* @__PURE__ */ __name(() => { + cacheQueue.length = 0; + Object.keys(signingKeyCache).forEach((cacheKey) => { + delete signingKeyCache[cacheKey]; + }); +}, "clearCredentialCache"); +var hmac = /* @__PURE__ */ __name((ctor, secret, data) => { + const hash = new ctor(secret); + hash.update((0, import_util_utf8.toUint8Array)(data)); + return hash.digest(); +}, "hmac"); + +// src/getCanonicalHeaders.ts +var getCanonicalHeaders = /* @__PURE__ */ __name(({ headers }, unsignableHeaders, signableHeaders) => { + const canonical = {}; + for (const headerName of Object.keys(headers).sort()) { + if (headers[headerName] == void 0) { + continue; } - if (number < 0) { - negate(bytes); + const canonicalHeaderName = headerName.toLowerCase(); + if (canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS || unsignableHeaders?.has(canonicalHeaderName) || PROXY_HEADER_PATTERN.test(canonicalHeaderName) || SEC_HEADER_PATTERN.test(canonicalHeaderName)) { + if (!signableHeaders || signableHeaders && !signableHeaders.has(canonicalHeaderName)) { + continue; + } } - return new _Int64(bytes); + canonical[canonicalHeaderName] = headers[headerName].trim().replace(/\s+/g, " "); } - /** - * Called implicitly by infix arithmetic operators. - */ - valueOf() { - const bytes = this.bytes.slice(0); - const negative = bytes[0] & 128; - if (negative) { - negate(bytes); + return canonical; +}, "getCanonicalHeaders"); + +// src/getCanonicalQuery.ts +var import_util_uri_escape = __nccwpck_require__(54197); +var getCanonicalQuery = /* @__PURE__ */ __name(({ query = {} }) => { + const keys = []; + const serialized = {}; + for (const key of Object.keys(query)) { + if (key.toLowerCase() === SIGNATURE_HEADER) { + continue; + } + const encodedKey = (0, import_util_uri_escape.escapeUri)(key); + keys.push(encodedKey); + const value = query[key]; + if (typeof value === "string") { + serialized[encodedKey] = `${encodedKey}=${(0, import_util_uri_escape.escapeUri)(value)}`; + } else if (Array.isArray(value)) { + serialized[encodedKey] = value.slice(0).reduce((encoded, value2) => encoded.concat([`${encodedKey}=${(0, import_util_uri_escape.escapeUri)(value2)}`]), []).sort().join("&"); } - return parseInt((0, import_util_hex_encoding.toHex)(bytes), 16) * (negative ? -1 : 1); - } - toString() { - return String(this.valueOf()); } -}; -function negate(bytes) { - for (let i = 0; i < 8; i++) { - bytes[i] ^= 255; + return keys.sort().map((key) => serialized[key]).filter((serialized2) => serialized2).join("&"); +}, "getCanonicalQuery"); + +// src/getPayloadHash.ts +var import_is_array_buffer = __nccwpck_require__(10780); + +var import_util_utf82 = __nccwpck_require__(41895); +var getPayloadHash = /* @__PURE__ */ __name(async ({ headers, body }, hashConstructor) => { + for (const headerName of Object.keys(headers)) { + if (headerName.toLowerCase() === SHA256_HEADER) { + return headers[headerName]; + } } - for (let i = 7; i > -1; i--) { - bytes[i]++; - if (bytes[i] !== 0) - break; + if (body == void 0) { + return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + } else if (typeof body === "string" || ArrayBuffer.isView(body) || (0, import_is_array_buffer.isArrayBuffer)(body)) { + const hashCtor = new hashConstructor(); + hashCtor.update((0, import_util_utf82.toUint8Array)(body)); + return (0, import_util_hex_encoding.toHex)(await hashCtor.digest()); } -} -__name(negate, "negate"); + return UNSIGNED_PAYLOAD; +}, "getPayloadHash"); -// src/HeaderMarshaller.ts -var HeaderMarshaller = class { - constructor(toUtf8, fromUtf8) { - this.toUtf8 = toUtf8; - this.fromUtf8 = fromUtf8; - } +// src/HeaderFormatter.ts + +var import_util_utf83 = __nccwpck_require__(41895); +var HeaderFormatter = class { static { - __name(this, "HeaderMarshaller"); + __name(this, "HeaderFormatter"); } format(headers) { const chunks = []; for (const headerName of Object.keys(headers)) { - const bytes = this.fromUtf8(headerName); + const bytes = (0, import_util_utf83.fromUtf8)(headerName); chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName])); } const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0)); @@ -240490,7 +237591,7 @@ var HeaderMarshaller = class { binBytes.set(header.value, 3); return binBytes; case "string": - const utf8Bytes = this.fromUtf8(header.value); + const utf8Bytes = (0, import_util_utf83.fromUtf8)(header.value); const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); strView.setUint8(0, 7 /* string */); strView.setUint16(1, utf8Bytes.byteLength, false); @@ -240512,305 +237613,324 @@ var HeaderMarshaller = class { return uuidBytes; } } - parse(headers) { - const out = {}; - let position = 0; - while (position < headers.byteLength) { - const nameLength = headers.getUint8(position++); - const name = this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, nameLength)); - position += nameLength; - switch (headers.getUint8(position++)) { - case 0 /* boolTrue */: - out[name] = { - type: BOOLEAN_TAG, - value: true - }; - break; - case 1 /* boolFalse */: - out[name] = { - type: BOOLEAN_TAG, - value: false - }; - break; - case 2 /* byte */: - out[name] = { - type: BYTE_TAG, - value: headers.getInt8(position++) - }; - break; - case 3 /* short */: - out[name] = { - type: SHORT_TAG, - value: headers.getInt16(position, false) - }; - position += 2; - break; - case 4 /* integer */: - out[name] = { - type: INT_TAG, - value: headers.getInt32(position, false) - }; - position += 4; - break; - case 5 /* long */: - out[name] = { - type: LONG_TAG, - value: new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)) - }; - position += 8; - break; - case 6 /* byteArray */: - const binaryLength = headers.getUint16(position, false); - position += 2; - out[name] = { - type: BINARY_TAG, - value: new Uint8Array(headers.buffer, headers.byteOffset + position, binaryLength) - }; - position += binaryLength; - break; - case 7 /* string */: - const stringLength = headers.getUint16(position, false); - position += 2; - out[name] = { - type: STRING_TAG, - value: this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, stringLength)) - }; - position += stringLength; - break; - case 8 /* timestamp */: - out[name] = { - type: TIMESTAMP_TAG, - value: new Date(new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)).valueOf()) - }; - position += 8; - break; - case 9 /* uuid */: - const uuidBytes = new Uint8Array(headers.buffer, headers.byteOffset + position, 16); - position += 16; - out[name] = { - type: UUID_TAG, - value: `${(0, import_util_hex_encoding.toHex)(uuidBytes.subarray(0, 4))}-${(0, import_util_hex_encoding.toHex)(uuidBytes.subarray(4, 6))}-${(0, import_util_hex_encoding.toHex)( - uuidBytes.subarray(6, 8) - )}-${(0, import_util_hex_encoding.toHex)(uuidBytes.subarray(8, 10))}-${(0, import_util_hex_encoding.toHex)(uuidBytes.subarray(10))}` - }; - break; - default: - throw new Error(`Unrecognized header type tag`); - } - } - return out; - } }; -var BOOLEAN_TAG = "boolean"; -var BYTE_TAG = "byte"; -var SHORT_TAG = "short"; -var INT_TAG = "integer"; -var LONG_TAG = "long"; -var BINARY_TAG = "binary"; -var STRING_TAG = "string"; -var TIMESTAMP_TAG = "timestamp"; -var UUID_TAG = "uuid"; var UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; - -// src/splitMessage.ts -var import_crc32 = __nccwpck_require__(48408); -var PRELUDE_MEMBER_LENGTH = 4; -var PRELUDE_LENGTH = PRELUDE_MEMBER_LENGTH * 2; -var CHECKSUM_LENGTH = 4; -var MINIMUM_MESSAGE_LENGTH = PRELUDE_LENGTH + CHECKSUM_LENGTH * 2; -function splitMessage({ byteLength, byteOffset, buffer }) { - if (byteLength < MINIMUM_MESSAGE_LENGTH) { - throw new Error("Provided message too short to accommodate event stream message overhead"); - } - const view = new DataView(buffer, byteOffset, byteLength); - const messageLength = view.getUint32(0, false); - if (byteLength !== messageLength) { - throw new Error("Reported message length does not match received message length"); +var Int64 = class _Int64 { + constructor(bytes) { + this.bytes = bytes; + if (bytes.byteLength !== 8) { + throw new Error("Int64 buffers must be exactly 8 bytes"); + } } - const headerLength = view.getUint32(PRELUDE_MEMBER_LENGTH, false); - const expectedPreludeChecksum = view.getUint32(PRELUDE_LENGTH, false); - const expectedMessageChecksum = view.getUint32(byteLength - CHECKSUM_LENGTH, false); - const checksummer = new import_crc32.Crc32().update(new Uint8Array(buffer, byteOffset, PRELUDE_LENGTH)); - if (expectedPreludeChecksum !== checksummer.digest()) { - throw new Error( - `The prelude checksum specified in the message (${expectedPreludeChecksum}) does not match the calculated CRC32 checksum (${checksummer.digest()})` - ); + static { + __name(this, "Int64"); } - checksummer.update( - new Uint8Array(buffer, byteOffset + PRELUDE_LENGTH, byteLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH)) - ); - if (expectedMessageChecksum !== checksummer.digest()) { - throw new Error( - `The message checksum (${checksummer.digest()}) did not match the expected value of ${expectedMessageChecksum}` - ); + static fromNumber(number) { + if (number > 9223372036854776e3 || number < -9223372036854776e3) { + throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`); + } + const bytes = new Uint8Array(8); + for (let i = 7, remaining = Math.abs(Math.round(number)); i > -1 && remaining > 0; i--, remaining /= 256) { + bytes[i] = remaining; + } + if (number < 0) { + negate(bytes); + } + return new _Int64(bytes); } - return { - headers: new DataView(buffer, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH, headerLength), - body: new Uint8Array( - buffer, - byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH + headerLength, - messageLength - headerLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH + CHECKSUM_LENGTH) - ) - }; -} -__name(splitMessage, "splitMessage"); - -// src/EventStreamCodec.ts -var EventStreamCodec = class { - static { - __name(this, "EventStreamCodec"); + /** + * Called implicitly by infix arithmetic operators. + */ + valueOf() { + const bytes = this.bytes.slice(0); + const negative = bytes[0] & 128; + if (negative) { + negate(bytes); + } + return parseInt((0, import_util_hex_encoding.toHex)(bytes), 16) * (negative ? -1 : 1); } - constructor(toUtf8, fromUtf8) { - this.headerMarshaller = new HeaderMarshaller(toUtf8, fromUtf8); - this.messageBuffer = []; - this.isEndOfStream = false; + toString() { + return String(this.valueOf()); } - feed(message) { - this.messageBuffer.push(this.decode(message)); +}; +function negate(bytes) { + for (let i = 0; i < 8; i++) { + bytes[i] ^= 255; } - endOfStream() { - this.isEndOfStream = true; + for (let i = 7; i > -1; i--) { + bytes[i]++; + if (bytes[i] !== 0) + break; } - getMessage() { - const message = this.messageBuffer.pop(); - const isEndOfStream = this.isEndOfStream; - return { - getMessage() { - return message; - }, - isEndOfStream() { - return isEndOfStream; - } - }; +} +__name(negate, "negate"); + +// src/headerUtil.ts +var hasHeader = /* @__PURE__ */ __name((soughtHeader, headers) => { + soughtHeader = soughtHeader.toLowerCase(); + for (const headerName of Object.keys(headers)) { + if (soughtHeader === headerName.toLowerCase()) { + return true; + } } - getAvailableMessages() { - const messages = this.messageBuffer; - this.messageBuffer = []; - const isEndOfStream = this.isEndOfStream; - return { - getMessages() { - return messages; - }, - isEndOfStream() { - return isEndOfStream; - } - }; + return false; +}, "hasHeader"); + +// src/moveHeadersToQuery.ts +var import_protocol_http = __nccwpck_require__(64418); +var moveHeadersToQuery = /* @__PURE__ */ __name((request, options = {}) => { + const { headers, query = {} } = import_protocol_http.HttpRequest.clone(request); + for (const name of Object.keys(headers)) { + const lname = name.toLowerCase(); + if (lname.slice(0, 6) === "x-amz-" && !options.unhoistableHeaders?.has(lname) || options.hoistableHeaders?.has(lname)) { + query[name] = headers[name]; + delete headers[name]; + } } - /** - * Convert a structured JavaScript object with tagged headers into a binary - * event stream message. - */ - encode({ headers: rawHeaders, body }) { - const headers = this.headerMarshaller.format(rawHeaders); - const length = headers.byteLength + body.byteLength + 16; - const out = new Uint8Array(length); - const view = new DataView(out.buffer, out.byteOffset, out.byteLength); - const checksum = new import_crc322.Crc32(); - view.setUint32(0, length, false); - view.setUint32(4, headers.byteLength, false); - view.setUint32(8, checksum.update(out.subarray(0, 8)).digest(), false); - out.set(headers, 12); - out.set(body, headers.byteLength + 12); - view.setUint32(length - 4, checksum.update(out.subarray(8, length - 4)).digest(), false); - return out; + return { + ...request, + headers, + query + }; +}, "moveHeadersToQuery"); + +// src/prepareRequest.ts + +var prepareRequest = /* @__PURE__ */ __name((request) => { + request = import_protocol_http.HttpRequest.clone(request); + for (const headerName of Object.keys(request.headers)) { + if (GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) { + delete request.headers[headerName]; + } } - /** - * Convert a binary event stream message into a JavaScript object with an - * opaque, binary body and tagged, parsed headers. - */ - decode(message) { - const { headers, body } = splitMessage(message); - return { headers: this.headerMarshaller.parse(headers), body }; + return request; +}, "prepareRequest"); + +// src/utilDate.ts +var iso8601 = /* @__PURE__ */ __name((time) => toDate(time).toISOString().replace(/\.\d{3}Z$/, "Z"), "iso8601"); +var toDate = /* @__PURE__ */ __name((time) => { + if (typeof time === "number") { + return new Date(time * 1e3); } - /** - * Convert a structured JavaScript object with tagged headers into a binary - * event stream message header. - */ - formatHeaders(rawHeaders) { - return this.headerMarshaller.format(rawHeaders); + if (typeof time === "string") { + if (Number(time)) { + return new Date(Number(time) * 1e3); + } + return new Date(time); } -}; + return time; +}, "toDate"); -// src/MessageDecoderStream.ts -var MessageDecoderStream = class { - constructor(options) { - this.options = options; +// src/SignatureV4.ts +var SignatureV4 = class { + constructor({ + applyChecksum, + credentials, + region, + service, + sha256, + uriEscapePath = true + }) { + this.headerFormatter = new HeaderFormatter(); + this.service = service; + this.sha256 = sha256; + this.uriEscapePath = uriEscapePath; + this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true; + this.regionProvider = (0, import_util_middleware.normalizeProvider)(region); + this.credentialProvider = (0, import_util_middleware.normalizeProvider)(credentials); } static { - __name(this, "MessageDecoderStream"); - } - [Symbol.asyncIterator]() { - return this.asyncIterator(); + __name(this, "SignatureV4"); } - async *asyncIterator() { - for await (const bytes of this.options.inputStream) { - const decoded = this.options.decoder.decode(bytes); - yield decoded; + async presign(originalRequest, options = {}) { + const { + signingDate = /* @__PURE__ */ new Date(), + expiresIn = 3600, + unsignableHeaders, + unhoistableHeaders, + signableHeaders, + hoistableHeaders, + signingRegion, + signingService + } = options; + const credentials = await this.credentialProvider(); + this.validateResolvedCredentials(credentials); + const region = signingRegion ?? await this.regionProvider(); + const { longDate, shortDate } = formatDate(signingDate); + if (expiresIn > MAX_PRESIGNED_TTL) { + return Promise.reject( + "Signature version 4 presigned URLs must have an expiration date less than one week in the future" + ); + } + const scope = createScope(shortDate, region, signingService ?? this.service); + const request = moveHeadersToQuery(prepareRequest(originalRequest), { unhoistableHeaders, hoistableHeaders }); + if (credentials.sessionToken) { + request.query[TOKEN_QUERY_PARAM] = credentials.sessionToken; } + request.query[ALGORITHM_QUERY_PARAM] = ALGORITHM_IDENTIFIER; + request.query[CREDENTIAL_QUERY_PARAM] = `${credentials.accessKeyId}/${scope}`; + request.query[AMZ_DATE_QUERY_PARAM] = longDate; + request.query[EXPIRES_QUERY_PARAM] = expiresIn.toString(10); + const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); + request.query[SIGNED_HEADERS_QUERY_PARAM] = getCanonicalHeaderList(canonicalHeaders); + request.query[SIGNATURE_QUERY_PARAM] = await this.getSignature( + longDate, + scope, + this.getSigningKey(credentials, region, shortDate, signingService), + this.createCanonicalRequest(request, canonicalHeaders, await getPayloadHash(originalRequest, this.sha256)) + ); + return request; } -}; - -// src/MessageEncoderStream.ts -var MessageEncoderStream = class { - constructor(options) { - this.options = options; + async sign(toSign, options) { + if (typeof toSign === "string") { + return this.signString(toSign, options); + } else if (toSign.headers && toSign.payload) { + return this.signEvent(toSign, options); + } else if (toSign.message) { + return this.signMessage(toSign, options); + } else { + return this.signRequest(toSign, options); + } } - static { - __name(this, "MessageEncoderStream"); + async signEvent({ headers, payload }, { signingDate = /* @__PURE__ */ new Date(), priorSignature, signingRegion, signingService }) { + const region = signingRegion ?? await this.regionProvider(); + const { shortDate, longDate } = formatDate(signingDate); + const scope = createScope(shortDate, region, signingService ?? this.service); + const hashedPayload = await getPayloadHash({ headers: {}, body: payload }, this.sha256); + const hash = new this.sha256(); + hash.update(headers); + const hashedHeaders = (0, import_util_hex_encoding.toHex)(await hash.digest()); + const stringToSign = [ + EVENT_ALGORITHM_IDENTIFIER, + longDate, + scope, + priorSignature, + hashedHeaders, + hashedPayload + ].join("\n"); + return this.signString(stringToSign, { signingDate, signingRegion: region, signingService }); } - [Symbol.asyncIterator]() { - return this.asyncIterator(); + async signMessage(signableMessage, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService }) { + const promise = this.signEvent( + { + headers: this.headerFormatter.format(signableMessage.message.headers), + payload: signableMessage.message.body + }, + { + signingDate, + signingRegion, + signingService, + priorSignature: signableMessage.priorSignature + } + ); + return promise.then((signature) => { + return { message: signableMessage.message, signature }; + }); } - async *asyncIterator() { - for await (const msg of this.options.messageStream) { - const encoded = this.options.encoder.encode(msg); - yield encoded; + async signString(stringToSign, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService } = {}) { + const credentials = await this.credentialProvider(); + this.validateResolvedCredentials(credentials); + const region = signingRegion ?? await this.regionProvider(); + const { shortDate } = formatDate(signingDate); + const hash = new this.sha256(await this.getSigningKey(credentials, region, shortDate, signingService)); + hash.update((0, import_util_utf84.toUint8Array)(stringToSign)); + return (0, import_util_hex_encoding.toHex)(await hash.digest()); + } + async signRequest(requestToSign, { + signingDate = /* @__PURE__ */ new Date(), + signableHeaders, + unsignableHeaders, + signingRegion, + signingService + } = {}) { + const credentials = await this.credentialProvider(); + this.validateResolvedCredentials(credentials); + const region = signingRegion ?? await this.regionProvider(); + const request = prepareRequest(requestToSign); + const { longDate, shortDate } = formatDate(signingDate); + const scope = createScope(shortDate, region, signingService ?? this.service); + request.headers[AMZ_DATE_HEADER] = longDate; + if (credentials.sessionToken) { + request.headers[TOKEN_HEADER] = credentials.sessionToken; } - if (this.options.includeEndFrame) { - yield new Uint8Array(0); + const payloadHash = await getPayloadHash(request, this.sha256); + if (!hasHeader(SHA256_HEADER, request.headers) && this.applyChecksum) { + request.headers[SHA256_HEADER] = payloadHash; } + const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); + const signature = await this.getSignature( + longDate, + scope, + this.getSigningKey(credentials, region, shortDate, signingService), + this.createCanonicalRequest(request, canonicalHeaders, payloadHash) + ); + request.headers[AUTH_HEADER] = `${ALGORITHM_IDENTIFIER} Credential=${credentials.accessKeyId}/${scope}, SignedHeaders=${getCanonicalHeaderList(canonicalHeaders)}, Signature=${signature}`; + return request; } -}; + createCanonicalRequest(request, canonicalHeaders, payloadHash) { + const sortedHeaders = Object.keys(canonicalHeaders).sort(); + return `${request.method} +${this.getCanonicalPath(request)} +${getCanonicalQuery(request)} +${sortedHeaders.map((name) => `${name}:${canonicalHeaders[name]}`).join("\n")} -// src/SmithyMessageDecoderStream.ts -var SmithyMessageDecoderStream = class { - constructor(options) { - this.options = options; - } - static { - __name(this, "SmithyMessageDecoderStream"); +${sortedHeaders.join(";")} +${payloadHash}`; } - [Symbol.asyncIterator]() { - return this.asyncIterator(); + async createStringToSign(longDate, credentialScope, canonicalRequest) { + const hash = new this.sha256(); + hash.update((0, import_util_utf84.toUint8Array)(canonicalRequest)); + const hashedRequest = await hash.digest(); + return `${ALGORITHM_IDENTIFIER} +${longDate} +${credentialScope} +${(0, import_util_hex_encoding.toHex)(hashedRequest)}`; } - async *asyncIterator() { - for await (const message of this.options.messageStream) { - const deserialized = await this.options.deserializer(message); - if (deserialized === void 0) - continue; - yield deserialized; + getCanonicalPath({ path }) { + if (this.uriEscapePath) { + const normalizedPathSegments = []; + for (const pathSegment of path.split("/")) { + if (pathSegment?.length === 0) + continue; + if (pathSegment === ".") + continue; + if (pathSegment === "..") { + normalizedPathSegments.pop(); + } else { + normalizedPathSegments.push(pathSegment); + } + } + const normalizedPath = `${path?.startsWith("/") ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && path?.endsWith("/") ? "/" : ""}`; + const doubleEncoded = (0, import_util_uri_escape.escapeUri)(normalizedPath); + return doubleEncoded.replace(/%2F/g, "/"); } + return path; } -}; - -// src/SmithyMessageEncoderStream.ts -var SmithyMessageEncoderStream = class { - constructor(options) { - this.options = options; - } - static { - __name(this, "SmithyMessageEncoderStream"); + async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) { + const stringToSign = await this.createStringToSign(longDate, credentialScope, canonicalRequest); + const hash = new this.sha256(await keyPromise); + hash.update((0, import_util_utf84.toUint8Array)(stringToSign)); + return (0, import_util_hex_encoding.toHex)(await hash.digest()); } - [Symbol.asyncIterator]() { - return this.asyncIterator(); + getSigningKey(credentials, region, shortDate, service) { + return getSigningKey(this.sha256, credentials, shortDate, region, service || this.service); } - async *asyncIterator() { - for await (const chunk of this.options.inputStream) { - const payloadBuf = this.options.serializer(chunk); - yield payloadBuf; + validateResolvedCredentials(credentials) { + if (typeof credentials !== "object" || // @ts-expect-error: Property 'accessKeyId' does not exist on type 'object'.ts(2339) + typeof credentials.accessKeyId !== "string" || // @ts-expect-error: Property 'secretAccessKey' does not exist on type 'object'.ts(2339) + typeof credentials.secretAccessKey !== "string") { + throw new Error("Resolved credential object is not valid"); } } }; +var formatDate = /* @__PURE__ */ __name((now) => { + const longDate = iso8601(now).replace(/[\-:]/g, ""); + return { + longDate, + shortDate: longDate.slice(0, 8) + }; +}, "formatDate"); +var getCanonicalHeaderList = /* @__PURE__ */ __name((headers) => Object.keys(headers).sort().join(";"), "getCanonicalHeaderList"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -240819,8 +237939,8 @@ var SmithyMessageEncoderStream = class { /***/ }), -/***/ 16181: -/***/ ((module) => { +/***/ 63570: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; @@ -240844,1185 +237964,1239 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var src_exports = {}; __export(src_exports, { - resolveEventStreamSerdeConfig: () => resolveEventStreamSerdeConfig + Client: () => Client, + Command: () => Command, + LazyJsonString: () => LazyJsonString, + NoOpLogger: () => NoOpLogger, + SENSITIVE_STRING: () => SENSITIVE_STRING, + ServiceException: () => ServiceException, + _json: () => _json, + collectBody: () => import_protocols.collectBody, + convertMap: () => convertMap, + createAggregatedClient: () => createAggregatedClient, + dateToUtcString: () => dateToUtcString, + decorateServiceException: () => decorateServiceException, + emitWarningIfUnsupportedVersion: () => emitWarningIfUnsupportedVersion, + expectBoolean: () => expectBoolean, + expectByte: () => expectByte, + expectFloat32: () => expectFloat32, + expectInt: () => expectInt, + expectInt32: () => expectInt32, + expectLong: () => expectLong, + expectNonNull: () => expectNonNull, + expectNumber: () => expectNumber, + expectObject: () => expectObject, + expectShort: () => expectShort, + expectString: () => expectString, + expectUnion: () => expectUnion, + extendedEncodeURIComponent: () => import_protocols.extendedEncodeURIComponent, + getArrayIfSingleItem: () => getArrayIfSingleItem, + getDefaultClientConfiguration: () => getDefaultClientConfiguration, + getDefaultExtensionConfiguration: () => getDefaultExtensionConfiguration, + getValueFromTextNode: () => getValueFromTextNode, + handleFloat: () => handleFloat, + isSerializableHeaderValue: () => isSerializableHeaderValue, + limitedParseDouble: () => limitedParseDouble, + limitedParseFloat: () => limitedParseFloat, + limitedParseFloat32: () => limitedParseFloat32, + loadConfigsForDefaultMode: () => loadConfigsForDefaultMode, + logger: () => logger, + map: () => map, + parseBoolean: () => parseBoolean, + parseEpochTimestamp: () => parseEpochTimestamp, + parseRfc3339DateTime: () => parseRfc3339DateTime, + parseRfc3339DateTimeWithOffset: () => parseRfc3339DateTimeWithOffset, + parseRfc7231DateTime: () => parseRfc7231DateTime, + quoteHeader: () => quoteHeader, + resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig, + resolvedPath: () => import_protocols.resolvedPath, + serializeDateTime: () => serializeDateTime, + serializeFloat: () => serializeFloat, + splitEvery: () => splitEvery, + splitHeader: () => splitHeader, + strictParseByte: () => strictParseByte, + strictParseDouble: () => strictParseDouble, + strictParseFloat: () => strictParseFloat, + strictParseFloat32: () => strictParseFloat32, + strictParseInt: () => strictParseInt, + strictParseInt32: () => strictParseInt32, + strictParseLong: () => strictParseLong, + strictParseShort: () => strictParseShort, + take: () => take, + throwDefaultError: () => throwDefaultError, + withBaseException: () => withBaseException }); module.exports = __toCommonJS(src_exports); -// src/EventStreamSerdeConfig.ts -var resolveEventStreamSerdeConfig = /* @__PURE__ */ __name((input) => Object.assign(input, { - eventStreamMarshaller: input.eventStreamSerdeProvider(input) -}), "resolveEventStreamSerdeConfig"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 77682: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -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 }); +// src/client.ts +var import_middleware_stack = __nccwpck_require__(97911); +var Client = class { + constructor(config) { + this.config = config; + this.middlewareStack = (0, import_middleware_stack.constructStack)(); + } + static { + __name(this, "Client"); + } + send(command, optionsOrCb, cb) { + const options = typeof optionsOrCb !== "function" ? optionsOrCb : void 0; + const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb; + const useHandlerCache = options === void 0 && this.config.cacheMiddleware === true; + let handler; + if (useHandlerCache) { + if (!this.handlers) { + this.handlers = /* @__PURE__ */ new WeakMap(); + } + const handlers = this.handlers; + if (handlers.has(command.constructor)) { + handler = handlers.get(command.constructor); + } else { + handler = command.resolveMiddleware(this.middlewareStack, this.config, options); + handlers.set(command.constructor, handler); + } + } else { + delete this.handlers; + handler = command.resolveMiddleware(this.middlewareStack, this.config, options); + } + if (callback) { + handler(command).then( + (result) => callback(null, result.output), + (err) => callback(err) + ).catch( + // prevent any errors thrown in the callback from triggering an + // unhandled promise rejection + () => { + } + ); + } else { + return handler(command).then((result) => result.output); + } + } + destroy() { + this.config?.requestHandler?.destroy?.(); + delete this.handlers; } - return to; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts -var src_exports = {}; -__export(src_exports, { - EventStreamMarshaller: () => EventStreamMarshaller, - eventStreamSerdeProvider: () => eventStreamSerdeProvider -}); -module.exports = __toCommonJS(src_exports); +// src/collect-stream-body.ts +var import_protocols = __nccwpck_require__(2241); -// src/EventStreamMarshaller.ts -var import_eventstream_serde_universal = __nccwpck_require__(66673); -var import_stream = __nccwpck_require__(12781); +// src/command.ts -// src/utils.ts -async function* readabletoIterable(readStream) { - let streamEnded = false; - let generationEnded = false; - const records = new Array(); - readStream.on("error", (err) => { - if (!streamEnded) { - streamEnded = true; - } - if (err) { - throw err; - } - }); - readStream.on("data", (data) => { - records.push(data); - }); - readStream.on("end", () => { - streamEnded = true; - }); - while (!generationEnded) { - const value = await new Promise((resolve) => setTimeout(() => resolve(records.shift()), 0)); - if (value) { - yield value; +var import_types = __nccwpck_require__(55756); +var Command = class { + constructor() { + this.middlewareStack = (0, import_middleware_stack.constructStack)(); + } + static { + __name(this, "Command"); + } + /** + * Factory for Command ClassBuilder. + * @internal + */ + static classBuilder() { + return new ClassBuilder(); + } + /** + * @internal + */ + resolveMiddlewareWithContext(clientStack, configuration, options, { + middlewareFn, + clientName, + commandName, + inputFilterSensitiveLog, + outputFilterSensitiveLog, + smithyContext, + additionalContext, + CommandCtor + }) { + for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) { + this.middlewareStack.use(mw); } - generationEnded = streamEnded && records.length === 0; + const stack = clientStack.concat(this.middlewareStack); + const { logger: logger2 } = configuration; + const handlerExecutionContext = { + logger: logger2, + clientName, + commandName, + inputFilterSensitiveLog, + outputFilterSensitiveLog, + [import_types.SMITHY_CONTEXT_KEY]: { + commandInstance: this, + ...smithyContext + }, + ...additionalContext + }; + const { requestHandler } = configuration; + return stack.resolve( + (request) => requestHandler.handle(request.request, options || {}), + handlerExecutionContext + ); + } +}; +var ClassBuilder = class { + constructor() { + this._init = () => { + }; + this._ep = {}; + this._middlewareFn = () => []; + this._commandName = ""; + this._clientName = ""; + this._additionalContext = {}; + this._smithyContext = {}; + this._inputFilterSensitiveLog = (_) => _; + this._outputFilterSensitiveLog = (_) => _; + this._serializer = null; + this._deserializer = null; } -} -__name(readabletoIterable, "readabletoIterable"); - -// src/EventStreamMarshaller.ts -var EventStreamMarshaller = class { static { - __name(this, "EventStreamMarshaller"); + __name(this, "ClassBuilder"); } - constructor({ utf8Encoder, utf8Decoder }) { - this.universalMarshaller = new import_eventstream_serde_universal.EventStreamMarshaller({ - utf8Decoder, - utf8Encoder - }); + /** + * Optional init callback. + */ + init(cb) { + this._init = cb; } - deserialize(body, deserializer) { - const bodyIterable = typeof body[Symbol.asyncIterator] === "function" ? body : readabletoIterable(body); - return this.universalMarshaller.deserialize(bodyIterable, deserializer); + /** + * Set the endpoint parameter instructions. + */ + ep(endpointParameterInstructions) { + this._ep = endpointParameterInstructions; + return this; } - serialize(input, serializer) { - return import_stream.Readable.from(this.universalMarshaller.serialize(input, serializer)); + /** + * Add any number of middleware. + */ + m(middlewareSupplier) { + this._middlewareFn = middlewareSupplier; + return this; } -}; - -// src/provider.ts -var eventStreamSerdeProvider = /* @__PURE__ */ __name((options) => new EventStreamMarshaller(options), "eventStreamSerdeProvider"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 66673: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -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 }); + /** + * Set the initial handler execution context Smithy field. + */ + s(service, operation, smithyContext = {}) { + this._smithyContext = { + service, + operation, + ...smithyContext + }; + return this; + } + /** + * Set the initial handler execution context. + */ + c(additionalContext = {}) { + this._additionalContext = additionalContext; + return this; + } + /** + * Set constant string identifiers for the operation. + */ + n(clientName, commandName) { + this._clientName = clientName; + this._commandName = commandName; + return this; + } + /** + * Set the input and output sensistive log filters. + */ + f(inputFilter = (_) => _, outputFilter = (_) => _) { + this._inputFilterSensitiveLog = inputFilter; + this._outputFilterSensitiveLog = outputFilter; + return this; + } + /** + * Sets the serializer. + */ + ser(serializer) { + this._serializer = serializer; + return this; + } + /** + * Sets the deserializer. + */ + de(deserializer) { + this._deserializer = deserializer; + return this; + } + /** + * @returns a Command class with the classBuilder properties. + */ + build() { + const closure = this; + let CommandRef; + return CommandRef = class extends Command { + /** + * @public + */ + constructor(...[input]) { + super(); + /** + * @internal + */ + // @ts-ignore used in middlewareFn closure. + this.serialize = closure._serializer; + /** + * @internal + */ + // @ts-ignore used in middlewareFn closure. + this.deserialize = closure._deserializer; + this.input = input ?? {}; + closure._init(this); + } + static { + __name(this, "CommandRef"); + } + /** + * @public + */ + static getEndpointParameterInstructions() { + return closure._ep; + } + /** + * @internal + */ + resolveMiddleware(stack, configuration, options) { + return this.resolveMiddlewareWithContext(stack, configuration, options, { + CommandCtor: CommandRef, + middlewareFn: closure._middlewareFn, + clientName: closure._clientName, + commandName: closure._commandName, + inputFilterSensitiveLog: closure._inputFilterSensitiveLog, + outputFilterSensitiveLog: closure._outputFilterSensitiveLog, + smithyContext: closure._smithyContext, + additionalContext: closure._additionalContext + }); + } + }; } - return to; }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// src/index.ts -var src_exports = {}; -__export(src_exports, { - EventStreamMarshaller: () => EventStreamMarshaller, - eventStreamSerdeProvider: () => eventStreamSerdeProvider -}); -module.exports = __toCommonJS(src_exports); +// src/constants.ts +var SENSITIVE_STRING = "***SensitiveInformation***"; -// src/EventStreamMarshaller.ts -var import_eventstream_codec = __nccwpck_require__(56459); +// src/create-aggregated-client.ts +var createAggregatedClient = /* @__PURE__ */ __name((commands, Client2) => { + for (const command of Object.keys(commands)) { + const CommandCtor = commands[command]; + const methodImpl = /* @__PURE__ */ __name(async function(args, optionsOrCb, cb) { + const command2 = new CommandCtor(args); + if (typeof optionsOrCb === "function") { + this.send(command2, optionsOrCb); + } else if (typeof cb === "function") { + if (typeof optionsOrCb !== "object") + throw new Error(`Expected http options but got ${typeof optionsOrCb}`); + this.send(command2, optionsOrCb || {}, cb); + } else { + return this.send(command2, optionsOrCb); + } + }, "methodImpl"); + const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, ""); + Client2.prototype[methodName] = methodImpl; + } +}, "createAggregatedClient"); -// src/getChunkedStream.ts -function getChunkedStream(source) { - let currentMessageTotalLength = 0; - let currentMessagePendingLength = 0; - let currentMessage = null; - let messageLengthBuffer = null; - const allocateMessage = /* @__PURE__ */ __name((size) => { - if (typeof size !== "number") { - throw new Error("Attempted to allocate an event message where size was not a number: " + size); +// src/parse-utils.ts +var parseBoolean = /* @__PURE__ */ __name((value) => { + switch (value) { + case "true": + return true; + case "false": + return false; + default: + throw new Error(`Unable to parse boolean value "${value}"`); + } +}, "parseBoolean"); +var expectBoolean = /* @__PURE__ */ __name((value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value === "number") { + if (value === 0 || value === 1) { + logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); } - currentMessageTotalLength = size; - currentMessagePendingLength = 4; - currentMessage = new Uint8Array(size); - const currentMessageView = new DataView(currentMessage.buffer); - currentMessageView.setUint32(0, size, false); - }, "allocateMessage"); - const iterator = /* @__PURE__ */ __name(async function* () { - const sourceIterator = source[Symbol.asyncIterator](); - while (true) { - const { value, done } = await sourceIterator.next(); - if (done) { - if (!currentMessageTotalLength) { - return; - } else if (currentMessageTotalLength === currentMessagePendingLength) { - yield currentMessage; - } else { - throw new Error("Truncated event message received."); - } - return; - } - const chunkLength = value.length; - let currentOffset = 0; - while (currentOffset < chunkLength) { - if (!currentMessage) { - const bytesRemaining = chunkLength - currentOffset; - if (!messageLengthBuffer) { - messageLengthBuffer = new Uint8Array(4); - } - const numBytesForTotal = Math.min( - 4 - currentMessagePendingLength, - // remaining bytes to fill the messageLengthBuffer - bytesRemaining - // bytes left in chunk - ); - messageLengthBuffer.set( - // @ts-ignore error TS2532: Object is possibly 'undefined' for value - value.slice(currentOffset, currentOffset + numBytesForTotal), - currentMessagePendingLength - ); - currentMessagePendingLength += numBytesForTotal; - currentOffset += numBytesForTotal; - if (currentMessagePendingLength < 4) { - break; - } - allocateMessage(new DataView(messageLengthBuffer.buffer).getUint32(0, false)); - messageLengthBuffer = null; - } - const numBytesToWrite = Math.min( - currentMessageTotalLength - currentMessagePendingLength, - // number of bytes left to complete message - chunkLength - currentOffset - // number of bytes left in the original chunk - ); - currentMessage.set( - // @ts-ignore error TS2532: Object is possibly 'undefined' for value - value.slice(currentOffset, currentOffset + numBytesToWrite), - currentMessagePendingLength - ); - currentMessagePendingLength += numBytesToWrite; - currentOffset += numBytesToWrite; - if (currentMessageTotalLength && currentMessageTotalLength === currentMessagePendingLength) { - yield currentMessage; - currentMessage = null; - currentMessageTotalLength = 0; - currentMessagePendingLength = 0; - } - } + if (value === 0) { + return false; } - }, "iterator"); - return { - [Symbol.asyncIterator]: iterator - }; -} -__name(getChunkedStream, "getChunkedStream"); - -// src/getUnmarshalledStream.ts -function getMessageUnmarshaller(deserializer, toUtf8) { - return async function(message) { - const { value: messageType } = message.headers[":message-type"]; - if (messageType === "error") { - const unmodeledError = new Error(message.headers[":error-message"].value || "UnknownError"); - unmodeledError.name = message.headers[":error-code"].value; - throw unmodeledError; - } else if (messageType === "exception") { - const code = message.headers[":exception-type"].value; - const exception = { [code]: message }; - const deserializedException = await deserializer(exception); - if (deserializedException.$unknown) { - const error = new Error(toUtf8(message.body)); - error.name = code; - throw error; + if (value === 1) { + return true; + } + } + if (typeof value === "string") { + const lower = value.toLowerCase(); + if (lower === "false" || lower === "true") { + logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); + } + if (lower === "false") { + return false; + } + if (lower === "true") { + return true; + } + } + if (typeof value === "boolean") { + return value; + } + throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`); +}, "expectBoolean"); +var expectNumber = /* @__PURE__ */ __name((value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value === "string") { + const parsed = parseFloat(value); + if (!Number.isNaN(parsed)) { + if (String(parsed) !== String(value)) { + logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`)); } - throw deserializedException[code]; - } else if (messageType === "event") { - const event = { - [message.headers[":event-type"].value]: message - }; - const deserialized = await deserializer(event); - if (deserialized.$unknown) - return; - return deserialized; - } else { - throw Error(`Unrecognizable event type: ${message.headers[":event-type"].value}`); + return parsed; } - }; -} -__name(getMessageUnmarshaller, "getMessageUnmarshaller"); - -// src/EventStreamMarshaller.ts -var EventStreamMarshaller = class { - static { - __name(this, "EventStreamMarshaller"); } - constructor({ utf8Encoder, utf8Decoder }) { - this.eventStreamCodec = new import_eventstream_codec.EventStreamCodec(utf8Encoder, utf8Decoder); - this.utfEncoder = utf8Encoder; + if (typeof value === "number") { + return value; } - deserialize(body, deserializer) { - const inputStream = getChunkedStream(body); - return new import_eventstream_codec.SmithyMessageDecoderStream({ - messageStream: new import_eventstream_codec.MessageDecoderStream({ inputStream, decoder: this.eventStreamCodec }), - // @ts-expect-error Type 'T' is not assignable to type 'Record' - deserializer: getMessageUnmarshaller(deserializer, this.utfEncoder) - }); + throw new TypeError(`Expected number, got ${typeof value}: ${value}`); +}, "expectNumber"); +var MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23)); +var expectFloat32 = /* @__PURE__ */ __name((value) => { + const expected = expectNumber(value); + if (expected !== void 0 && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) { + if (Math.abs(expected) > MAX_FLOAT) { + throw new TypeError(`Expected 32-bit float, got ${value}`); + } } - serialize(inputStream, serializer) { - return new import_eventstream_codec.MessageEncoderStream({ - messageStream: new import_eventstream_codec.SmithyMessageEncoderStream({ inputStream, serializer }), - encoder: this.eventStreamCodec, - includeEndFrame: true - }); + return expected; +}, "expectFloat32"); +var expectLong = /* @__PURE__ */ __name((value) => { + if (value === null || value === void 0) { + return void 0; } -}; - -// src/provider.ts -var eventStreamSerdeProvider = /* @__PURE__ */ __name((options) => new EventStreamMarshaller(options), "eventStreamSerdeProvider"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 82687: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -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 }); + if (Number.isInteger(value) && !Number.isNaN(value)) { + return value; } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - FetchHttpHandler: () => FetchHttpHandler, - keepAliveSupport: () => keepAliveSupport, - streamCollector: () => streamCollector -}); -module.exports = __toCommonJS(src_exports); - -// src/fetch-http-handler.ts -var import_protocol_http = __nccwpck_require__(64418); -var import_querystring_builder = __nccwpck_require__(68031); - -// src/create-request.ts -function createRequest(url, requestOptions) { - return new Request(url, requestOptions); -} -__name(createRequest, "createRequest"); - -// src/request-timeout.ts -function requestTimeout(timeoutInMs = 0) { - return new Promise((resolve, reject) => { - if (timeoutInMs) { - setTimeout(() => { - const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`); - timeoutError.name = "TimeoutError"; - reject(timeoutError); - }, timeoutInMs); + throw new TypeError(`Expected integer, got ${typeof value}: ${value}`); +}, "expectLong"); +var expectInt = expectLong; +var expectInt32 = /* @__PURE__ */ __name((value) => expectSizedInt(value, 32), "expectInt32"); +var expectShort = /* @__PURE__ */ __name((value) => expectSizedInt(value, 16), "expectShort"); +var expectByte = /* @__PURE__ */ __name((value) => expectSizedInt(value, 8), "expectByte"); +var expectSizedInt = /* @__PURE__ */ __name((value, size) => { + const expected = expectLong(value); + if (expected !== void 0 && castInt(expected, size) !== expected) { + throw new TypeError(`Expected ${size}-bit integer, got ${value}`); + } + return expected; +}, "expectSizedInt"); +var castInt = /* @__PURE__ */ __name((value, size) => { + switch (size) { + case 32: + return Int32Array.of(value)[0]; + case 16: + return Int16Array.of(value)[0]; + case 8: + return Int8Array.of(value)[0]; + } +}, "castInt"); +var expectNonNull = /* @__PURE__ */ __name((value, location) => { + if (value === null || value === void 0) { + if (location) { + throw new TypeError(`Expected a non-null value for ${location}`); } - }); -} -__name(requestTimeout, "requestTimeout"); - -// src/fetch-http-handler.ts -var keepAliveSupport = { - supported: void 0 + throw new TypeError("Expected a non-null value"); + } + return value; +}, "expectNonNull"); +var expectObject = /* @__PURE__ */ __name((value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value === "object" && !Array.isArray(value)) { + return value; + } + const receivedType = Array.isArray(value) ? "array" : typeof value; + throw new TypeError(`Expected object, got ${receivedType}: ${value}`); +}, "expectObject"); +var expectString = /* @__PURE__ */ __name((value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value === "string") { + return value; + } + if (["boolean", "number", "bigint"].includes(typeof value)) { + logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`)); + return String(value); + } + throw new TypeError(`Expected string, got ${typeof value}: ${value}`); +}, "expectString"); +var expectUnion = /* @__PURE__ */ __name((value) => { + if (value === null || value === void 0) { + return void 0; + } + const asObject = expectObject(value); + const setKeys = Object.entries(asObject).filter(([, v]) => v != null).map(([k]) => k); + if (setKeys.length === 0) { + throw new TypeError(`Unions must have exactly one non-null member. None were found.`); + } + if (setKeys.length > 1) { + throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`); + } + return asObject; +}, "expectUnion"); +var strictParseDouble = /* @__PURE__ */ __name((value) => { + if (typeof value == "string") { + return expectNumber(parseNumber(value)); + } + return expectNumber(value); +}, "strictParseDouble"); +var strictParseFloat = strictParseDouble; +var strictParseFloat32 = /* @__PURE__ */ __name((value) => { + if (typeof value == "string") { + return expectFloat32(parseNumber(value)); + } + return expectFloat32(value); +}, "strictParseFloat32"); +var NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g; +var parseNumber = /* @__PURE__ */ __name((value) => { + const matches = value.match(NUMBER_REGEX); + if (matches === null || matches[0].length !== value.length) { + throw new TypeError(`Expected real number, got implicit NaN`); + } + return parseFloat(value); +}, "parseNumber"); +var limitedParseDouble = /* @__PURE__ */ __name((value) => { + if (typeof value == "string") { + return parseFloatString(value); + } + return expectNumber(value); +}, "limitedParseDouble"); +var handleFloat = limitedParseDouble; +var limitedParseFloat = limitedParseDouble; +var limitedParseFloat32 = /* @__PURE__ */ __name((value) => { + if (typeof value == "string") { + return parseFloatString(value); + } + return expectFloat32(value); +}, "limitedParseFloat32"); +var parseFloatString = /* @__PURE__ */ __name((value) => { + switch (value) { + case "NaN": + return NaN; + case "Infinity": + return Infinity; + case "-Infinity": + return -Infinity; + default: + throw new Error(`Unable to parse float value: ${value}`); + } +}, "parseFloatString"); +var strictParseLong = /* @__PURE__ */ __name((value) => { + if (typeof value === "string") { + return expectLong(parseNumber(value)); + } + return expectLong(value); +}, "strictParseLong"); +var strictParseInt = strictParseLong; +var strictParseInt32 = /* @__PURE__ */ __name((value) => { + if (typeof value === "string") { + return expectInt32(parseNumber(value)); + } + return expectInt32(value); +}, "strictParseInt32"); +var strictParseShort = /* @__PURE__ */ __name((value) => { + if (typeof value === "string") { + return expectShort(parseNumber(value)); + } + return expectShort(value); +}, "strictParseShort"); +var strictParseByte = /* @__PURE__ */ __name((value) => { + if (typeof value === "string") { + return expectByte(parseNumber(value)); + } + return expectByte(value); +}, "strictParseByte"); +var stackTraceWarning = /* @__PURE__ */ __name((message) => { + return String(new TypeError(message).stack || message).split("\n").slice(0, 5).filter((s) => !s.includes("stackTraceWarning")).join("\n"); +}, "stackTraceWarning"); +var logger = { + warn: console.warn }; -var FetchHttpHandler = class _FetchHttpHandler { - static { - __name(this, "FetchHttpHandler"); + +// src/date-utils.ts +var DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; +var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; +function dateToUtcString(date) { + const year = date.getUTCFullYear(); + const month = date.getUTCMonth(); + const dayOfWeek = date.getUTCDay(); + const dayOfMonthInt = date.getUTCDate(); + const hoursInt = date.getUTCHours(); + const minutesInt = date.getUTCMinutes(); + const secondsInt = date.getUTCSeconds(); + const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`; + const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`; + const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`; + const secondsString = secondsInt < 10 ? `0${secondsInt}` : `${secondsInt}`; + return `${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year} ${hoursString}:${minutesString}:${secondsString} GMT`; +} +__name(dateToUtcString, "dateToUtcString"); +var RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/); +var parseRfc3339DateTime = /* @__PURE__ */ __name((value) => { + if (value === null || value === void 0) { + return void 0; } - /** - * @returns the input if it is an HttpHandler of any class, - * or instantiates a new instance of this handler. - */ - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; - } - return new _FetchHttpHandler(instanceOrOptions); + if (typeof value !== "string") { + throw new TypeError("RFC-3339 date-times must be expressed as strings"); } - constructor(options) { - if (typeof options === "function") { - this.configProvider = options().then((opts) => opts || {}); - } else { - this.config = options ?? {}; - this.configProvider = Promise.resolve(this.config); - } - if (keepAliveSupport.supported === void 0) { - keepAliveSupport.supported = Boolean( - typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]") - ); - } + const match = RFC3339.exec(value); + if (!match) { + throw new TypeError("Invalid RFC-3339 date-time value"); } - destroy() { + const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match; + const year = strictParseShort(stripLeadingZeroes(yearStr)); + const month = parseDateValue(monthStr, "month", 1, 12); + const day = parseDateValue(dayStr, "day", 1, 31); + return buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); +}, "parseRfc3339DateTime"); +var RFC3339_WITH_OFFSET = new RegExp( + /^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/ +); +var parseRfc3339DateTimeWithOffset = /* @__PURE__ */ __name((value) => { + if (value === null || value === void 0) { + return void 0; } - async handle(request, { abortSignal } = {}) { - if (!this.config) { - this.config = await this.configProvider; - } - const requestTimeoutInMs = this.config.requestTimeout; - const keepAlive = this.config.keepAlive === true; - const credentials = this.config.credentials; - if (abortSignal?.aborted) { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - return Promise.reject(abortError); - } - let path = request.path; - const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - let auth = ""; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}@`; - } - const { port, method } = request; - const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path}`; - const body = method === "GET" || method === "HEAD" ? void 0 : request.body; - const requestOptions = { - body, - headers: new Headers(request.headers), - method, - credentials - }; - if (this.config?.cache) { - requestOptions.cache = this.config.cache; - } - if (body) { - requestOptions.duplex = "half"; - } - if (typeof AbortController !== "undefined") { - requestOptions.signal = abortSignal; - } - if (keepAliveSupport.supported) { - requestOptions.keepalive = keepAlive; - } - if (typeof this.config.requestInit === "function") { - Object.assign(requestOptions, this.config.requestInit(request)); - } - let removeSignalEventListener = /* @__PURE__ */ __name(() => { - }, "removeSignalEventListener"); - const fetchRequest = createRequest(url, requestOptions); - const raceOfPromises = [ - fetch(fetchRequest).then((response) => { - const fetchHeaders = response.headers; - const transformedHeaders = {}; - for (const pair of fetchHeaders.entries()) { - transformedHeaders[pair[0]] = pair[1]; - } - const hasReadableStream = response.body != void 0; - if (!hasReadableStream) { - return response.blob().then((body2) => ({ - response: new import_protocol_http.HttpResponse({ - headers: transformedHeaders, - reason: response.statusText, - statusCode: response.status, - body: body2 - }) - })); - } - return { - response: new import_protocol_http.HttpResponse({ - headers: transformedHeaders, - reason: response.statusText, - statusCode: response.status, - body: response.body - }) - }; - }), - requestTimeout(requestTimeoutInMs) - ]; - if (abortSignal) { - raceOfPromises.push( - new Promise((resolve, reject) => { - const onAbort = /* @__PURE__ */ __name(() => { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - }, "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - removeSignalEventListener = /* @__PURE__ */ __name(() => signal.removeEventListener("abort", onAbort), "removeSignalEventListener"); - } else { - abortSignal.onabort = onAbort; - } - }) - ); - } - return Promise.race(raceOfPromises).finally(removeSignalEventListener); + if (typeof value !== "string") { + throw new TypeError("RFC-3339 date-times must be expressed as strings"); } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config) => { - config[key] = value; - return config; - }); + const match = RFC3339_WITH_OFFSET.exec(value); + if (!match) { + throw new TypeError("Invalid RFC-3339 date-time value"); } - httpHandlerConfigs() { - return this.config ?? {}; + const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match; + const year = strictParseShort(stripLeadingZeroes(yearStr)); + const month = parseDateValue(monthStr, "month", 1, 12); + const day = parseDateValue(dayStr, "day", 1, 31); + const date = buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); + if (offsetStr.toUpperCase() != "Z") { + date.setTime(date.getTime() - parseOffsetToMilliseconds(offsetStr)); } -}; - -// src/stream-collector.ts -var import_util_base64 = __nccwpck_require__(75600); -var streamCollector = /* @__PURE__ */ __name(async (stream) => { - if (typeof Blob === "function" && stream instanceof Blob || stream.constructor?.name === "Blob") { - if (Blob.prototype.arrayBuffer !== void 0) { - return new Uint8Array(await stream.arrayBuffer()); - } - return collectBlob(stream); + return date; +}, "parseRfc3339DateTimeWithOffset"); +var IMF_FIXDATE = new RegExp( + /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/ +); +var RFC_850_DATE = new RegExp( + /^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/ +); +var ASC_TIME = new RegExp( + /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/ +); +var parseRfc7231DateTime = /* @__PURE__ */ __name((value) => { + if (value === null || value === void 0) { + return void 0; } - return collectStream(stream); -}, "streamCollector"); -async function collectBlob(blob) { - const base64 = await readToBase64(blob); - const arrayBuffer = (0, import_util_base64.fromBase64)(base64); - return new Uint8Array(arrayBuffer); -} -__name(collectBlob, "collectBlob"); -async function collectStream(stream) { - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - let length = 0; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - length += value.length; - } - isDone = done; + if (typeof value !== "string") { + throw new TypeError("RFC-7231 date-times must be expressed as strings"); } - const collected = new Uint8Array(length); - let offset = 0; - for (const chunk of chunks) { - collected.set(chunk, offset); - offset += chunk.length; + let match = IMF_FIXDATE.exec(value); + if (match) { + const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; + return buildDate( + strictParseShort(stripLeadingZeroes(yearStr)), + parseMonthByShortName(monthStr), + parseDateValue(dayStr, "day", 1, 31), + { hours, minutes, seconds, fractionalMilliseconds } + ); } - return collected; -} -__name(collectStream, "collectStream"); -function readToBase64(blob) { - return new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onloadend = () => { - if (reader.readyState !== 2) { - return reject(new Error("Reader aborted too early")); - } - const result = reader.result ?? ""; - const commaIndex = result.indexOf(","); - const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length; - resolve(result.substring(dataOffset)); - }; - reader.onabort = () => reject(new Error("Read aborted")); - reader.onerror = () => reject(reader.error); - reader.readAsDataURL(blob); - }); -} -__name(readToBase64, "readToBase64"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 3081: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -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 }); + match = RFC_850_DATE.exec(value); + if (match) { + const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; + return adjustRfc850Year( + buildDate(parseTwoDigitYear(yearStr), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { + hours, + minutes, + seconds, + fractionalMilliseconds + }) + ); } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - Hash: () => Hash -}); -module.exports = __toCommonJS(src_exports); -var import_util_buffer_from = __nccwpck_require__(31381); -var import_util_utf8 = __nccwpck_require__(41895); -var import_buffer = __nccwpck_require__(14300); -var import_crypto = __nccwpck_require__(6113); -var Hash = class { - static { - __name(this, "Hash"); + match = ASC_TIME.exec(value); + if (match) { + const [_, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match; + return buildDate( + strictParseShort(stripLeadingZeroes(yearStr)), + parseMonthByShortName(monthStr), + parseDateValue(dayStr.trimLeft(), "day", 1, 31), + { hours, minutes, seconds, fractionalMilliseconds } + ); } - constructor(algorithmIdentifier, secret) { - this.algorithmIdentifier = algorithmIdentifier; - this.secret = secret; - this.reset(); + throw new TypeError("Invalid RFC-7231 date-time value"); +}, "parseRfc7231DateTime"); +var parseEpochTimestamp = /* @__PURE__ */ __name((value) => { + if (value === null || value === void 0) { + return void 0; } - update(toHash, encoding) { - this.hash.update((0, import_util_utf8.toUint8Array)(castSourceData(toHash, encoding))); + let valueAsDouble; + if (typeof value === "number") { + valueAsDouble = value; + } else if (typeof value === "string") { + valueAsDouble = strictParseDouble(value); + } else if (typeof value === "object" && value.tag === 1) { + valueAsDouble = value.value; + } else { + throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation"); } - digest() { - return Promise.resolve(this.hash.digest()); + if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) { + throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics"); } - reset() { - this.hash = this.secret ? (0, import_crypto.createHmac)(this.algorithmIdentifier, castSourceData(this.secret)) : (0, import_crypto.createHash)(this.algorithmIdentifier); + return new Date(Math.round(valueAsDouble * 1e3)); +}, "parseEpochTimestamp"); +var buildDate = /* @__PURE__ */ __name((year, month, day, time) => { + const adjustedMonth = month - 1; + validateDayOfMonth(year, adjustedMonth, day); + return new Date( + Date.UTC( + year, + adjustedMonth, + day, + parseDateValue(time.hours, "hour", 0, 23), + parseDateValue(time.minutes, "minute", 0, 59), + // seconds can go up to 60 for leap seconds + parseDateValue(time.seconds, "seconds", 0, 60), + parseMilliseconds(time.fractionalMilliseconds) + ) + ); +}, "buildDate"); +var parseTwoDigitYear = /* @__PURE__ */ __name((value) => { + const thisYear = (/* @__PURE__ */ new Date()).getUTCFullYear(); + const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort(stripLeadingZeroes(value)); + if (valueInThisCentury < thisYear) { + return valueInThisCentury + 100; } -}; -function castSourceData(toCast, encoding) { - if (import_buffer.Buffer.isBuffer(toCast)) { - return toCast; + return valueInThisCentury; +}, "parseTwoDigitYear"); +var FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1e3; +var adjustRfc850Year = /* @__PURE__ */ __name((input) => { + if (input.getTime() - (/* @__PURE__ */ new Date()).getTime() > FIFTY_YEARS_IN_MILLIS) { + return new Date( + Date.UTC( + input.getUTCFullYear() - 100, + input.getUTCMonth(), + input.getUTCDate(), + input.getUTCHours(), + input.getUTCMinutes(), + input.getUTCSeconds(), + input.getUTCMilliseconds() + ) + ); } - if (typeof toCast === "string") { - return (0, import_util_buffer_from.fromString)(toCast, encoding); + return input; +}, "adjustRfc850Year"); +var parseMonthByShortName = /* @__PURE__ */ __name((value) => { + const monthIdx = MONTHS.indexOf(value); + if (monthIdx < 0) { + throw new TypeError(`Invalid month: ${value}`); } - if (ArrayBuffer.isView(toCast)) { - return (0, import_util_buffer_from.fromArrayBuffer)(toCast.buffer, toCast.byteOffset, toCast.byteLength); + return monthIdx + 1; +}, "parseMonthByShortName"); +var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +var validateDayOfMonth = /* @__PURE__ */ __name((year, month, day) => { + let maxDays = DAYS_IN_MONTH[month]; + if (month === 1 && isLeapYear(year)) { + maxDays = 29; } - return (0, import_util_buffer_from.fromArrayBuffer)(toCast); -} -__name(castSourceData, "castSourceData"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 48866: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -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 }); + if (day > maxDays) { + throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`); } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - fileStreamHasher: () => fileStreamHasher, - readableStreamHasher: () => readableStreamHasher -}); -module.exports = __toCommonJS(src_exports); - -// src/fileStreamHasher.ts -var import_fs = __nccwpck_require__(57147); - -// src/HashCalculator.ts -var import_util_utf8 = __nccwpck_require__(41895); -var import_stream = __nccwpck_require__(12781); -var HashCalculator = class extends import_stream.Writable { - constructor(hash, options) { - super(options); - this.hash = hash; +}, "validateDayOfMonth"); +var isLeapYear = /* @__PURE__ */ __name((year) => { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +}, "isLeapYear"); +var parseDateValue = /* @__PURE__ */ __name((value, type, lower, upper) => { + const dateVal = strictParseByte(stripLeadingZeroes(value)); + if (dateVal < lower || dateVal > upper) { + throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`); + } + return dateVal; +}, "parseDateValue"); +var parseMilliseconds = /* @__PURE__ */ __name((value) => { + if (value === null || value === void 0) { + return 0; + } + return strictParseFloat32("0." + value) * 1e3; +}, "parseMilliseconds"); +var parseOffsetToMilliseconds = /* @__PURE__ */ __name((value) => { + const directionStr = value[0]; + let direction = 1; + if (directionStr == "+") { + direction = 1; + } else if (directionStr == "-") { + direction = -1; + } else { + throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`); + } + const hour = Number(value.substring(1, 3)); + const minute = Number(value.substring(4, 6)); + return direction * (hour * 60 + minute) * 60 * 1e3; +}, "parseOffsetToMilliseconds"); +var stripLeadingZeroes = /* @__PURE__ */ __name((value) => { + let idx = 0; + while (idx < value.length - 1 && value.charAt(idx) === "0") { + idx++; + } + if (idx === 0) { + return value; } + return value.slice(idx); +}, "stripLeadingZeroes"); + +// src/exceptions.ts +var ServiceException = class _ServiceException extends Error { static { - __name(this, "HashCalculator"); + __name(this, "ServiceException"); } - _write(chunk, encoding, callback) { - try { - this.hash.update((0, import_util_utf8.toUint8Array)(chunk)); - } catch (err) { - return callback(err); + constructor(options) { + super(options.message); + Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype); + this.name = options.name; + this.$fault = options.$fault; + this.$metadata = options.$metadata; + } + /** + * Checks if a value is an instance of ServiceException (duck typed) + */ + static isInstance(value) { + if (!value) + return false; + const candidate = value; + return _ServiceException.prototype.isPrototypeOf(candidate) || Boolean(candidate.$fault) && Boolean(candidate.$metadata) && (candidate.$fault === "client" || candidate.$fault === "server"); + } + /** + * Custom instanceof check to support the operator for ServiceException base class + */ + static [Symbol.hasInstance](instance) { + if (!instance) + return false; + const candidate = instance; + if (this === _ServiceException) { + return _ServiceException.isInstance(instance); } - callback(); + if (_ServiceException.isInstance(instance)) { + if (candidate.name && this.name) { + return this.prototype.isPrototypeOf(instance) || candidate.name === this.name; + } + return this.prototype.isPrototypeOf(instance); + } + return false; } }; - -// src/fileStreamHasher.ts -var fileStreamHasher = /* @__PURE__ */ __name((hashCtor, fileStream) => new Promise((resolve, reject) => { - if (!isReadStream(fileStream)) { - reject(new Error("Unable to calculate hash for non-file streams.")); - return; - } - const fileStreamTee = (0, import_fs.createReadStream)(fileStream.path, { - start: fileStream.start, - end: fileStream.end - }); - const hash = new hashCtor(); - const hashCalculator = new HashCalculator(hash); - fileStreamTee.pipe(hashCalculator); - fileStreamTee.on("error", (err) => { - hashCalculator.end(); - reject(err); - }); - hashCalculator.on("error", reject); - hashCalculator.on("finish", function() { - hash.digest().then(resolve).catch(reject); +var decorateServiceException = /* @__PURE__ */ __name((exception, additions = {}) => { + Object.entries(additions).filter(([, v]) => v !== void 0).forEach(([k, v]) => { + if (exception[k] == void 0 || exception[k] === "") { + exception[k] = v; + } }); -}), "fileStreamHasher"); -var isReadStream = /* @__PURE__ */ __name((stream) => typeof stream.path === "string", "isReadStream"); + const message = exception.message || exception.Message || "UnknownError"; + exception.message = message; + delete exception.Message; + return exception; +}, "decorateServiceException"); -// src/readableStreamHasher.ts -var readableStreamHasher = /* @__PURE__ */ __name((hashCtor, readableStream) => { - if (readableStream.readableFlowing !== null) { - throw new Error("Unable to calculate hash for flowing readable stream"); - } - const hash = new hashCtor(); - const hashCalculator = new HashCalculator(hash); - readableStream.pipe(hashCalculator); - return new Promise((resolve, reject) => { - readableStream.on("error", (err) => { - hashCalculator.end(); - reject(err); - }); - hashCalculator.on("error", reject); - hashCalculator.on("finish", () => { - hash.digest().then(resolve).catch(reject); - }); +// src/default-error-handler.ts +var throwDefaultError = /* @__PURE__ */ __name(({ output, parsedBody, exceptionCtor, errorCode }) => { + const $metadata = deserializeMetadata(output); + const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : void 0; + const response = new exceptionCtor({ + name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError", + $fault: "client", + $metadata }); -}, "readableStreamHasher"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 10780: -/***/ ((module) => { + throw decorateServiceException(response, parsedBody); +}, "throwDefaultError"); +var withBaseException = /* @__PURE__ */ __name((ExceptionCtor) => { + return ({ output, parsedBody, errorCode }) => { + throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode }); + }; +}, "withBaseException"); +var deserializeMetadata = /* @__PURE__ */ __name((output) => ({ + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"] +}), "deserializeMetadata"); -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -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 }); +// src/defaults-mode.ts +var loadConfigsForDefaultMode = /* @__PURE__ */ __name((mode) => { + switch (mode) { + case "standard": + return { + retryMode: "standard", + connectionTimeout: 3100 + }; + case "in-region": + return { + retryMode: "standard", + connectionTimeout: 1100 + }; + case "cross-region": + return { + retryMode: "standard", + connectionTimeout: 3100 + }; + case "mobile": + return { + retryMode: "standard", + connectionTimeout: 3e4 + }; + default: + return {}; } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - isArrayBuffer: () => isArrayBuffer -}); -module.exports = __toCommonJS(src_exports); -var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - +}, "loadConfigsForDefaultMode"); +// src/emitWarningIfUnsupportedVersion.ts +var warningEmitted = false; +var emitWarningIfUnsupportedVersion = /* @__PURE__ */ __name((version) => { + if (version && !warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 16) { + warningEmitted = true; + } +}, "emitWarningIfUnsupportedVersion"); -/***/ }), +// src/extended-encode-uri-component.ts -/***/ 82800: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -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); +// src/extensions/checksum.ts -// src/index.ts -var src_exports = {}; -__export(src_exports, { - contentLengthMiddleware: () => contentLengthMiddleware, - contentLengthMiddlewareOptions: () => contentLengthMiddlewareOptions, - getContentLengthPlugin: () => getContentLengthPlugin -}); -module.exports = __toCommonJS(src_exports); -var import_protocol_http = __nccwpck_require__(64418); -var CONTENT_LENGTH_HEADER = "content-length"; -function contentLengthMiddleware(bodyLengthChecker) { - return (next) => async (args) => { - const request = args.request; - if (import_protocol_http.HttpRequest.isInstance(request)) { - const { body, headers } = request; - if (body && Object.keys(headers).map((str) => str.toLowerCase()).indexOf(CONTENT_LENGTH_HEADER) === -1) { - try { - const length = bodyLengthChecker(body); - request.headers = { - ...request.headers, - [CONTENT_LENGTH_HEADER]: String(length) - }; - } catch (error) { - } - } +var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + const checksumAlgorithms = []; + for (const id in import_types.AlgorithmId) { + const algorithmId = import_types.AlgorithmId[id]; + if (runtimeConfig[algorithmId] === void 0) { + continue; } - return next({ - ...args, - request + checksumAlgorithms.push({ + algorithmId: () => algorithmId, + checksumConstructor: () => runtimeConfig[algorithmId] }); - }; -} -__name(contentLengthMiddleware, "contentLengthMiddleware"); -var contentLengthMiddlewareOptions = { - step: "build", - tags: ["SET_CONTENT_LENGTH", "CONTENT_LENGTH"], - name: "contentLengthMiddleware", - override: true -}; -var getContentLengthPlugin = /* @__PURE__ */ __name((options) => ({ - applyToStack: (clientStack) => { - clientStack.add(contentLengthMiddleware(options.bodyLengthChecker), contentLengthMiddlewareOptions); } -}), "getContentLengthPlugin"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 31518: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + } + }; +}, "getChecksumConfiguration"); +var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}, "resolveChecksumRuntimeConfig"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getEndpointFromConfig = void 0; -const node_config_provider_1 = __nccwpck_require__(33461); -const getEndpointUrlConfig_1 = __nccwpck_require__(7574); -const getEndpointFromConfig = async (serviceId) => (0, node_config_provider_1.loadConfig)((0, getEndpointUrlConfig_1.getEndpointUrlConfig)(serviceId !== null && serviceId !== void 0 ? serviceId : ""))(); -exports.getEndpointFromConfig = getEndpointFromConfig; +// src/extensions/retry.ts +var getRetryConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return { + setRetryStrategy(retryStrategy) { + runtimeConfig.retryStrategy = retryStrategy; + }, + retryStrategy() { + return runtimeConfig.retryStrategy; + } + }; +}, "getRetryConfiguration"); +var resolveRetryRuntimeConfig = /* @__PURE__ */ __name((retryStrategyConfiguration) => { + const runtimeConfig = {}; + runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy(); + return runtimeConfig; +}, "resolveRetryRuntimeConfig"); +// src/extensions/defaultExtensionConfiguration.ts +var getDefaultExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return Object.assign(getChecksumConfiguration(runtimeConfig), getRetryConfiguration(runtimeConfig)); +}, "getDefaultExtensionConfiguration"); +var getDefaultClientConfiguration = getDefaultExtensionConfiguration; +var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { + return Object.assign(resolveChecksumRuntimeConfig(config), resolveRetryRuntimeConfig(config)); +}, "resolveDefaultRuntimeConfig"); -/***/ }), +// src/get-array-if-single-item.ts +var getArrayIfSingleItem = /* @__PURE__ */ __name((mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray], "getArrayIfSingleItem"); -/***/ 7574: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// src/get-value-from-text-node.ts +var getValueFromTextNode = /* @__PURE__ */ __name((obj) => { + const textNodeName = "#text"; + for (const key in obj) { + if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== void 0) { + obj[key] = obj[key][textNodeName]; + } else if (typeof obj[key] === "object" && obj[key] !== null) { + obj[key] = getValueFromTextNode(obj[key]); + } + } + return obj; +}, "getValueFromTextNode"); -"use strict"; +// src/is-serializable-header-value.ts +var isSerializableHeaderValue = /* @__PURE__ */ __name((value) => { + return value != null; +}, "isSerializableHeaderValue"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getEndpointUrlConfig = void 0; -const shared_ini_file_loader_1 = __nccwpck_require__(43507); -const ENV_ENDPOINT_URL = "AWS_ENDPOINT_URL"; -const CONFIG_ENDPOINT_URL = "endpoint_url"; -const getEndpointUrlConfig = (serviceId) => ({ - environmentVariableSelector: (env) => { - const serviceSuffixParts = serviceId.split(" ").map((w) => w.toUpperCase()); - const serviceEndpointUrl = env[[ENV_ENDPOINT_URL, ...serviceSuffixParts].join("_")]; - if (serviceEndpointUrl) - return serviceEndpointUrl; - const endpointUrl = env[ENV_ENDPOINT_URL]; - if (endpointUrl) - return endpointUrl; - return undefined; +// src/lazy-json.ts +var LazyJsonString = /* @__PURE__ */ __name(function LazyJsonString2(val) { + const str = Object.assign(new String(val), { + deserializeJSON() { + return JSON.parse(String(val)); }, - configFileSelector: (profile, config) => { - if (config && profile.services) { - const servicesSection = config[["services", profile.services].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)]; - if (servicesSection) { - const servicePrefixParts = serviceId.split(" ").map((w) => w.toLowerCase()); - const endpointUrl = servicesSection[[servicePrefixParts.join("_"), CONFIG_ENDPOINT_URL].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)]; - if (endpointUrl) - return endpointUrl; - } - } - const endpointUrl = profile[CONFIG_ENDPOINT_URL]; - if (endpointUrl) - return endpointUrl; - return undefined; + toString() { + return String(val); }, - default: undefined, -}); -exports.getEndpointUrlConfig = getEndpointUrlConfig; - - -/***/ }), - -/***/ 82918: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -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 }); + toJSON() { + return String(val); + } + }); + return str; +}, "LazyJsonString"); +LazyJsonString.from = (object) => { + if (object && typeof object === "object" && (object instanceof LazyJsonString || "deserializeJSON" in object)) { + return object; + } else if (typeof object === "string" || Object.getPrototypeOf(object) === String.prototype) { + return LazyJsonString(String(object)); } - return to; + return LazyJsonString(JSON.stringify(object)); }; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +LazyJsonString.fromObject = LazyJsonString.from; -// src/index.ts -var src_exports = {}; -__export(src_exports, { - endpointMiddleware: () => endpointMiddleware, - endpointMiddlewareOptions: () => endpointMiddlewareOptions, - getEndpointFromInstructions: () => getEndpointFromInstructions, - getEndpointPlugin: () => getEndpointPlugin, - resolveEndpointConfig: () => resolveEndpointConfig, - resolveParams: () => resolveParams, - toEndpointV1: () => toEndpointV1 -}); -module.exports = __toCommonJS(src_exports); +// src/NoOpLogger.ts +var NoOpLogger = class { + static { + __name(this, "NoOpLogger"); + } + trace() { + } + debug() { + } + info() { + } + warn() { + } + error() { + } +}; -// src/service-customizations/s3.ts -var resolveParamsForS3 = /* @__PURE__ */ __name(async (endpointParams) => { - const bucket = endpointParams?.Bucket || ""; - if (typeof endpointParams.Bucket === "string") { - endpointParams.Bucket = bucket.replace(/#/g, encodeURIComponent("#")).replace(/\?/g, encodeURIComponent("?")); +// src/object-mapping.ts +function map(arg0, arg1, arg2) { + let target; + let filter; + let instructions; + if (typeof arg1 === "undefined" && typeof arg2 === "undefined") { + target = {}; + instructions = arg0; + } else { + target = arg0; + if (typeof arg1 === "function") { + filter = arg1; + instructions = arg2; + return mapWithFilter(target, filter, instructions); + } else { + instructions = arg1; + } + } + for (const key of Object.keys(instructions)) { + if (!Array.isArray(instructions[key])) { + target[key] = instructions[key]; + continue; + } + applyInstruction(target, null, instructions, key); + } + return target; +} +__name(map, "map"); +var convertMap = /* @__PURE__ */ __name((target) => { + const output = {}; + for (const [k, v] of Object.entries(target || {})) { + output[k] = [, v]; + } + return output; +}, "convertMap"); +var take = /* @__PURE__ */ __name((source, instructions) => { + const out = {}; + for (const key in instructions) { + applyInstruction(out, source, instructions, key); + } + return out; +}, "take"); +var mapWithFilter = /* @__PURE__ */ __name((target, filter, instructions) => { + return map( + target, + Object.entries(instructions).reduce( + (_instructions, [key, value]) => { + if (Array.isArray(value)) { + _instructions[key] = value; + } else { + if (typeof value === "function") { + _instructions[key] = [filter, value()]; + } else { + _instructions[key] = [filter, value]; + } + } + return _instructions; + }, + {} + ) + ); +}, "mapWithFilter"); +var applyInstruction = /* @__PURE__ */ __name((target, source, instructions, targetKey) => { + if (source !== null) { + let instruction = instructions[targetKey]; + if (typeof instruction === "function") { + instruction = [, instruction]; + } + const [filter2 = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction; + if (typeof filter2 === "function" && filter2(source[sourceKey]) || typeof filter2 !== "function" && !!filter2) { + target[targetKey] = valueFn(source[sourceKey]); + } + return; } - if (isArnBucketName(bucket)) { - if (endpointParams.ForcePathStyle === true) { - throw new Error("Path-style addressing cannot be used with ARN buckets"); + let [filter, value] = instructions[targetKey]; + if (typeof value === "function") { + let _value; + const defaultFilterPassed = filter === void 0 && (_value = value()) != null; + const customFilterPassed = typeof filter === "function" && !!filter(void 0) || typeof filter !== "function" && !!filter; + if (defaultFilterPassed) { + target[targetKey] = _value; + } else if (customFilterPassed) { + target[targetKey] = value(); + } + } else { + const defaultFilterPassed = filter === void 0 && value != null; + const customFilterPassed = typeof filter === "function" && !!filter(value) || typeof filter !== "function" && !!filter; + if (defaultFilterPassed || customFilterPassed) { + target[targetKey] = value; } - } else if (!isDnsCompatibleBucketName(bucket) || bucket.indexOf(".") !== -1 && !String(endpointParams.Endpoint).startsWith("http:") || bucket.toLowerCase() !== bucket || bucket.length < 3) { - endpointParams.ForcePathStyle = true; } - if (endpointParams.DisableMultiRegionAccessPoints) { - endpointParams.disableMultiRegionAccessPoints = true; - endpointParams.DisableMRAP = true; +}, "applyInstruction"); +var nonNullish = /* @__PURE__ */ __name((_) => _ != null, "nonNullish"); +var pass = /* @__PURE__ */ __name((_) => _, "pass"); + +// src/quote-header.ts +function quoteHeader(part) { + if (part.includes(",") || part.includes('"')) { + part = `"${part.replace(/"/g, '\\"')}"`; } - return endpointParams; -}, "resolveParamsForS3"); -var DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/; -var IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/; -var DOTS_PATTERN = /\.\./; -var isDnsCompatibleBucketName = /* @__PURE__ */ __name((bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName), "isDnsCompatibleBucketName"); -var isArnBucketName = /* @__PURE__ */ __name((bucketName) => { - const [arn, partition, service, , , bucket] = bucketName.split(":"); - const isArn = arn === "arn" && bucketName.split(":").length >= 6; - const isValidArn = Boolean(isArn && partition && service && bucket); - if (isArn && !isValidArn) { - throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`); + return part; +} +__name(quoteHeader, "quoteHeader"); + +// src/resolve-path.ts + + +// src/ser-utils.ts +var serializeFloat = /* @__PURE__ */ __name((value) => { + if (value !== value) { + return "NaN"; } - return isValidArn; -}, "isArnBucketName"); + switch (value) { + case Infinity: + return "Infinity"; + case -Infinity: + return "-Infinity"; + default: + return value; + } +}, "serializeFloat"); +var serializeDateTime = /* @__PURE__ */ __name((date) => date.toISOString().replace(".000Z", "Z"), "serializeDateTime"); -// src/adaptors/createConfigValueProvider.ts -var createConfigValueProvider = /* @__PURE__ */ __name((configKey, canonicalEndpointParamKey, config) => { - const configProvider = /* @__PURE__ */ __name(async () => { - const configValue = config[configKey] ?? config[canonicalEndpointParamKey]; - if (typeof configValue === "function") { - return configValue(); - } - return configValue; - }, "configProvider"); - if (configKey === "credentialScope" || canonicalEndpointParamKey === "CredentialScope") { - return async () => { - const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; - const configValue = credentials?.credentialScope ?? credentials?.CredentialScope; - return configValue; - }; +// src/serde-json.ts +var _json = /* @__PURE__ */ __name((obj) => { + if (obj == null) { + return {}; } - if (configKey === "accountId" || canonicalEndpointParamKey === "AccountId") { - return async () => { - const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; - const configValue = credentials?.accountId ?? credentials?.AccountId; - return configValue; - }; + if (Array.isArray(obj)) { + return obj.filter((_) => _ != null).map(_json); } - if (configKey === "endpoint" || canonicalEndpointParamKey === "endpoint") { - return async () => { - const endpoint = await configProvider(); - if (endpoint && typeof endpoint === "object") { - if ("url" in endpoint) { - return endpoint.url.href; - } - if ("hostname" in endpoint) { - const { protocol, hostname, port, path } = endpoint; - return `${protocol}//${hostname}${port ? ":" + port : ""}${path}`; - } + if (typeof obj === "object") { + const target = {}; + for (const key of Object.keys(obj)) { + if (obj[key] == null) { + continue; } - return endpoint; - }; - } - return configProvider; -}, "createConfigValueProvider"); - -// src/adaptors/getEndpointFromInstructions.ts -var import_getEndpointFromConfig = __nccwpck_require__(31518); - -// src/adaptors/toEndpointV1.ts -var import_url_parser = __nccwpck_require__(14681); -var toEndpointV1 = /* @__PURE__ */ __name((endpoint) => { - if (typeof endpoint === "object") { - if ("url" in endpoint) { - return (0, import_url_parser.parseUrl)(endpoint.url); + target[key] = _json(obj[key]); } - return endpoint; + return target; } - return (0, import_url_parser.parseUrl)(endpoint); -}, "toEndpointV1"); + return obj; +}, "_json"); -// src/adaptors/getEndpointFromInstructions.ts -var getEndpointFromInstructions = /* @__PURE__ */ __name(async (commandInput, instructionsSupplier, clientConfig, context) => { - if (!clientConfig.endpoint) { - let endpointFromConfig; - if (clientConfig.serviceConfiguredEndpoint) { - endpointFromConfig = await clientConfig.serviceConfiguredEndpoint(); +// src/split-every.ts +function splitEvery(value, delimiter, numDelimiters) { + if (numDelimiters <= 0 || !Number.isInteger(numDelimiters)) { + throw new Error("Invalid number of delimiters (" + numDelimiters + ") for splitEvery."); + } + const segments = value.split(delimiter); + if (numDelimiters === 1) { + return segments; + } + const compoundSegments = []; + let currentSegment = ""; + for (let i = 0; i < segments.length; i++) { + if (currentSegment === "") { + currentSegment = segments[i]; } else { - endpointFromConfig = await (0, import_getEndpointFromConfig.getEndpointFromConfig)(clientConfig.serviceId); + currentSegment += delimiter + segments[i]; } - if (endpointFromConfig) { - clientConfig.endpoint = () => Promise.resolve(toEndpointV1(endpointFromConfig)); + if ((i + 1) % numDelimiters === 0) { + compoundSegments.push(currentSegment); + currentSegment = ""; } } - const endpointParams = await resolveParams(commandInput, instructionsSupplier, clientConfig); - if (typeof clientConfig.endpointProvider !== "function") { - throw new Error("config.endpointProvider is not set."); + if (currentSegment !== "") { + compoundSegments.push(currentSegment); } - const endpoint = clientConfig.endpointProvider(endpointParams, context); - return endpoint; -}, "getEndpointFromInstructions"); -var resolveParams = /* @__PURE__ */ __name(async (commandInput, instructionsSupplier, clientConfig) => { - const endpointParams = {}; - const instructions = instructionsSupplier?.getEndpointParameterInstructions?.() || {}; - for (const [name, instruction] of Object.entries(instructions)) { - switch (instruction.type) { - case "staticContextParams": - endpointParams[name] = instruction.value; - break; - case "contextParams": - endpointParams[name] = commandInput[instruction.name]; - break; - case "clientContextParams": - case "builtInParams": - endpointParams[name] = await createConfigValueProvider(instruction.name, name, clientConfig)(); + return compoundSegments; +} +__name(splitEvery, "splitEvery"); + +// src/split-header.ts +var splitHeader = /* @__PURE__ */ __name((value) => { + const z = value.length; + const values = []; + let withinQuotes = false; + let prevChar = void 0; + let anchor = 0; + for (let i = 0; i < z; ++i) { + const char = value[i]; + switch (char) { + case `"`: + if (prevChar !== "\\") { + withinQuotes = !withinQuotes; + } break; - case "operationContextParams": - endpointParams[name] = instruction.get(commandInput); + case ",": + if (!withinQuotes) { + values.push(value.slice(anchor, i)); + anchor = i + 1; + } break; default: - throw new Error("Unrecognized endpoint parameter instruction: " + JSON.stringify(instruction)); } + prevChar = char; } - if (Object.keys(instructions).length === 0) { - Object.assign(endpointParams, clientConfig); - } - if (String(clientConfig.serviceId).toLowerCase() === "s3") { - await resolveParamsForS3(endpointParams); - } - return endpointParams; -}, "resolveParams"); - -// src/endpointMiddleware.ts -var import_core = __nccwpck_require__(55829); -var import_util_middleware = __nccwpck_require__(2390); -var endpointMiddleware = /* @__PURE__ */ __name(({ - config, - instructions -}) => { - return (next, context) => async (args) => { - if (config.endpoint) { - (0, import_core.setFeature)(context, "ENDPOINT_OVERRIDE", "N"); + values.push(value.slice(anchor)); + return values.map((v) => { + v = v.trim(); + const z2 = v.length; + if (z2 < 2) { + return v; } - const endpoint = await getEndpointFromInstructions( - args.input, - { - getEndpointParameterInstructions() { - return instructions; - } - }, - { ...config }, - context - ); - context.endpointV2 = endpoint; - context.authSchemes = endpoint.properties?.authSchemes; - const authScheme = context.authSchemes?.[0]; - if (authScheme) { - context["signing_region"] = authScheme.signingRegion; - context["signing_service"] = authScheme.signingName; - const smithyContext = (0, import_util_middleware.getSmithyContext)(context); - const httpAuthOption = smithyContext?.selectedHttpAuthScheme?.httpAuthOption; - if (httpAuthOption) { - httpAuthOption.signingProperties = Object.assign( - httpAuthOption.signingProperties || {}, - { - signing_region: authScheme.signingRegion, - signingRegion: authScheme.signingRegion, - signing_service: authScheme.signingName, - signingName: authScheme.signingName, - signingRegionSet: authScheme.signingRegionSet - }, - authScheme.properties - ); - } + if (v[0] === `"` && v[z2 - 1] === `"`) { + v = v.slice(1, z2 - 1); } - return next({ - ...args - }); - }; -}, "endpointMiddleware"); - -// src/getEndpointPlugin.ts -var import_middleware_serde = __nccwpck_require__(81238); -var endpointMiddlewareOptions = { - step: "serialize", - tags: ["ENDPOINT_PARAMETERS", "ENDPOINT_V2", "ENDPOINT"], - name: "endpointV2Middleware", - override: true, - relation: "before", - toMiddleware: import_middleware_serde.serializerMiddlewareOption.name -}; -var getEndpointPlugin = /* @__PURE__ */ __name((config, instructions) => ({ - applyToStack: (clientStack) => { - clientStack.addRelativeTo( - endpointMiddleware({ - config, - instructions - }), - endpointMiddlewareOptions - ); - } -}), "getEndpointPlugin"); - -// src/resolveEndpointConfig.ts - -var import_getEndpointFromConfig2 = __nccwpck_require__(31518); -var resolveEndpointConfig = /* @__PURE__ */ __name((input) => { - const tls = input.tls ?? true; - const { endpoint, useDualstackEndpoint, useFipsEndpoint } = input; - const customEndpointProvider = endpoint != null ? async () => toEndpointV1(await (0, import_util_middleware.normalizeProvider)(endpoint)()) : void 0; - const isCustomEndpoint = !!endpoint; - const resolvedConfig = Object.assign(input, { - endpoint: customEndpointProvider, - tls, - isCustomEndpoint, - useDualstackEndpoint: (0, import_util_middleware.normalizeProvider)(useDualstackEndpoint ?? false), - useFipsEndpoint: (0, import_util_middleware.normalizeProvider)(useFipsEndpoint ?? false) + return v.replace(/\\"/g, '"'); }); - let configuredEndpointPromise = void 0; - resolvedConfig.serviceConfiguredEndpoint = async () => { - if (input.serviceId && !configuredEndpointPromise) { - configuredEndpointPromise = (0, import_getEndpointFromConfig2.getEndpointFromConfig)(input.serviceId); - } - return configuredEndpointPromise; - }; - return resolvedConfig; -}, "resolveEndpointConfig"); +}, "splitHeader"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -242031,8 +239205,8 @@ var resolveEndpointConfig = /* @__PURE__ */ __name((input) => { /***/ }), -/***/ 96039: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 55756: +/***/ ((module) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; @@ -242056,1092 +239230,1174 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var src_exports = {}; __export(src_exports, { - AdaptiveRetryStrategy: () => AdaptiveRetryStrategy, - CONFIG_MAX_ATTEMPTS: () => CONFIG_MAX_ATTEMPTS, - CONFIG_RETRY_MODE: () => CONFIG_RETRY_MODE, - ENV_MAX_ATTEMPTS: () => ENV_MAX_ATTEMPTS, - ENV_RETRY_MODE: () => ENV_RETRY_MODE, - NODE_MAX_ATTEMPT_CONFIG_OPTIONS: () => NODE_MAX_ATTEMPT_CONFIG_OPTIONS, - NODE_RETRY_MODE_CONFIG_OPTIONS: () => NODE_RETRY_MODE_CONFIG_OPTIONS, - StandardRetryStrategy: () => StandardRetryStrategy, - defaultDelayDecider: () => defaultDelayDecider, - defaultRetryDecider: () => defaultRetryDecider, - getOmitRetryHeadersPlugin: () => getOmitRetryHeadersPlugin, - getRetryAfterHint: () => getRetryAfterHint, - getRetryPlugin: () => getRetryPlugin, - omitRetryHeadersMiddleware: () => omitRetryHeadersMiddleware, - omitRetryHeadersMiddlewareOptions: () => omitRetryHeadersMiddlewareOptions, - resolveRetryConfig: () => resolveRetryConfig, - retryMiddleware: () => retryMiddleware, - retryMiddlewareOptions: () => retryMiddlewareOptions + AlgorithmId: () => AlgorithmId, + EndpointURLScheme: () => EndpointURLScheme, + FieldPosition: () => FieldPosition, + HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, + HttpAuthLocation: () => HttpAuthLocation, + IniSectionType: () => IniSectionType, + RequestHandlerProtocol: () => RequestHandlerProtocol, + SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, + getDefaultClientConfiguration: () => getDefaultClientConfiguration, + resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig }); module.exports = __toCommonJS(src_exports); -// src/AdaptiveRetryStrategy.ts - - -// src/StandardRetryStrategy.ts -var import_protocol_http = __nccwpck_require__(64418); - - -var import_uuid = __nccwpck_require__(7761); - -// src/defaultRetryQuota.ts -var import_util_retry = __nccwpck_require__(84902); -var getDefaultRetryQuota = /* @__PURE__ */ __name((initialRetryTokens, options) => { - const MAX_CAPACITY = initialRetryTokens; - const noRetryIncrement = options?.noRetryIncrement ?? import_util_retry.NO_RETRY_INCREMENT; - const retryCost = options?.retryCost ?? import_util_retry.RETRY_COST; - const timeoutRetryCost = options?.timeoutRetryCost ?? import_util_retry.TIMEOUT_RETRY_COST; - let availableCapacity = initialRetryTokens; - const getCapacityAmount = /* @__PURE__ */ __name((error) => error.name === "TimeoutError" ? timeoutRetryCost : retryCost, "getCapacityAmount"); - const hasRetryTokens = /* @__PURE__ */ __name((error) => getCapacityAmount(error) <= availableCapacity, "hasRetryTokens"); - const retrieveRetryTokens = /* @__PURE__ */ __name((error) => { - if (!hasRetryTokens(error)) { - throw new Error("No retry token available"); - } - const capacityAmount = getCapacityAmount(error); - availableCapacity -= capacityAmount; - return capacityAmount; - }, "retrieveRetryTokens"); - const releaseRetryTokens = /* @__PURE__ */ __name((capacityReleaseAmount) => { - availableCapacity += capacityReleaseAmount ?? noRetryIncrement; - availableCapacity = Math.min(availableCapacity, MAX_CAPACITY); - }, "releaseRetryTokens"); - return Object.freeze({ - hasRetryTokens, - retrieveRetryTokens, - releaseRetryTokens - }); -}, "getDefaultRetryQuota"); - -// src/delayDecider.ts - -var defaultDelayDecider = /* @__PURE__ */ __name((delayBase, attempts) => Math.floor(Math.min(import_util_retry.MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase)), "defaultDelayDecider"); - -// src/retryDecider.ts -var import_service_error_classification = __nccwpck_require__(6375); -var defaultRetryDecider = /* @__PURE__ */ __name((error) => { - if (!error) { - return false; - } - return (0, import_service_error_classification.isRetryableByTrait)(error) || (0, import_service_error_classification.isClockSkewError)(error) || (0, import_service_error_classification.isThrottlingError)(error) || (0, import_service_error_classification.isTransientError)(error); -}, "defaultRetryDecider"); +// src/auth/auth.ts +var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { + HttpAuthLocation2["HEADER"] = "header"; + HttpAuthLocation2["QUERY"] = "query"; + return HttpAuthLocation2; +})(HttpAuthLocation || {}); -// src/util.ts -var asSdkError = /* @__PURE__ */ __name((error) => { - if (error instanceof Error) - return error; - if (error instanceof Object) - return Object.assign(new Error(), error); - if (typeof error === "string") - return new Error(error); - return new Error(`AWS SDK error wrapper for ${error}`); -}, "asSdkError"); +// src/auth/HttpApiKeyAuth.ts +var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { + HttpApiKeyAuthLocation2["HEADER"] = "header"; + HttpApiKeyAuthLocation2["QUERY"] = "query"; + return HttpApiKeyAuthLocation2; +})(HttpApiKeyAuthLocation || {}); -// src/StandardRetryStrategy.ts -var StandardRetryStrategy = class { - constructor(maxAttemptsProvider, options) { - this.maxAttemptsProvider = maxAttemptsProvider; - this.mode = import_util_retry.RETRY_MODES.STANDARD; - this.retryDecider = options?.retryDecider ?? defaultRetryDecider; - this.delayDecider = options?.delayDecider ?? defaultDelayDecider; - this.retryQuota = options?.retryQuota ?? getDefaultRetryQuota(import_util_retry.INITIAL_RETRY_TOKENS); - } - static { - __name(this, "StandardRetryStrategy"); - } - shouldRetry(error, attempts, maxAttempts) { - return attempts < maxAttempts && this.retryDecider(error) && this.retryQuota.hasRetryTokens(error); - } - async getMaxAttempts() { - let maxAttempts; - try { - maxAttempts = await this.maxAttemptsProvider(); - } catch (error) { - maxAttempts = import_util_retry.DEFAULT_MAX_ATTEMPTS; - } - return maxAttempts; - } - async retry(next, args, options) { - let retryTokenAmount; - let attempts = 0; - let totalDelay = 0; - const maxAttempts = await this.getMaxAttempts(); - const { request } = args; - if (import_protocol_http.HttpRequest.isInstance(request)) { - request.headers[import_util_retry.INVOCATION_ID_HEADER] = (0, import_uuid.v4)(); - } - while (true) { - try { - if (import_protocol_http.HttpRequest.isInstance(request)) { - request.headers[import_util_retry.REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; - } - if (options?.beforeRequest) { - await options.beforeRequest(); - } - const { response, output } = await next(args); - if (options?.afterRequest) { - options.afterRequest(response); - } - this.retryQuota.releaseRetryTokens(retryTokenAmount); - output.$metadata.attempts = attempts + 1; - output.$metadata.totalRetryDelay = totalDelay; - return { response, output }; - } catch (e) { - const err = asSdkError(e); - attempts++; - if (this.shouldRetry(err, attempts, maxAttempts)) { - retryTokenAmount = this.retryQuota.retrieveRetryTokens(err); - const delayFromDecider = this.delayDecider( - (0, import_service_error_classification.isThrottlingError)(err) ? import_util_retry.THROTTLING_RETRY_DELAY_BASE : import_util_retry.DEFAULT_RETRY_DELAY_BASE, - attempts - ); - const delayFromResponse = getDelayFromRetryAfterHeader(err.$response); - const delay = Math.max(delayFromResponse || 0, delayFromDecider); - totalDelay += delay; - await new Promise((resolve) => setTimeout(resolve, delay)); - continue; - } - if (!err.$metadata) { - err.$metadata = {}; - } - err.$metadata.attempts = attempts; - err.$metadata.totalRetryDelay = totalDelay; - throw err; - } - } - } -}; -var getDelayFromRetryAfterHeader = /* @__PURE__ */ __name((response) => { - if (!import_protocol_http.HttpResponse.isInstance(response)) - return; - const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === "retry-after"); - if (!retryAfterHeaderName) - return; - const retryAfter = response.headers[retryAfterHeaderName]; - const retryAfterSeconds = Number(retryAfter); - if (!Number.isNaN(retryAfterSeconds)) - return retryAfterSeconds * 1e3; - const retryAfterDate = new Date(retryAfter); - return retryAfterDate.getTime() - Date.now(); -}, "getDelayFromRetryAfterHeader"); +// src/endpoint.ts +var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { + EndpointURLScheme2["HTTP"] = "http"; + EndpointURLScheme2["HTTPS"] = "https"; + return EndpointURLScheme2; +})(EndpointURLScheme || {}); -// src/AdaptiveRetryStrategy.ts -var AdaptiveRetryStrategy = class extends StandardRetryStrategy { - static { - __name(this, "AdaptiveRetryStrategy"); - } - constructor(maxAttemptsProvider, options) { - const { rateLimiter, ...superOptions } = options ?? {}; - super(maxAttemptsProvider, superOptions); - this.rateLimiter = rateLimiter ?? new import_util_retry.DefaultRateLimiter(); - this.mode = import_util_retry.RETRY_MODES.ADAPTIVE; - } - async retry(next, args) { - return super.retry(next, args, { - beforeRequest: async () => { - return this.rateLimiter.getSendToken(); - }, - afterRequest: (response) => { - this.rateLimiter.updateClientSendingRate(response); - } +// src/extensions/checksum.ts +var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { + AlgorithmId2["MD5"] = "md5"; + AlgorithmId2["CRC32"] = "crc32"; + AlgorithmId2["CRC32C"] = "crc32c"; + AlgorithmId2["SHA1"] = "sha1"; + AlgorithmId2["SHA256"] = "sha256"; + return AlgorithmId2; +})(AlgorithmId || {}); +var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== void 0) { + checksumAlgorithms.push({ + algorithmId: () => "sha256" /* SHA256 */, + checksumConstructor: () => runtimeConfig.sha256 }); } -}; - -// src/configurations.ts -var import_util_middleware = __nccwpck_require__(2390); - -var ENV_MAX_ATTEMPTS = "AWS_MAX_ATTEMPTS"; -var CONFIG_MAX_ATTEMPTS = "max_attempts"; -var NODE_MAX_ATTEMPT_CONFIG_OPTIONS = { - environmentVariableSelector: (env) => { - const value = env[ENV_MAX_ATTEMPTS]; - if (!value) - return void 0; - const maxAttempt = parseInt(value); - if (Number.isNaN(maxAttempt)) { - throw new Error(`Environment variable ${ENV_MAX_ATTEMPTS} mast be a number, got "${value}"`); - } - return maxAttempt; - }, - configFileSelector: (profile) => { - const value = profile[CONFIG_MAX_ATTEMPTS]; - if (!value) - return void 0; - const maxAttempt = parseInt(value); - if (Number.isNaN(maxAttempt)) { - throw new Error(`Shared config file entry ${CONFIG_MAX_ATTEMPTS} mast be a number, got "${value}"`); - } - return maxAttempt; - }, - default: import_util_retry.DEFAULT_MAX_ATTEMPTS -}; -var resolveRetryConfig = /* @__PURE__ */ __name((input) => { - const { retryStrategy, retryMode: _retryMode, maxAttempts: _maxAttempts } = input; - const maxAttempts = (0, import_util_middleware.normalizeProvider)(_maxAttempts ?? import_util_retry.DEFAULT_MAX_ATTEMPTS); - return Object.assign(input, { - maxAttempts, - retryStrategy: async () => { - if (retryStrategy) { - return retryStrategy; - } - const retryMode = await (0, import_util_middleware.normalizeProvider)(_retryMode)(); - if (retryMode === import_util_retry.RETRY_MODES.ADAPTIVE) { - return new import_util_retry.AdaptiveRetryStrategy(maxAttempts); - } - return new import_util_retry.StandardRetryStrategy(maxAttempts); - } - }); -}, "resolveRetryConfig"); -var ENV_RETRY_MODE = "AWS_RETRY_MODE"; -var CONFIG_RETRY_MODE = "retry_mode"; -var NODE_RETRY_MODE_CONFIG_OPTIONS = { - environmentVariableSelector: (env) => env[ENV_RETRY_MODE], - configFileSelector: (profile) => profile[CONFIG_RETRY_MODE], - default: import_util_retry.DEFAULT_RETRY_MODE -}; - -// src/omitRetryHeadersMiddleware.ts - - -var omitRetryHeadersMiddleware = /* @__PURE__ */ __name(() => (next) => async (args) => { - const { request } = args; - if (import_protocol_http.HttpRequest.isInstance(request)) { - delete request.headers[import_util_retry.INVOCATION_ID_HEADER]; - delete request.headers[import_util_retry.REQUEST_HEADER]; - } - return next(args); -}, "omitRetryHeadersMiddleware"); -var omitRetryHeadersMiddlewareOptions = { - name: "omitRetryHeadersMiddleware", - tags: ["RETRY", "HEADERS", "OMIT_RETRY_HEADERS"], - relation: "before", - toMiddleware: "awsAuthMiddleware", - override: true -}; -var getOmitRetryHeadersPlugin = /* @__PURE__ */ __name((options) => ({ - applyToStack: (clientStack) => { - clientStack.addRelativeTo(omitRetryHeadersMiddleware(), omitRetryHeadersMiddlewareOptions); + if (runtimeConfig.md5 != void 0) { + checksumAlgorithms.push({ + algorithmId: () => "md5" /* MD5 */, + checksumConstructor: () => runtimeConfig.md5 + }); } -}), "getOmitRetryHeadersPlugin"); - -// src/retryMiddleware.ts - - -var import_smithy_client = __nccwpck_require__(63570); - - -var import_isStreamingPayload = __nccwpck_require__(18977); -var retryMiddleware = /* @__PURE__ */ __name((options) => (next, context) => async (args) => { - let retryStrategy = await options.retryStrategy(); - const maxAttempts = await options.maxAttempts(); - if (isRetryStrategyV2(retryStrategy)) { - retryStrategy = retryStrategy; - let retryToken = await retryStrategy.acquireInitialRetryToken(context["partition_id"]); - let lastError = new Error(); - let attempts = 0; - let totalRetryDelay = 0; - const { request } = args; - const isRequest = import_protocol_http.HttpRequest.isInstance(request); - if (isRequest) { - request.headers[import_util_retry.INVOCATION_ID_HEADER] = (0, import_uuid.v4)(); - } - while (true) { - try { - if (isRequest) { - request.headers[import_util_retry.REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; - } - const { response, output } = await next(args); - retryStrategy.recordSuccess(retryToken); - output.$metadata.attempts = attempts + 1; - output.$metadata.totalRetryDelay = totalRetryDelay; - return { response, output }; - } catch (e) { - const retryErrorInfo = getRetryErrorInfo(e); - lastError = asSdkError(e); - if (isRequest && (0, import_isStreamingPayload.isStreamingPayload)(request)) { - (context.logger instanceof import_smithy_client.NoOpLogger ? console : context.logger)?.warn( - "An error was encountered in a non-retryable streaming request." - ); - throw lastError; - } - try { - retryToken = await retryStrategy.refreshRetryTokenForRetry(retryToken, retryErrorInfo); - } catch (refreshError) { - if (!lastError.$metadata) { - lastError.$metadata = {}; - } - lastError.$metadata.attempts = attempts + 1; - lastError.$metadata.totalRetryDelay = totalRetryDelay; - throw lastError; - } - attempts = retryToken.getRetryCount(); - const delay = retryToken.getRetryDelay(); - totalRetryDelay += delay; - await new Promise((resolve) => setTimeout(resolve, delay)); - } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; } - } else { - retryStrategy = retryStrategy; - if (retryStrategy?.mode) - context.userAgent = [...context.userAgent || [], ["cfg/retry-mode", retryStrategy.mode]]; - return retryStrategy.retry(next, args); - } -}, "retryMiddleware"); -var isRetryStrategyV2 = /* @__PURE__ */ __name((retryStrategy) => typeof retryStrategy.acquireInitialRetryToken !== "undefined" && typeof retryStrategy.refreshRetryTokenForRetry !== "undefined" && typeof retryStrategy.recordSuccess !== "undefined", "isRetryStrategyV2"); -var getRetryErrorInfo = /* @__PURE__ */ __name((error) => { - const errorInfo = { - error, - errorType: getRetryErrorType(error) }; - const retryAfterHint = getRetryAfterHint(error.$response); - if (retryAfterHint) { - errorInfo.retryAfterHint = retryAfterHint; - } - return errorInfo; -}, "getRetryErrorInfo"); -var getRetryErrorType = /* @__PURE__ */ __name((error) => { - if ((0, import_service_error_classification.isThrottlingError)(error)) - return "THROTTLING"; - if ((0, import_service_error_classification.isTransientError)(error)) - return "TRANSIENT"; - if ((0, import_service_error_classification.isServerError)(error)) - return "SERVER_ERROR"; - return "CLIENT_ERROR"; -}, "getRetryErrorType"); -var retryMiddlewareOptions = { - name: "retryMiddleware", - tags: ["RETRY"], - step: "finalizeRequest", - priority: "high", - override: true -}; -var getRetryPlugin = /* @__PURE__ */ __name((options) => ({ - applyToStack: (clientStack) => { - clientStack.add(retryMiddleware(options), retryMiddlewareOptions); - } -}), "getRetryPlugin"); -var getRetryAfterHint = /* @__PURE__ */ __name((response) => { - if (!import_protocol_http.HttpResponse.isInstance(response)) - return; - const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === "retry-after"); - if (!retryAfterHeaderName) - return; - const retryAfter = response.headers[retryAfterHeaderName]; - const retryAfterSeconds = Number(retryAfter); - if (!Number.isNaN(retryAfterSeconds)) - return new Date(retryAfterSeconds * 1e3); - const retryAfterDate = new Date(retryAfter); - return retryAfterDate; -}, "getRetryAfterHint"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 18977: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isStreamingPayload = void 0; -const stream_1 = __nccwpck_require__(12781); -const isStreamingPayload = (request) => (request === null || request === void 0 ? void 0 : request.body) instanceof stream_1.Readable || - (typeof ReadableStream !== "undefined" && (request === null || request === void 0 ? void 0 : request.body) instanceof ReadableStream); -exports.isStreamingPayload = isStreamingPayload; - - -/***/ }), - -/***/ 7761: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "NIL", ({ - enumerable: true, - get: function () { - return _nil.default; - } -})); -Object.defineProperty(exports, "parse", ({ - enumerable: true, - get: function () { - return _parse.default; - } -})); -Object.defineProperty(exports, "stringify", ({ - enumerable: true, - get: function () { - return _stringify.default; - } -})); -Object.defineProperty(exports, "v1", ({ - enumerable: true, - get: function () { - return _v.default; - } -})); -Object.defineProperty(exports, "v3", ({ - enumerable: true, - get: function () { - return _v2.default; - } -})); -Object.defineProperty(exports, "v4", ({ - enumerable: true, - get: function () { - return _v3.default; - } -})); -Object.defineProperty(exports, "v5", ({ - enumerable: true, - get: function () { - return _v4.default; - } -})); -Object.defineProperty(exports, "validate", ({ - enumerable: true, - get: function () { - return _validate.default; - } -})); -Object.defineProperty(exports, "version", ({ - enumerable: true, - get: function () { - return _version.default; - } -})); - -var _v = _interopRequireDefault(__nccwpck_require__(36310)); - -var _v2 = _interopRequireDefault(__nccwpck_require__(9465)); - -var _v3 = _interopRequireDefault(__nccwpck_require__(86001)); - -var _v4 = _interopRequireDefault(__nccwpck_require__(38310)); - -var _nil = _interopRequireDefault(__nccwpck_require__(3436)); - -var _version = _interopRequireDefault(__nccwpck_require__(17780)); - -var _validate = _interopRequireDefault(__nccwpck_require__(66992)); - -var _stringify = _interopRequireDefault(__nccwpck_require__(79618)); - -var _parse = _interopRequireDefault(__nccwpck_require__(40086)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/***/ }), - -/***/ 11380: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; - -var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function md5(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); - } - - return _crypto.default.createHash('md5').update(bytes).digest(); -} - -var _default = md5; -exports["default"] = _default; - -/***/ }), - -/***/ 34672: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; - -var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var _default = { - randomUUID: _crypto.default.randomUUID -}; -exports["default"] = _default; - -/***/ }), - -/***/ 3436: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = '00000000-0000-0000-0000-000000000000'; -exports["default"] = _default; - -/***/ }), - -/***/ 40086: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; - -var _validate = _interopRequireDefault(__nccwpck_require__(66992)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function parse(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); - } - - let v; - const arr = new Uint8Array(16); // Parse ########-....-....-....-............ - - arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; - arr[1] = v >>> 16 & 0xff; - arr[2] = v >>> 8 & 0xff; - arr[3] = v & 0xff; // Parse ........-####-....-....-............ - - arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; - arr[5] = v & 0xff; // Parse ........-....-####-....-............ - - arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; - arr[7] = v & 0xff; // Parse ........-....-....-####-............ - - arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; - arr[9] = v & 0xff; // Parse ........-....-....-....-############ - // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) - - arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; - arr[11] = v / 0x100000000 & 0xff; - arr[12] = v >>> 24 & 0xff; - arr[13] = v >>> 16 & 0xff; - arr[14] = v >>> 8 & 0xff; - arr[15] = v & 0xff; - return arr; -} - -var _default = parse; -exports["default"] = _default; - -/***/ }), - -/***/ 3194: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; -exports["default"] = _default; - -/***/ }), - -/***/ 68136: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = rng; - -var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate +}, "getChecksumConfiguration"); +var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; +}, "resolveChecksumRuntimeConfig"); -let poolPtr = rnds8Pool.length; +// src/extensions/defaultClientConfiguration.ts +var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); +}, "getDefaultClientConfiguration"); +var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { + return resolveChecksumRuntimeConfig(config); +}, "resolveDefaultRuntimeConfig"); -function rng() { - if (poolPtr > rnds8Pool.length - 16) { - _crypto.default.randomFillSync(rnds8Pool); +// src/http.ts +var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { + FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; + FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; + return FieldPosition2; +})(FieldPosition || {}); - poolPtr = 0; - } +// src/middleware.ts +var SMITHY_CONTEXT_KEY = "__smithy_context"; - return rnds8Pool.slice(poolPtr, poolPtr += 16); -} +// src/profile.ts +var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { + IniSectionType2["PROFILE"] = "profile"; + IniSectionType2["SSO_SESSION"] = "sso-session"; + IniSectionType2["SERVICES"] = "services"; + return IniSectionType2; +})(IniSectionType || {}); -/***/ }), +// src/transfer.ts +var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { + RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; + return RequestHandlerProtocol2; +})(RequestHandlerProtocol || {}); +// Annotate the CommonJS export names for ESM import in node: -/***/ 46679: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +0 && (0); -"use strict"; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; +/***/ }), -var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); +/***/ 14681: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +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); -function sha1(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); +// src/index.ts +var src_exports = {}; +__export(src_exports, { + parseUrl: () => parseUrl +}); +module.exports = __toCommonJS(src_exports); +var import_querystring_parser = __nccwpck_require__(4769); +var parseUrl = /* @__PURE__ */ __name((url) => { + if (typeof url === "string") { + return parseUrl(new URL(url)); + } + const { hostname, pathname, port, protocol, search } = url; + let query; + if (search) { + query = (0, import_querystring_parser.parseQueryString)(search); } + return { + hostname, + port: port ? parseInt(port) : void 0, + protocol, + path: pathname, + query + }; +}, "parseUrl"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); - return _crypto.default.createHash('sha1').update(bytes).digest(); -} -var _default = sha1; -exports["default"] = _default; /***/ }), -/***/ 79618: +/***/ 30305: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fromBase64 = void 0; +const util_buffer_from_1 = __nccwpck_require__(31381); +const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; +const fromBase64 = (input) => { + if ((input.length * 3) % 4 !== 0) { + throw new TypeError(`Incorrect padding on base64 string.`); + } + if (!BASE64_REGEX.exec(input)) { + throw new TypeError(`Invalid base64 string.`); + } + const buffer = (0, util_buffer_from_1.fromString)(input, "base64"); + return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); +}; +exports.fromBase64 = fromBase64; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -exports.unsafeStringify = unsafeStringify; - -var _validate = _interopRequireDefault(__nccwpck_require__(66992)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - */ -const byteToHex = []; +/***/ }), -for (let i = 0; i < 256; ++i) { - byteToHex.push((i + 0x100).toString(16).slice(1)); -} +/***/ 75600: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function unsafeStringify(arr, offset = 0) { - // Note: Be careful editing this code! It's been tuned for performance - // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 - return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]; -} +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +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 __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -function stringify(arr, offset = 0) { - const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one - // of the following: - // - One or more input array values don't map to a hex octet (leading to - // "undefined" in the uuid) - // - Invalid input values for the RFC `version` or `variant` fields +// src/index.ts +var src_exports = {}; +module.exports = __toCommonJS(src_exports); +__reExport(src_exports, __nccwpck_require__(30305), module.exports); +__reExport(src_exports, __nccwpck_require__(74730), module.exports); +// Annotate the CommonJS export names for ESM import in node: - if (!(0, _validate.default)(uuid)) { - throw TypeError('Stringified UUID is invalid'); - } +0 && (0); - return uuid; -} -var _default = stringify; -exports["default"] = _default; /***/ }), -/***/ 36310: +/***/ 74730: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.toBase64 = void 0; +const util_buffer_from_1 = __nccwpck_require__(31381); +const util_utf8_1 = __nccwpck_require__(41895); +const toBase64 = (_input) => { + let input; + if (typeof _input === "string") { + input = (0, util_utf8_1.fromUtf8)(_input); + } + else { + input = _input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); + } + return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); +}; +exports.toBase64 = toBase64; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; - -var _rng = _interopRequireDefault(__nccwpck_require__(68136)); - -var _stringify = __nccwpck_require__(79618); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/***/ }), -// **`v1()` - Generate time-based UUID** -// -// Inspired by https://github.com/LiosK/UUID.js -// and http://docs.python.org/library/uuid.html -let _nodeId; +/***/ 68075: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -let _clockseq; // Previous uuid creation time +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +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); +// src/index.ts +var src_exports = {}; +__export(src_exports, { + calculateBodyLength: () => calculateBodyLength +}); +module.exports = __toCommonJS(src_exports); -let _lastMSecs = 0; -let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details +// src/calculateBodyLength.ts +var import_fs = __nccwpck_require__(57147); +var calculateBodyLength = /* @__PURE__ */ __name((body) => { + if (!body) { + return 0; + } + if (typeof body === "string") { + return Buffer.byteLength(body); + } else if (typeof body.byteLength === "number") { + return body.byteLength; + } else if (typeof body.size === "number") { + return body.size; + } else if (typeof body.start === "number" && typeof body.end === "number") { + return body.end + 1 - body.start; + } else if (typeof body.path === "string" || Buffer.isBuffer(body.path)) { + return (0, import_fs.lstatSync)(body.path).size; + } else if (typeof body.fd === "number") { + return (0, import_fs.fstatSync)(body.fd).size; + } + throw new Error(`Body Length computation failed for ${body}`); +}, "calculateBodyLength"); +// Annotate the CommonJS export names for ESM import in node: -function v1(options, buf, offset) { - let i = buf && offset || 0; - const b = buf || new Array(16); - options = options || {}; - let node = options.node || _nodeId; - let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not - // specified. We do this lazily to minimize issues related to insufficient - // system entropy. See #189 +0 && (0); - if (node == null || clockseq == null) { - const seedBytes = options.random || (options.rng || _rng.default)(); - if (node == null) { - // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) - node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; - } - if (clockseq == null) { - // Per 4.2.2, randomize (14 bit) clockseq - clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; - } - } // UUID timestamps are 100 nano-second units since the Gregorian epoch, - // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so - // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' - // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. +/***/ }), +/***/ 31381: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock - // cycle to simulate higher resolution clock +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +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); - let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) +// src/index.ts +var src_exports = {}; +__export(src_exports, { + fromArrayBuffer: () => fromArrayBuffer, + fromString: () => fromString +}); +module.exports = __toCommonJS(src_exports); +var import_is_array_buffer = __nccwpck_require__(10780); +var import_buffer = __nccwpck_require__(14300); +var fromArrayBuffer = /* @__PURE__ */ __name((input, offset = 0, length = input.byteLength - offset) => { + if (!(0, import_is_array_buffer.isArrayBuffer)(input)) { + throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); + } + return import_buffer.Buffer.from(input, offset, length); +}, "fromArrayBuffer"); +var fromString = /* @__PURE__ */ __name((input, encoding) => { + if (typeof input !== "string") { + throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); + } + return encoding ? import_buffer.Buffer.from(input, encoding) : import_buffer.Buffer.from(input); +}, "fromString"); +// Annotate the CommonJS export names for ESM import in node: - const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression +0 && (0); - if (dt < 0 && options.clockseq === undefined) { - clockseq = clockseq + 1 & 0x3fff; - } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new - // time interval - if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { - nsecs = 0; - } // Per 4.2.1.2 Throw error if too many uuids are requested +/***/ }), +/***/ 83375: +/***/ ((module) => { - if (nsecs >= 10000) { - throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +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); - _lastMSecs = msecs; - _lastNSecs = nsecs; - _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - - msecs += 12219292800000; // `time_low` - - const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; - b[i++] = tl >>> 24 & 0xff; - b[i++] = tl >>> 16 & 0xff; - b[i++] = tl >>> 8 & 0xff; - b[i++] = tl & 0xff; // `time_mid` +// src/index.ts +var src_exports = {}; +__export(src_exports, { + SelectorType: () => SelectorType, + booleanSelector: () => booleanSelector, + numberSelector: () => numberSelector +}); +module.exports = __toCommonJS(src_exports); - const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; - b[i++] = tmh >>> 8 & 0xff; - b[i++] = tmh & 0xff; // `time_high_and_version` +// src/booleanSelector.ts +var booleanSelector = /* @__PURE__ */ __name((obj, key, type) => { + if (!(key in obj)) + return void 0; + if (obj[key] === "true") + return true; + if (obj[key] === "false") + return false; + throw new Error(`Cannot load ${type} "${key}". Expected "true" or "false", got ${obj[key]}.`); +}, "booleanSelector"); - b[i++] = tmh >>> 24 & 0xf | 0x10; // include version +// src/numberSelector.ts +var numberSelector = /* @__PURE__ */ __name((obj, key, type) => { + if (!(key in obj)) + return void 0; + const numberValue = parseInt(obj[key], 10); + if (Number.isNaN(numberValue)) { + throw new TypeError(`Cannot load ${type} '${key}'. Expected number, got '${obj[key]}'.`); + } + return numberValue; +}, "numberSelector"); - b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) +// src/types.ts +var SelectorType = /* @__PURE__ */ ((SelectorType2) => { + SelectorType2["ENV"] = "env"; + SelectorType2["CONFIG"] = "shared config entry"; + return SelectorType2; +})(SelectorType || {}); +// Annotate the CommonJS export names for ESM import in node: - b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` +0 && (0); - b[i++] = clockseq & 0xff; // `node` - for (let n = 0; n < 6; ++n) { - b[i + n] = node[n]; - } - return buf || (0, _stringify.unsafeStringify)(b); -} +/***/ }), -var _default = v1; -exports["default"] = _default; +/***/ 72429: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/***/ }), +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 __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +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); -/***/ 9465: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// src/index.ts +var src_exports = {}; +__export(src_exports, { + resolveDefaultsModeConfig: () => resolveDefaultsModeConfig +}); +module.exports = __toCommonJS(src_exports); -"use strict"; +// src/resolveDefaultsModeConfig.ts +var import_config_resolver = __nccwpck_require__(53098); +var import_node_config_provider = __nccwpck_require__(33461); +var import_property_provider = __nccwpck_require__(79721); +// src/constants.ts +var AWS_EXECUTION_ENV = "AWS_EXECUTION_ENV"; +var AWS_REGION_ENV = "AWS_REGION"; +var AWS_DEFAULT_REGION_ENV = "AWS_DEFAULT_REGION"; +var ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED"; +var DEFAULTS_MODE_OPTIONS = ["in-region", "cross-region", "mobile", "standard", "legacy"]; +var IMDS_REGION_PATH = "/latest/meta-data/placement/region"; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; +// src/defaultsModeConfig.ts +var AWS_DEFAULTS_MODE_ENV = "AWS_DEFAULTS_MODE"; +var AWS_DEFAULTS_MODE_CONFIG = "defaults_mode"; +var NODE_DEFAULTS_MODE_CONFIG_OPTIONS = { + environmentVariableSelector: (env) => { + return env[AWS_DEFAULTS_MODE_ENV]; + }, + configFileSelector: (profile) => { + return profile[AWS_DEFAULTS_MODE_CONFIG]; + }, + default: "legacy" +}; -var _v = _interopRequireDefault(__nccwpck_require__(2568)); +// src/resolveDefaultsModeConfig.ts +var resolveDefaultsModeConfig = /* @__PURE__ */ __name(({ + region = (0, import_node_config_provider.loadConfig)(import_config_resolver.NODE_REGION_CONFIG_OPTIONS), + defaultsMode = (0, import_node_config_provider.loadConfig)(NODE_DEFAULTS_MODE_CONFIG_OPTIONS) +} = {}) => (0, import_property_provider.memoize)(async () => { + const mode = typeof defaultsMode === "function" ? await defaultsMode() : defaultsMode; + switch (mode?.toLowerCase()) { + case "auto": + return resolveNodeDefaultsModeAuto(region); + case "in-region": + case "cross-region": + case "mobile": + case "standard": + case "legacy": + return Promise.resolve(mode?.toLocaleLowerCase()); + case void 0: + return Promise.resolve("legacy"); + default: + throw new Error( + `Invalid parameter for "defaultsMode", expect ${DEFAULTS_MODE_OPTIONS.join(", ")}, got ${mode}` + ); + } +}), "resolveDefaultsModeConfig"); +var resolveNodeDefaultsModeAuto = /* @__PURE__ */ __name(async (clientRegion) => { + if (clientRegion) { + const resolvedRegion = typeof clientRegion === "function" ? await clientRegion() : clientRegion; + const inferredRegion = await inferPhysicalRegion(); + if (!inferredRegion) { + return "standard"; + } + if (resolvedRegion === inferredRegion) { + return "in-region"; + } else { + return "cross-region"; + } + } + return "standard"; +}, "resolveNodeDefaultsModeAuto"); +var inferPhysicalRegion = /* @__PURE__ */ __name(async () => { + if (process.env[AWS_EXECUTION_ENV] && (process.env[AWS_REGION_ENV] || process.env[AWS_DEFAULT_REGION_ENV])) { + return process.env[AWS_REGION_ENV] ?? process.env[AWS_DEFAULT_REGION_ENV]; + } + if (!process.env[ENV_IMDS_DISABLED]) { + try { + const { getInstanceMetadataEndpoint, httpRequest } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(7477))); + const endpoint = await getInstanceMetadataEndpoint(); + return (await httpRequest({ ...endpoint, path: IMDS_REGION_PATH })).toString(); + } catch (e) { + } + } +}, "inferPhysicalRegion"); +// Annotate the CommonJS export names for ESM import in node: -var _md = _interopRequireDefault(__nccwpck_require__(11380)); +0 && (0); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -const v3 = (0, _v.default)('v3', 0x30, _md.default); -var _default = v3; -exports["default"] = _default; /***/ }), -/***/ 2568: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; +/***/ 45473: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +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); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.URL = exports.DNS = void 0; -exports["default"] = v35; +// src/index.ts +var src_exports = {}; +__export(src_exports, { + EndpointCache: () => EndpointCache, + EndpointError: () => EndpointError, + customEndpointFunctions: () => customEndpointFunctions, + isIpAddress: () => isIpAddress, + isValidHostLabel: () => isValidHostLabel, + resolveEndpoint: () => resolveEndpoint +}); +module.exports = __toCommonJS(src_exports); -var _stringify = __nccwpck_require__(79618); +// src/cache/EndpointCache.ts +var EndpointCache = class { + /** + * @param [size] - desired average maximum capacity. A buffer of 10 additional keys will be allowed + * before keys are dropped. + * @param [params] - list of params to consider as part of the cache key. + * + * If the params list is not populated, no caching will happen. + * This may be out of order depending on how the object is created and arrives to this class. + */ + constructor({ size, params }) { + this.data = /* @__PURE__ */ new Map(); + this.parameters = []; + this.capacity = size ?? 50; + if (params) { + this.parameters = params; + } + } + static { + __name(this, "EndpointCache"); + } + /** + * @param endpointParams - query for endpoint. + * @param resolver - provider of the value if not present. + * @returns endpoint corresponding to the query. + */ + get(endpointParams, resolver) { + const key = this.hash(endpointParams); + if (key === false) { + return resolver(); + } + if (!this.data.has(key)) { + if (this.data.size > this.capacity + 10) { + const keys = this.data.keys(); + let i = 0; + while (true) { + const { value, done } = keys.next(); + this.data.delete(value); + if (done || ++i > 10) { + break; + } + } + } + this.data.set(key, resolver()); + } + return this.data.get(key); + } + size() { + return this.data.size; + } + /** + * @returns cache key or false if not cachable. + */ + hash(endpointParams) { + let buffer = ""; + const { parameters } = this; + if (parameters.length === 0) { + return false; + } + for (const param of parameters) { + const val = String(endpointParams[param] ?? ""); + if (val.includes("|;")) { + return false; + } + buffer += val + "|;"; + } + return buffer; + } +}; -var _parse = _interopRequireDefault(__nccwpck_require__(40086)); +// src/lib/isIpAddress.ts +var IP_V4_REGEX = new RegExp( + `^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$` +); +var isIpAddress = /* @__PURE__ */ __name((value) => IP_V4_REGEX.test(value) || value.startsWith("[") && value.endsWith("]"), "isIpAddress"); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +// src/lib/isValidHostLabel.ts +var VALID_HOST_LABEL_REGEX = new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`); +var isValidHostLabel = /* @__PURE__ */ __name((value, allowSubDomains = false) => { + if (!allowSubDomains) { + return VALID_HOST_LABEL_REGEX.test(value); + } + const labels = value.split("."); + for (const label of labels) { + if (!isValidHostLabel(label)) { + return false; + } + } + return true; +}, "isValidHostLabel"); -function stringToBytes(str) { - str = unescape(encodeURIComponent(str)); // UTF8 escape +// src/utils/customEndpointFunctions.ts +var customEndpointFunctions = {}; - const bytes = []; +// src/debug/debugId.ts +var debugId = "endpoints"; - for (let i = 0; i < str.length; ++i) { - bytes.push(str.charCodeAt(i)); +// src/debug/toDebugString.ts +function toDebugString(input) { + if (typeof input !== "object" || input == null) { + return input; } - - return bytes; + if ("ref" in input) { + return `$${toDebugString(input.ref)}`; + } + if ("fn" in input) { + return `${input.fn}(${(input.argv || []).map(toDebugString).join(", ")})`; + } + return JSON.stringify(input, null, 2); } +__name(toDebugString, "toDebugString"); -const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; -exports.DNS = DNS; -const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; -exports.URL = URL; - -function v35(name, version, hashfunc) { - function generateUUID(value, namespace, buf, offset) { - var _namespace; +// src/types/EndpointError.ts +var EndpointError = class extends Error { + static { + __name(this, "EndpointError"); + } + constructor(message) { + super(message); + this.name = "EndpointError"; + } +}; - if (typeof value === 'string') { - value = stringToBytes(value); - } +// src/lib/booleanEquals.ts +var booleanEquals = /* @__PURE__ */ __name((value1, value2) => value1 === value2, "booleanEquals"); - if (typeof namespace === 'string') { - namespace = (0, _parse.default)(namespace); +// src/lib/getAttrPathList.ts +var getAttrPathList = /* @__PURE__ */ __name((path) => { + const parts = path.split("."); + const pathList = []; + for (const part of parts) { + const squareBracketIndex = part.indexOf("["); + if (squareBracketIndex !== -1) { + if (part.indexOf("]") !== part.length - 1) { + throw new EndpointError(`Path: '${path}' does not end with ']'`); + } + const arrayIndex = part.slice(squareBracketIndex + 1, -1); + if (Number.isNaN(parseInt(arrayIndex))) { + throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path}'`); + } + if (squareBracketIndex !== 0) { + pathList.push(part.slice(0, squareBracketIndex)); + } + pathList.push(arrayIndex); + } else { + pathList.push(part); } + } + return pathList; +}, "getAttrPathList"); - if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) { - throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); - } // Compute hash of namespace and value, Per 4.3 - // Future: Use spread syntax when supported on all platforms, e.g. `bytes = - // hashfunc([...namespace, ... value])` - +// src/lib/getAttr.ts +var getAttr = /* @__PURE__ */ __name((value, path) => getAttrPathList(path).reduce((acc, index) => { + if (typeof acc !== "object") { + throw new EndpointError(`Index '${index}' in '${path}' not found in '${JSON.stringify(value)}'`); + } else if (Array.isArray(acc)) { + return acc[parseInt(index)]; + } + return acc[index]; +}, value), "getAttr"); - let bytes = new Uint8Array(16 + value.length); - bytes.set(namespace); - bytes.set(value, namespace.length); - bytes = hashfunc(bytes); - bytes[6] = bytes[6] & 0x0f | version; - bytes[8] = bytes[8] & 0x3f | 0x80; +// src/lib/isSet.ts +var isSet = /* @__PURE__ */ __name((value) => value != null, "isSet"); - if (buf) { - offset = offset || 0; +// src/lib/not.ts +var not = /* @__PURE__ */ __name((value) => !value, "not"); - for (let i = 0; i < 16; ++i) { - buf[offset + i] = bytes[i]; +// src/lib/parseURL.ts +var import_types3 = __nccwpck_require__(55756); +var DEFAULT_PORTS = { + [import_types3.EndpointURLScheme.HTTP]: 80, + [import_types3.EndpointURLScheme.HTTPS]: 443 +}; +var parseURL = /* @__PURE__ */ __name((value) => { + const whatwgURL = (() => { + try { + if (value instanceof URL) { + return value; } - - return buf; + if (typeof value === "object" && "hostname" in value) { + const { hostname: hostname2, port, protocol: protocol2 = "", path = "", query = {} } = value; + const url = new URL(`${protocol2}//${hostname2}${port ? `:${port}` : ""}${path}`); + url.search = Object.entries(query).map(([k, v]) => `${k}=${v}`).join("&"); + return url; + } + return new URL(value); + } catch (error) { + return null; } + })(); + if (!whatwgURL) { + console.error(`Unable to parse ${JSON.stringify(value)} as a whatwg URL.`); + return null; + } + const urlString = whatwgURL.href; + const { host, hostname, pathname, protocol, search } = whatwgURL; + if (search) { + return null; + } + const scheme = protocol.slice(0, -1); + if (!Object.values(import_types3.EndpointURLScheme).includes(scheme)) { + return null; + } + const isIp = isIpAddress(hostname); + const inputContainsDefaultPort = urlString.includes(`${host}:${DEFAULT_PORTS[scheme]}`) || typeof value === "string" && value.includes(`${host}:${DEFAULT_PORTS[scheme]}`); + const authority = `${host}${inputContainsDefaultPort ? `:${DEFAULT_PORTS[scheme]}` : ``}`; + return { + scheme, + authority, + path: pathname, + normalizedPath: pathname.endsWith("/") ? pathname : `${pathname}/`, + isIp + }; +}, "parseURL"); - return (0, _stringify.unsafeStringify)(bytes); - } // Function#name is not settable on some platforms (#270) - - - try { - generateUUID.name = name; // eslint-disable-next-line no-empty - } catch (err) {} // For CommonJS default export support - - - generateUUID.DNS = DNS; - generateUUID.URL = URL; - return generateUUID; -} - -/***/ }), - -/***/ 86001: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; +// src/lib/stringEquals.ts +var stringEquals = /* @__PURE__ */ __name((value1, value2) => value1 === value2, "stringEquals"); +// src/lib/substring.ts +var substring = /* @__PURE__ */ __name((input, start, stop, reverse) => { + if (start >= stop || input.length < stop) { + return null; + } + if (!reverse) { + return input.substring(start, stop); + } + return input.substring(input.length - stop, input.length - start); +}, "substring"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; +// src/lib/uriEncode.ts +var uriEncode = /* @__PURE__ */ __name((value) => encodeURIComponent(value).replace(/[!*'()]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`), "uriEncode"); -var _native = _interopRequireDefault(__nccwpck_require__(34672)); +// src/utils/endpointFunctions.ts +var endpointFunctions = { + booleanEquals, + getAttr, + isSet, + isValidHostLabel, + not, + parseURL, + stringEquals, + substring, + uriEncode +}; -var _rng = _interopRequireDefault(__nccwpck_require__(68136)); +// src/utils/evaluateTemplate.ts +var evaluateTemplate = /* @__PURE__ */ __name((template, options) => { + const evaluatedTemplateArr = []; + const templateContext = { + ...options.endpointParams, + ...options.referenceRecord + }; + let currentIndex = 0; + while (currentIndex < template.length) { + const openingBraceIndex = template.indexOf("{", currentIndex); + if (openingBraceIndex === -1) { + evaluatedTemplateArr.push(template.slice(currentIndex)); + break; + } + evaluatedTemplateArr.push(template.slice(currentIndex, openingBraceIndex)); + const closingBraceIndex = template.indexOf("}", openingBraceIndex); + if (closingBraceIndex === -1) { + evaluatedTemplateArr.push(template.slice(openingBraceIndex)); + break; + } + if (template[openingBraceIndex + 1] === "{" && template[closingBraceIndex + 1] === "}") { + evaluatedTemplateArr.push(template.slice(openingBraceIndex + 1, closingBraceIndex)); + currentIndex = closingBraceIndex + 2; + } + const parameterName = template.substring(openingBraceIndex + 1, closingBraceIndex); + if (parameterName.includes("#")) { + const [refName, attrName] = parameterName.split("#"); + evaluatedTemplateArr.push(getAttr(templateContext[refName], attrName)); + } else { + evaluatedTemplateArr.push(templateContext[parameterName]); + } + currentIndex = closingBraceIndex + 1; + } + return evaluatedTemplateArr.join(""); +}, "evaluateTemplate"); -var _stringify = __nccwpck_require__(79618); +// src/utils/getReferenceValue.ts +var getReferenceValue = /* @__PURE__ */ __name(({ ref }, options) => { + const referenceRecord = { + ...options.endpointParams, + ...options.referenceRecord + }; + return referenceRecord[ref]; +}, "getReferenceValue"); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +// src/utils/evaluateExpression.ts +var evaluateExpression = /* @__PURE__ */ __name((obj, keyName, options) => { + if (typeof obj === "string") { + return evaluateTemplate(obj, options); + } else if (obj["fn"]) { + return callFunction(obj, options); + } else if (obj["ref"]) { + return getReferenceValue(obj, options); + } + throw new EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`); +}, "evaluateExpression"); -function v4(options, buf, offset) { - if (_native.default.randomUUID && !buf && !options) { - return _native.default.randomUUID(); +// src/utils/callFunction.ts +var callFunction = /* @__PURE__ */ __name(({ fn, argv }, options) => { + const evaluatedArgs = argv.map( + (arg) => ["boolean", "number"].includes(typeof arg) ? arg : evaluateExpression(arg, "arg", options) + ); + const fnSegments = fn.split("."); + if (fnSegments[0] in customEndpointFunctions && fnSegments[1] != null) { + return customEndpointFunctions[fnSegments[0]][fnSegments[1]](...evaluatedArgs); } + return endpointFunctions[fn](...evaluatedArgs); +}, "callFunction"); - options = options || {}; +// src/utils/evaluateCondition.ts +var evaluateCondition = /* @__PURE__ */ __name(({ assign, ...fnArgs }, options) => { + if (assign && assign in options.referenceRecord) { + throw new EndpointError(`'${assign}' is already defined in Reference Record.`); + } + const value = callFunction(fnArgs, options); + options.logger?.debug?.(`${debugId} evaluateCondition: ${toDebugString(fnArgs)} = ${toDebugString(value)}`); + return { + result: value === "" ? true : !!value, + ...assign != null && { toAssign: { name: assign, value } } + }; +}, "evaluateCondition"); - const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` +// src/utils/evaluateConditions.ts +var evaluateConditions = /* @__PURE__ */ __name((conditions = [], options) => { + const conditionsReferenceRecord = {}; + for (const condition of conditions) { + const { result, toAssign } = evaluateCondition(condition, { + ...options, + referenceRecord: { + ...options.referenceRecord, + ...conditionsReferenceRecord + } + }); + if (!result) { + return { result }; + } + if (toAssign) { + conditionsReferenceRecord[toAssign.name] = toAssign.value; + options.logger?.debug?.(`${debugId} assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`); + } + } + return { result: true, referenceRecord: conditionsReferenceRecord }; +}, "evaluateConditions"); +// src/utils/getEndpointHeaders.ts +var getEndpointHeaders = /* @__PURE__ */ __name((headers, options) => Object.entries(headers).reduce( + (acc, [headerKey, headerVal]) => ({ + ...acc, + [headerKey]: headerVal.map((headerValEntry) => { + const processedExpr = evaluateExpression(headerValEntry, "Header value entry", options); + if (typeof processedExpr !== "string") { + throw new EndpointError(`Header '${headerKey}' value '${processedExpr}' is not a string`); + } + return processedExpr; + }) + }), + {} +), "getEndpointHeaders"); - rnds[6] = rnds[6] & 0x0f | 0x40; - rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided +// src/utils/getEndpointProperty.ts +var getEndpointProperty = /* @__PURE__ */ __name((property, options) => { + if (Array.isArray(property)) { + return property.map((propertyEntry) => getEndpointProperty(propertyEntry, options)); + } + switch (typeof property) { + case "string": + return evaluateTemplate(property, options); + case "object": + if (property === null) { + throw new EndpointError(`Unexpected endpoint property: ${property}`); + } + return getEndpointProperties(property, options); + case "boolean": + return property; + default: + throw new EndpointError(`Unexpected endpoint property type: ${typeof property}`); + } +}, "getEndpointProperty"); - if (buf) { - offset = offset || 0; +// src/utils/getEndpointProperties.ts +var getEndpointProperties = /* @__PURE__ */ __name((properties, options) => Object.entries(properties).reduce( + (acc, [propertyKey, propertyVal]) => ({ + ...acc, + [propertyKey]: getEndpointProperty(propertyVal, options) + }), + {} +), "getEndpointProperties"); - for (let i = 0; i < 16; ++i) { - buf[offset + i] = rnds[i]; +// src/utils/getEndpointUrl.ts +var getEndpointUrl = /* @__PURE__ */ __name((endpointUrl, options) => { + const expression = evaluateExpression(endpointUrl, "Endpoint URL", options); + if (typeof expression === "string") { + try { + return new URL(expression); + } catch (error) { + console.error(`Failed to construct URL with ${expression}`, error); + throw error; } - - return buf; } + throw new EndpointError(`Endpoint URL must be a string, got ${typeof expression}`); +}, "getEndpointUrl"); - return (0, _stringify.unsafeStringify)(rnds); -} - -var _default = v4; -exports["default"] = _default; - -/***/ }), - -/***/ 38310: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// src/utils/evaluateEndpointRule.ts +var evaluateEndpointRule = /* @__PURE__ */ __name((endpointRule, options) => { + const { conditions, endpoint } = endpointRule; + const { result, referenceRecord } = evaluateConditions(conditions, options); + if (!result) { + return; + } + const endpointRuleOptions = { + ...options, + referenceRecord: { ...options.referenceRecord, ...referenceRecord } + }; + const { url, properties, headers } = endpoint; + options.logger?.debug?.(`${debugId} Resolving endpoint from template: ${toDebugString(endpoint)}`); + return { + ...headers != void 0 && { + headers: getEndpointHeaders(headers, endpointRuleOptions) + }, + ...properties != void 0 && { + properties: getEndpointProperties(properties, endpointRuleOptions) + }, + url: getEndpointUrl(url, endpointRuleOptions) + }; +}, "evaluateEndpointRule"); -"use strict"; +// src/utils/evaluateErrorRule.ts +var evaluateErrorRule = /* @__PURE__ */ __name((errorRule, options) => { + const { conditions, error } = errorRule; + const { result, referenceRecord } = evaluateConditions(conditions, options); + if (!result) { + return; + } + throw new EndpointError( + evaluateExpression(error, "Error", { + ...options, + referenceRecord: { ...options.referenceRecord, ...referenceRecord } + }) + ); +}, "evaluateErrorRule"); +// src/utils/evaluateTreeRule.ts +var evaluateTreeRule = /* @__PURE__ */ __name((treeRule, options) => { + const { conditions, rules } = treeRule; + const { result, referenceRecord } = evaluateConditions(conditions, options); + if (!result) { + return; + } + return evaluateRules(rules, { + ...options, + referenceRecord: { ...options.referenceRecord, ...referenceRecord } + }); +}, "evaluateTreeRule"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; +// src/utils/evaluateRules.ts +var evaluateRules = /* @__PURE__ */ __name((rules, options) => { + for (const rule of rules) { + if (rule.type === "endpoint") { + const endpointOrUndefined = evaluateEndpointRule(rule, options); + if (endpointOrUndefined) { + return endpointOrUndefined; + } + } else if (rule.type === "error") { + evaluateErrorRule(rule, options); + } else if (rule.type === "tree") { + const endpointOrUndefined = evaluateTreeRule(rule, options); + if (endpointOrUndefined) { + return endpointOrUndefined; + } + } else { + throw new EndpointError(`Unknown endpoint rule: ${rule}`); + } + } + throw new EndpointError(`Rules evaluation failed`); +}, "evaluateRules"); -var _v = _interopRequireDefault(__nccwpck_require__(2568)); +// src/resolveEndpoint.ts +var resolveEndpoint = /* @__PURE__ */ __name((ruleSetObject, options) => { + const { endpointParams, logger } = options; + const { parameters, rules } = ruleSetObject; + options.logger?.debug?.(`${debugId} Initial EndpointParams: ${toDebugString(endpointParams)}`); + const paramsWithDefault = Object.entries(parameters).filter(([, v]) => v.default != null).map(([k, v]) => [k, v.default]); + if (paramsWithDefault.length > 0) { + for (const [paramKey, paramDefaultValue] of paramsWithDefault) { + endpointParams[paramKey] = endpointParams[paramKey] ?? paramDefaultValue; + } + } + const requiredParams = Object.entries(parameters).filter(([, v]) => v.required).map(([k]) => k); + for (const requiredParam of requiredParams) { + if (endpointParams[requiredParam] == null) { + throw new EndpointError(`Missing required parameter: '${requiredParam}'`); + } + } + const endpoint = evaluateRules(rules, { endpointParams, logger, referenceRecord: {} }); + options.logger?.debug?.(`${debugId} Resolved endpoint: ${toDebugString(endpoint)}`); + return endpoint; +}, "resolveEndpoint"); +// Annotate the CommonJS export names for ESM import in node: -var _sha = _interopRequireDefault(__nccwpck_require__(46679)); +0 && (0); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -const v5 = (0, _v.default)('v5', 0x50, _sha.default); -var _default = v5; -exports["default"] = _default; /***/ }), -/***/ 66992: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; - -var _regex = _interopRequireDefault(__nccwpck_require__(3194)); +/***/ 45364: +/***/ ((module) => { -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +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); -function validate(uuid) { - return typeof uuid === 'string' && _regex.default.test(uuid); +// src/index.ts +var src_exports = {}; +__export(src_exports, { + fromHex: () => fromHex, + toHex: () => toHex +}); +module.exports = __toCommonJS(src_exports); +var SHORT_TO_HEX = {}; +var HEX_TO_SHORT = {}; +for (let i = 0; i < 256; i++) { + let encodedByte = i.toString(16).toLowerCase(); + if (encodedByte.length === 1) { + encodedByte = `0${encodedByte}`; + } + SHORT_TO_HEX[i] = encodedByte; + HEX_TO_SHORT[encodedByte] = i; } - -var _default = validate; -exports["default"] = _default; - -/***/ }), - -/***/ 17780: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; - -var _validate = _interopRequireDefault(__nccwpck_require__(66992)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function version(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); +function fromHex(encoded) { + if (encoded.length % 2 !== 0) { + throw new Error("Hex encoded strings must have an even number length"); } - - return parseInt(uuid.slice(14, 15), 16); + const out = new Uint8Array(encoded.length / 2); + for (let i = 0; i < encoded.length; i += 2) { + const encodedByte = encoded.slice(i, i + 2).toLowerCase(); + if (encodedByte in HEX_TO_SHORT) { + out[i / 2] = HEX_TO_SHORT[encodedByte]; + } else { + throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); + } + } + return out; +} +__name(fromHex, "fromHex"); +function toHex(bytes) { + let out = ""; + for (let i = 0; i < bytes.byteLength; i++) { + out += SHORT_TO_HEX[bytes[i]]; + } + return out; } +__name(toHex, "toHex"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + -var _default = version; -exports["default"] = _default; /***/ }), -/***/ 81238: -/***/ ((module) => { +/***/ 2390: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; @@ -243165,83 +240421,22 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var src_exports = {}; __export(src_exports, { - deserializerMiddleware: () => deserializerMiddleware, - deserializerMiddlewareOption: () => deserializerMiddlewareOption, - getSerdePlugin: () => getSerdePlugin, - serializerMiddleware: () => serializerMiddleware, - serializerMiddlewareOption: () => serializerMiddlewareOption + getSmithyContext: () => getSmithyContext, + normalizeProvider: () => normalizeProvider }); module.exports = __toCommonJS(src_exports); -// src/deserializerMiddleware.ts -var deserializerMiddleware = /* @__PURE__ */ __name((options, deserializer) => (next, context) => async (args) => { - const { response } = await next(args); - try { - const parsed = await deserializer(response, options); - return { - response, - output: parsed - }; - } catch (error) { - Object.defineProperty(error, "$response", { - value: response - }); - if (!("$metadata" in error)) { - const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; - try { - error.message += "\n " + hint; - } catch (e) { - if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { - console.warn(hint); - } else { - context.logger?.warn?.(hint); - } - } - if (typeof error.$responseBodyText !== "undefined") { - if (error.$response) { - error.$response.body = error.$responseBodyText; - } - } - } - throw error; - } -}, "deserializerMiddleware"); - -// src/serializerMiddleware.ts -var serializerMiddleware = /* @__PURE__ */ __name((options, serializer) => (next, context) => async (args) => { - const endpoint = context.endpointV2?.url && options.urlParser ? async () => options.urlParser(context.endpointV2.url) : options.endpoint; - if (!endpoint) { - throw new Error("No valid endpoint provider available."); - } - const request = await serializer(args.input, { ...options, endpoint }); - return next({ - ...args, - request - }); -}, "serializerMiddleware"); +// src/getSmithyContext.ts +var import_types = __nccwpck_require__(55756); +var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); -// src/serdePlugin.ts -var deserializerMiddlewareOption = { - name: "deserializerMiddleware", - step: "deserialize", - tags: ["DESERIALIZER"], - override: true -}; -var serializerMiddlewareOption = { - name: "serializerMiddleware", - step: "serialize", - tags: ["SERIALIZER"], - override: true -}; -function getSerdePlugin(config, serializer, deserializer) { - return { - applyToStack: (commandStack) => { - commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption); - commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption); - } - }; -} -__name(getSerdePlugin, "getSerdePlugin"); +// src/normalizeProvider.ts +var normalizeProvider = /* @__PURE__ */ __name((input) => { + if (typeof input === "function") + return input; + const promisified = Promise.resolve(input); + return () => promisified; +}, "normalizeProvider"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -243250,8 +240445,8 @@ __name(getSerdePlugin, "getSerdePlugin"); /***/ }), -/***/ 97911: -/***/ ((module) => { +/***/ 84902: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; @@ -243275,417 +240470,836 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var src_exports = {}; __export(src_exports, { - constructStack: () => constructStack + AdaptiveRetryStrategy: () => AdaptiveRetryStrategy, + ConfiguredRetryStrategy: () => ConfiguredRetryStrategy, + DEFAULT_MAX_ATTEMPTS: () => DEFAULT_MAX_ATTEMPTS, + DEFAULT_RETRY_DELAY_BASE: () => DEFAULT_RETRY_DELAY_BASE, + DEFAULT_RETRY_MODE: () => DEFAULT_RETRY_MODE, + DefaultRateLimiter: () => DefaultRateLimiter, + INITIAL_RETRY_TOKENS: () => INITIAL_RETRY_TOKENS, + INVOCATION_ID_HEADER: () => INVOCATION_ID_HEADER, + MAXIMUM_RETRY_DELAY: () => MAXIMUM_RETRY_DELAY, + NO_RETRY_INCREMENT: () => NO_RETRY_INCREMENT, + REQUEST_HEADER: () => REQUEST_HEADER, + RETRY_COST: () => RETRY_COST, + RETRY_MODES: () => RETRY_MODES, + StandardRetryStrategy: () => StandardRetryStrategy, + THROTTLING_RETRY_DELAY_BASE: () => THROTTLING_RETRY_DELAY_BASE, + TIMEOUT_RETRY_COST: () => TIMEOUT_RETRY_COST }); module.exports = __toCommonJS(src_exports); -// src/MiddlewareStack.ts -var getAllAliases = /* @__PURE__ */ __name((name, aliases) => { - const _aliases = []; - if (name) { - _aliases.push(name); +// src/config.ts +var RETRY_MODES = /* @__PURE__ */ ((RETRY_MODES2) => { + RETRY_MODES2["STANDARD"] = "standard"; + RETRY_MODES2["ADAPTIVE"] = "adaptive"; + return RETRY_MODES2; +})(RETRY_MODES || {}); +var DEFAULT_MAX_ATTEMPTS = 3; +var DEFAULT_RETRY_MODE = "standard" /* STANDARD */; + +// src/DefaultRateLimiter.ts +var import_service_error_classification = __nccwpck_require__(6375); +var DefaultRateLimiter = class _DefaultRateLimiter { + constructor(options) { + // Pre-set state variables + this.currentCapacity = 0; + this.enabled = false; + this.lastMaxRate = 0; + this.measuredTxRate = 0; + this.requestCount = 0; + this.lastTimestamp = 0; + this.timeWindow = 0; + this.beta = options?.beta ?? 0.7; + this.minCapacity = options?.minCapacity ?? 1; + this.minFillRate = options?.minFillRate ?? 0.5; + this.scaleConstant = options?.scaleConstant ?? 0.4; + this.smooth = options?.smooth ?? 0.8; + const currentTimeInSeconds = this.getCurrentTimeInSeconds(); + this.lastThrottleTime = currentTimeInSeconds; + this.lastTxRateBucket = Math.floor(this.getCurrentTimeInSeconds()); + this.fillRate = this.minFillRate; + this.maxCapacity = this.minCapacity; } - if (aliases) { - for (const alias of aliases) { - _aliases.push(alias); + static { + __name(this, "DefaultRateLimiter"); + } + static { + /** + * Only used in testing. + */ + this.setTimeoutFn = setTimeout; + } + getCurrentTimeInSeconds() { + return Date.now() / 1e3; + } + async getSendToken() { + return this.acquireTokenBucket(1); + } + async acquireTokenBucket(amount) { + if (!this.enabled) { + return; + } + this.refillTokenBucket(); + if (amount > this.currentCapacity) { + const delay = (amount - this.currentCapacity) / this.fillRate * 1e3; + await new Promise((resolve) => _DefaultRateLimiter.setTimeoutFn(resolve, delay)); } + this.currentCapacity = this.currentCapacity - amount; } - return _aliases; -}, "getAllAliases"); -var getMiddlewareNameWithAliases = /* @__PURE__ */ __name((name, aliases) => { - return `${name || "anonymous"}${aliases && aliases.length > 0 ? ` (a.k.a. ${aliases.join(",")})` : ""}`; -}, "getMiddlewareNameWithAliases"); -var constructStack = /* @__PURE__ */ __name(() => { - let absoluteEntries = []; - let relativeEntries = []; - let identifyOnResolve = false; - const entriesNameSet = /* @__PURE__ */ new Set(); - const sort = /* @__PURE__ */ __name((entries) => entries.sort( - (a, b) => stepWeights[b.step] - stepWeights[a.step] || priorityWeights[b.priority || "normal"] - priorityWeights[a.priority || "normal"] - ), "sort"); - const removeByName = /* @__PURE__ */ __name((toRemove) => { - let isRemoved = false; - const filterCb = /* @__PURE__ */ __name((entry) => { - const aliases = getAllAliases(entry.name, entry.aliases); - if (aliases.includes(toRemove)) { - isRemoved = true; - for (const alias of aliases) { - entriesNameSet.delete(alias); + refillTokenBucket() { + const timestamp = this.getCurrentTimeInSeconds(); + if (!this.lastTimestamp) { + this.lastTimestamp = timestamp; + return; + } + const fillAmount = (timestamp - this.lastTimestamp) * this.fillRate; + this.currentCapacity = Math.min(this.maxCapacity, this.currentCapacity + fillAmount); + this.lastTimestamp = timestamp; + } + updateClientSendingRate(response) { + let calculatedRate; + this.updateMeasuredRate(); + if ((0, import_service_error_classification.isThrottlingError)(response)) { + const rateToUse = !this.enabled ? this.measuredTxRate : Math.min(this.measuredTxRate, this.fillRate); + this.lastMaxRate = rateToUse; + this.calculateTimeWindow(); + this.lastThrottleTime = this.getCurrentTimeInSeconds(); + calculatedRate = this.cubicThrottle(rateToUse); + this.enableTokenBucket(); + } else { + this.calculateTimeWindow(); + calculatedRate = this.cubicSuccess(this.getCurrentTimeInSeconds()); + } + const newRate = Math.min(calculatedRate, 2 * this.measuredTxRate); + this.updateTokenBucketRate(newRate); + } + calculateTimeWindow() { + this.timeWindow = this.getPrecise(Math.pow(this.lastMaxRate * (1 - this.beta) / this.scaleConstant, 1 / 3)); + } + cubicThrottle(rateToUse) { + return this.getPrecise(rateToUse * this.beta); + } + cubicSuccess(timestamp) { + return this.getPrecise( + this.scaleConstant * Math.pow(timestamp - this.lastThrottleTime - this.timeWindow, 3) + this.lastMaxRate + ); + } + enableTokenBucket() { + this.enabled = true; + } + updateTokenBucketRate(newRate) { + this.refillTokenBucket(); + this.fillRate = Math.max(newRate, this.minFillRate); + this.maxCapacity = Math.max(newRate, this.minCapacity); + this.currentCapacity = Math.min(this.currentCapacity, this.maxCapacity); + } + updateMeasuredRate() { + const t = this.getCurrentTimeInSeconds(); + const timeBucket = Math.floor(t * 2) / 2; + this.requestCount++; + if (timeBucket > this.lastTxRateBucket) { + const currentRate = this.requestCount / (timeBucket - this.lastTxRateBucket); + this.measuredTxRate = this.getPrecise(currentRate * this.smooth + this.measuredTxRate * (1 - this.smooth)); + this.requestCount = 0; + this.lastTxRateBucket = timeBucket; + } + } + getPrecise(num) { + return parseFloat(num.toFixed(8)); + } +}; + +// src/constants.ts +var DEFAULT_RETRY_DELAY_BASE = 100; +var MAXIMUM_RETRY_DELAY = 20 * 1e3; +var THROTTLING_RETRY_DELAY_BASE = 500; +var INITIAL_RETRY_TOKENS = 500; +var RETRY_COST = 5; +var TIMEOUT_RETRY_COST = 10; +var NO_RETRY_INCREMENT = 1; +var INVOCATION_ID_HEADER = "amz-sdk-invocation-id"; +var REQUEST_HEADER = "amz-sdk-request"; + +// src/defaultRetryBackoffStrategy.ts +var getDefaultRetryBackoffStrategy = /* @__PURE__ */ __name(() => { + let delayBase = DEFAULT_RETRY_DELAY_BASE; + const computeNextBackoffDelay = /* @__PURE__ */ __name((attempts) => { + return Math.floor(Math.min(MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase)); + }, "computeNextBackoffDelay"); + const setDelayBase = /* @__PURE__ */ __name((delay) => { + delayBase = delay; + }, "setDelayBase"); + return { + computeNextBackoffDelay, + setDelayBase + }; +}, "getDefaultRetryBackoffStrategy"); + +// src/defaultRetryToken.ts +var createDefaultRetryToken = /* @__PURE__ */ __name(({ + retryDelay, + retryCount, + retryCost +}) => { + const getRetryCount = /* @__PURE__ */ __name(() => retryCount, "getRetryCount"); + const getRetryDelay = /* @__PURE__ */ __name(() => Math.min(MAXIMUM_RETRY_DELAY, retryDelay), "getRetryDelay"); + const getRetryCost = /* @__PURE__ */ __name(() => retryCost, "getRetryCost"); + return { + getRetryCount, + getRetryDelay, + getRetryCost + }; +}, "createDefaultRetryToken"); + +// src/StandardRetryStrategy.ts +var StandardRetryStrategy = class { + constructor(maxAttempts) { + this.maxAttempts = maxAttempts; + this.mode = "standard" /* STANDARD */; + this.capacity = INITIAL_RETRY_TOKENS; + this.retryBackoffStrategy = getDefaultRetryBackoffStrategy(); + this.maxAttemptsProvider = typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts; + } + static { + __name(this, "StandardRetryStrategy"); + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + async acquireInitialRetryToken(retryTokenScope) { + return createDefaultRetryToken({ + retryDelay: DEFAULT_RETRY_DELAY_BASE, + retryCount: 0 + }); + } + async refreshRetryTokenForRetry(token, errorInfo) { + const maxAttempts = await this.getMaxAttempts(); + if (this.shouldRetry(token, errorInfo, maxAttempts)) { + const errorType = errorInfo.errorType; + this.retryBackoffStrategy.setDelayBase( + errorType === "THROTTLING" ? THROTTLING_RETRY_DELAY_BASE : DEFAULT_RETRY_DELAY_BASE + ); + const delayFromErrorType = this.retryBackoffStrategy.computeNextBackoffDelay(token.getRetryCount()); + const retryDelay = errorInfo.retryAfterHint ? Math.max(errorInfo.retryAfterHint.getTime() - Date.now() || 0, delayFromErrorType) : delayFromErrorType; + const capacityCost = this.getCapacityCost(errorType); + this.capacity -= capacityCost; + return createDefaultRetryToken({ + retryDelay, + retryCount: token.getRetryCount() + 1, + retryCost: capacityCost + }); + } + throw new Error("No retry token available"); + } + recordSuccess(token) { + this.capacity = Math.max(INITIAL_RETRY_TOKENS, this.capacity + (token.getRetryCost() ?? NO_RETRY_INCREMENT)); + } + /** + * @returns the current available retry capacity. + * + * This number decreases when retries are executed and refills when requests or retries succeed. + */ + getCapacity() { + return this.capacity; + } + async getMaxAttempts() { + try { + return await this.maxAttemptsProvider(); + } catch (error) { + console.warn(`Max attempts provider could not resolve. Using default of ${DEFAULT_MAX_ATTEMPTS}`); + return DEFAULT_MAX_ATTEMPTS; + } + } + shouldRetry(tokenToRenew, errorInfo, maxAttempts) { + const attempts = tokenToRenew.getRetryCount() + 1; + return attempts < maxAttempts && this.capacity >= this.getCapacityCost(errorInfo.errorType) && this.isRetryableError(errorInfo.errorType); + } + getCapacityCost(errorType) { + return errorType === "TRANSIENT" ? TIMEOUT_RETRY_COST : RETRY_COST; + } + isRetryableError(errorType) { + return errorType === "THROTTLING" || errorType === "TRANSIENT"; + } +}; + +// src/AdaptiveRetryStrategy.ts +var AdaptiveRetryStrategy = class { + constructor(maxAttemptsProvider, options) { + this.maxAttemptsProvider = maxAttemptsProvider; + this.mode = "adaptive" /* ADAPTIVE */; + const { rateLimiter } = options ?? {}; + this.rateLimiter = rateLimiter ?? new DefaultRateLimiter(); + this.standardRetryStrategy = new StandardRetryStrategy(maxAttemptsProvider); + } + static { + __name(this, "AdaptiveRetryStrategy"); + } + async acquireInitialRetryToken(retryTokenScope) { + await this.rateLimiter.getSendToken(); + return this.standardRetryStrategy.acquireInitialRetryToken(retryTokenScope); + } + async refreshRetryTokenForRetry(tokenToRenew, errorInfo) { + this.rateLimiter.updateClientSendingRate(errorInfo); + return this.standardRetryStrategy.refreshRetryTokenForRetry(tokenToRenew, errorInfo); + } + recordSuccess(token) { + this.rateLimiter.updateClientSendingRate({}); + this.standardRetryStrategy.recordSuccess(token); + } +}; + +// src/ConfiguredRetryStrategy.ts +var ConfiguredRetryStrategy = class extends StandardRetryStrategy { + static { + __name(this, "ConfiguredRetryStrategy"); + } + /** + * @param maxAttempts - the maximum number of retry attempts allowed. + * e.g., if set to 3, then 4 total requests are possible. + * @param computeNextBackoffDelay - a millisecond delay for each retry or a function that takes the retry attempt + * and returns the delay. + * + * @example exponential backoff. + * ```js + * new Client({ + * retryStrategy: new ConfiguredRetryStrategy(3, (attempt) => attempt ** 2) + * }); + * ``` + * @example constant delay. + * ```js + * new Client({ + * retryStrategy: new ConfiguredRetryStrategy(3, 2000) + * }); + * ``` + */ + constructor(maxAttempts, computeNextBackoffDelay = DEFAULT_RETRY_DELAY_BASE) { + super(typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts); + if (typeof computeNextBackoffDelay === "number") { + this.computeNextBackoffDelay = () => computeNextBackoffDelay; + } else { + this.computeNextBackoffDelay = computeNextBackoffDelay; + } + } + async refreshRetryTokenForRetry(tokenToRenew, errorInfo) { + const token = await super.refreshRetryTokenForRetry(tokenToRenew, errorInfo); + token.getRetryDelay = () => this.computeNextBackoffDelay(token.getRetryCount()); + return token; + } +}; +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 39361: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ByteArrayCollector = void 0; +class ByteArrayCollector { + constructor(allocByteArray) { + this.allocByteArray = allocByteArray; + this.byteLength = 0; + this.byteArrays = []; + } + push(byteArray) { + this.byteArrays.push(byteArray); + this.byteLength += byteArray.byteLength; + } + flush() { + if (this.byteArrays.length === 1) { + const bytes = this.byteArrays[0]; + this.reset(); + return bytes; } - return false; - } - return true; - }, "filterCb"); - absoluteEntries = absoluteEntries.filter(filterCb); - relativeEntries = relativeEntries.filter(filterCb); - return isRemoved; - }, "removeByName"); - const removeByReference = /* @__PURE__ */ __name((toRemove) => { - let isRemoved = false; - const filterCb = /* @__PURE__ */ __name((entry) => { - if (entry.middleware === toRemove) { - isRemoved = true; - for (const alias of getAllAliases(entry.name, entry.aliases)) { - entriesNameSet.delete(alias); + const aggregation = this.allocByteArray(this.byteLength); + let cursor = 0; + for (let i = 0; i < this.byteArrays.length; ++i) { + const bytes = this.byteArrays[i]; + aggregation.set(bytes, cursor); + cursor += bytes.byteLength; } - return false; - } - return true; - }, "filterCb"); - absoluteEntries = absoluteEntries.filter(filterCb); - relativeEntries = relativeEntries.filter(filterCb); - return isRemoved; - }, "removeByReference"); - const cloneTo = /* @__PURE__ */ __name((toStack) => { - absoluteEntries.forEach((entry) => { - toStack.add(entry.middleware, { ...entry }); - }); - relativeEntries.forEach((entry) => { - toStack.addRelativeTo(entry.middleware, { ...entry }); - }); - toStack.identifyOnResolve?.(stack.identifyOnResolve()); - return toStack; - }, "cloneTo"); - const expandRelativeMiddlewareList = /* @__PURE__ */ __name((from) => { - const expandedMiddlewareList = []; - from.before.forEach((entry) => { - if (entry.before.length === 0 && entry.after.length === 0) { - expandedMiddlewareList.push(entry); - } else { - expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); - } - }); - expandedMiddlewareList.push(from); - from.after.reverse().forEach((entry) => { - if (entry.before.length === 0 && entry.after.length === 0) { - expandedMiddlewareList.push(entry); - } else { - expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); - } - }); - return expandedMiddlewareList; - }, "expandRelativeMiddlewareList"); - const getMiddlewareList = /* @__PURE__ */ __name((debug = false) => { - const normalizedAbsoluteEntries = []; - const normalizedRelativeEntries = []; - const normalizedEntriesNameMap = {}; - absoluteEntries.forEach((entry) => { - const normalizedEntry = { - ...entry, - before: [], - after: [] - }; - for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { - normalizedEntriesNameMap[alias] = normalizedEntry; - } - normalizedAbsoluteEntries.push(normalizedEntry); - }); - relativeEntries.forEach((entry) => { - const normalizedEntry = { - ...entry, - before: [], - after: [] - }; - for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { - normalizedEntriesNameMap[alias] = normalizedEntry; - } - normalizedRelativeEntries.push(normalizedEntry); - }); - normalizedRelativeEntries.forEach((entry) => { - if (entry.toMiddleware) { - const toMiddleware = normalizedEntriesNameMap[entry.toMiddleware]; - if (toMiddleware === void 0) { - if (debug) { - return; - } - throw new Error( - `${entry.toMiddleware} is not found when adding ${getMiddlewareNameWithAliases(entry.name, entry.aliases)} middleware ${entry.relation} ${entry.toMiddleware}` - ); + this.reset(); + return aggregation; + } + reset() { + this.byteArrays = []; + this.byteLength = 0; + } +} +exports.ByteArrayCollector = ByteArrayCollector; + + +/***/ }), + +/***/ 78551: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ChecksumStream = void 0; +const ReadableStreamRef = typeof ReadableStream === "function" ? ReadableStream : function () { }; +class ChecksumStream extends ReadableStreamRef { +} +exports.ChecksumStream = ChecksumStream; + + +/***/ }), + +/***/ 6982: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ChecksumStream = void 0; +const util_base64_1 = __nccwpck_require__(75600); +const stream_1 = __nccwpck_require__(12781); +class ChecksumStream extends stream_1.Duplex { + constructor({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) { + var _a, _b; + super(); + if (typeof source.pipe === "function") { + this.source = source; } - if (entry.relation === "after") { - toMiddleware.after.push(entry); + else { + throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); } - if (entry.relation === "before") { - toMiddleware.before.push(entry); + this.base64Encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; + this.expectedChecksum = expectedChecksum; + this.checksum = checksum; + this.checksumSourceLocation = checksumSourceLocation; + this.source.pipe(this); + } + _read(size) { } + _write(chunk, encoding, callback) { + try { + this.checksum.update(chunk); + this.push(chunk); } - } + catch (e) { + return callback(e); + } + return callback(); + } + async _final(callback) { + try { + const digest = await this.checksum.digest(); + const received = this.base64Encoder(digest); + if (this.expectedChecksum !== received) { + return callback(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${received}"` + + ` in response header "${this.checksumSourceLocation}".`)); + } + } + catch (e) { + return callback(e); + } + this.push(null); + return callback(); + } +} +exports.ChecksumStream = ChecksumStream; + + +/***/ }), + +/***/ 72313: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createChecksumStream = void 0; +const util_base64_1 = __nccwpck_require__(75600); +const stream_type_check_1 = __nccwpck_require__(57578); +const ChecksumStream_browser_1 = __nccwpck_require__(78551); +const createChecksumStream = ({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) => { + var _a, _b; + if (!(0, stream_type_check_1.isReadableStream)(source)) { + throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); + } + const encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; + if (typeof TransformStream !== "function") { + throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream."); + } + const transform = new TransformStream({ + start() { }, + async transform(chunk, controller) { + checksum.update(chunk); + controller.enqueue(chunk); + }, + async flush(controller) { + const digest = await checksum.digest(); + const received = encoder(digest); + if (expectedChecksum !== received) { + const error = new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}"` + + ` in response header "${checksumSourceLocation}".`); + controller.error(error); + } + else { + controller.terminate(); + } + }, }); - const mainChain = sort(normalizedAbsoluteEntries).map(expandRelativeMiddlewareList).reduce( - (wholeList, expandedMiddlewareList) => { - wholeList.push(...expandedMiddlewareList); - return wholeList; - }, - [] - ); - return mainChain; - }, "getMiddlewareList"); - const stack = { - add: (middleware, options = {}) => { - const { name, override, aliases: _aliases } = options; - const entry = { - step: "initialize", - priority: "normal", - middleware, - ...options - }; - const aliases = getAllAliases(name, _aliases); - if (aliases.length > 0) { - if (aliases.some((alias) => entriesNameSet.has(alias))) { - if (!override) - throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); - for (const alias of aliases) { - const toOverrideIndex = absoluteEntries.findIndex( - (entry2) => entry2.name === alias || entry2.aliases?.some((a) => a === alias) - ); - if (toOverrideIndex === -1) { - continue; + source.pipeThrough(transform); + const readable = transform.readable; + Object.setPrototypeOf(readable, ChecksumStream_browser_1.ChecksumStream.prototype); + return readable; +}; +exports.createChecksumStream = createChecksumStream; + + +/***/ }), + +/***/ 21927: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createChecksumStream = void 0; +const stream_type_check_1 = __nccwpck_require__(57578); +const ChecksumStream_1 = __nccwpck_require__(6982); +const createChecksumStream_browser_1 = __nccwpck_require__(72313); +function createChecksumStream(init) { + if (typeof ReadableStream === "function" && (0, stream_type_check_1.isReadableStream)(init.source)) { + return (0, createChecksumStream_browser_1.createChecksumStream)(init); + } + return new ChecksumStream_1.ChecksumStream(init); +} +exports.createChecksumStream = createChecksumStream; + + +/***/ }), + +/***/ 33259: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createBufferedReadable = void 0; +const node_stream_1 = __nccwpck_require__(84492); +const ByteArrayCollector_1 = __nccwpck_require__(39361); +const createBufferedReadableStream_1 = __nccwpck_require__(92558); +const stream_type_check_1 = __nccwpck_require__(57578); +function createBufferedReadable(upstream, size, logger) { + if ((0, stream_type_check_1.isReadableStream)(upstream)) { + return (0, createBufferedReadableStream_1.createBufferedReadableStream)(upstream, size, logger); + } + const downstream = new node_stream_1.Readable({ read() { } }); + let streamBufferingLoggedWarning = false; + let bytesSeen = 0; + const buffers = [ + "", + new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size)), + new ByteArrayCollector_1.ByteArrayCollector((size) => Buffer.from(new Uint8Array(size))), + ]; + let mode = -1; + upstream.on("data", (chunk) => { + const chunkMode = (0, createBufferedReadableStream_1.modeOf)(chunk, true); + if (mode !== chunkMode) { + if (mode >= 0) { + downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); + } + mode = chunkMode; + } + if (mode === -1) { + downstream.push(chunk); + return; + } + const chunkSize = (0, createBufferedReadableStream_1.sizeOf)(chunk); + bytesSeen += chunkSize; + const bufferSize = (0, createBufferedReadableStream_1.sizeOf)(buffers[mode]); + if (chunkSize >= size && bufferSize === 0) { + downstream.push(chunk); + } + else { + const newSize = (0, createBufferedReadableStream_1.merge)(buffers, mode, chunk); + if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { + streamBufferingLoggedWarning = true; + logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); } - const toOverride = absoluteEntries[toOverrideIndex]; - if (toOverride.step !== entry.step || entry.priority !== toOverride.priority) { - throw new Error( - `"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware with ${toOverride.priority} priority in ${toOverride.step} step cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware with ${entry.priority} priority in ${entry.step} step.` - ); + if (newSize >= size) { + downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); } - absoluteEntries.splice(toOverrideIndex, 1); - } - } - for (const alias of aliases) { - entriesNameSet.add(alias); } - } - absoluteEntries.push(entry); - }, - addRelativeTo: (middleware, options) => { - const { name, override, aliases: _aliases } = options; - const entry = { - middleware, - ...options - }; - const aliases = getAllAliases(name, _aliases); - if (aliases.length > 0) { - if (aliases.some((alias) => entriesNameSet.has(alias))) { - if (!override) - throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); - for (const alias of aliases) { - const toOverrideIndex = relativeEntries.findIndex( - (entry2) => entry2.name === alias || entry2.aliases?.some((a) => a === alias) - ); - if (toOverrideIndex === -1) { - continue; - } - const toOverride = relativeEntries[toOverrideIndex]; - if (toOverride.toMiddleware !== entry.toMiddleware || toOverride.relation !== entry.relation) { - throw new Error( - `"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware ${toOverride.relation} "${toOverride.toMiddleware}" middleware cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware ${entry.relation} "${entry.toMiddleware}" middleware.` - ); + }); + upstream.on("end", () => { + if (mode !== -1) { + const remainder = (0, createBufferedReadableStream_1.flush)(buffers, mode); + if ((0, createBufferedReadableStream_1.sizeOf)(remainder) > 0) { + downstream.push(remainder); } - relativeEntries.splice(toOverrideIndex, 1); - } } - for (const alias of aliases) { - entriesNameSet.add(alias); + downstream.push(null); + }); + return downstream; +} +exports.createBufferedReadable = createBufferedReadable; + + +/***/ }), + +/***/ 92558: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.modeOf = exports.sizeOf = exports.flush = exports.merge = exports.createBufferedReadable = exports.createBufferedReadableStream = void 0; +const ByteArrayCollector_1 = __nccwpck_require__(39361); +function createBufferedReadableStream(upstream, size, logger) { + const reader = upstream.getReader(); + let streamBufferingLoggedWarning = false; + let bytesSeen = 0; + const buffers = ["", new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size))]; + let mode = -1; + const pull = async (controller) => { + const { value, done } = await reader.read(); + const chunk = value; + if (done) { + if (mode !== -1) { + const remainder = flush(buffers, mode); + if (sizeOf(remainder) > 0) { + controller.enqueue(remainder); + } + } + controller.close(); } - } - relativeEntries.push(entry); - }, - clone: () => cloneTo(constructStack()), - use: (plugin) => { - plugin.applyToStack(stack); - }, - remove: (toRemove) => { - if (typeof toRemove === "string") - return removeByName(toRemove); - else - return removeByReference(toRemove); - }, - removeByTag: (toRemove) => { - let isRemoved = false; - const filterCb = /* @__PURE__ */ __name((entry) => { - const { tags, name, aliases: _aliases } = entry; - if (tags && tags.includes(toRemove)) { - const aliases = getAllAliases(name, _aliases); - for (const alias of aliases) { - entriesNameSet.delete(alias); - } - isRemoved = true; - return false; + else { + const chunkMode = modeOf(chunk, false); + if (mode !== chunkMode) { + if (mode >= 0) { + controller.enqueue(flush(buffers, mode)); + } + mode = chunkMode; + } + if (mode === -1) { + controller.enqueue(chunk); + return; + } + const chunkSize = sizeOf(chunk); + bytesSeen += chunkSize; + const bufferSize = sizeOf(buffers[mode]); + if (chunkSize >= size && bufferSize === 0) { + controller.enqueue(chunk); + } + else { + const newSize = merge(buffers, mode, chunk); + if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { + streamBufferingLoggedWarning = true; + logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); + } + if (newSize >= size) { + controller.enqueue(flush(buffers, mode)); + } + else { + await pull(controller); + } + } } - return true; - }, "filterCb"); - absoluteEntries = absoluteEntries.filter(filterCb); - relativeEntries = relativeEntries.filter(filterCb); - return isRemoved; - }, - concat: (from) => { - const cloned = cloneTo(constructStack()); - cloned.use(from); - cloned.identifyOnResolve( - identifyOnResolve || cloned.identifyOnResolve() || (from.identifyOnResolve?.() ?? false) - ); - return cloned; - }, - applyToStack: cloneTo, - identify: () => { - return getMiddlewareList(true).map((mw) => { - const step = mw.step ?? mw.relation + " " + mw.toMiddleware; - return getMiddlewareNameWithAliases(mw.name, mw.aliases) + " - " + step; - }); - }, - identifyOnResolve(toggle) { - if (typeof toggle === "boolean") - identifyOnResolve = toggle; - return identifyOnResolve; - }, - resolve: (handler, context) => { - for (const middleware of getMiddlewareList().map((entry) => entry.middleware).reverse()) { - handler = middleware(handler, context); - } - if (identifyOnResolve) { - console.log(stack.identify()); - } - return handler; + }; + return new ReadableStream({ + pull, + }); +} +exports.createBufferedReadableStream = createBufferedReadableStream; +exports.createBufferedReadable = createBufferedReadableStream; +function merge(buffers, mode, chunk) { + switch (mode) { + case 0: + buffers[0] += chunk; + return sizeOf(buffers[0]); + case 1: + case 2: + buffers[mode].push(chunk); + return sizeOf(buffers[mode]); } - }; - return stack; -}, "constructStack"); -var stepWeights = { - initialize: 5, - serialize: 4, - build: 3, - finalizeRequest: 2, - deserialize: 1 -}; -var priorityWeights = { - high: 3, - normal: 2, - low: 1 -}; -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - +} +exports.merge = merge; +function flush(buffers, mode) { + switch (mode) { + case 0: + const s = buffers[0]; + buffers[0] = ""; + return s; + case 1: + case 2: + return buffers[mode].flush(); + } + throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`); +} +exports.flush = flush; +function sizeOf(chunk) { + var _a, _b; + return (_b = (_a = chunk === null || chunk === void 0 ? void 0 : chunk.byteLength) !== null && _a !== void 0 ? _a : chunk === null || chunk === void 0 ? void 0 : chunk.length) !== null && _b !== void 0 ? _b : 0; +} +exports.sizeOf = sizeOf; +function modeOf(chunk, allowBuffer = true) { + if (allowBuffer && typeof Buffer !== "undefined" && chunk instanceof Buffer) { + return 2; + } + if (chunk instanceof Uint8Array) { + return 1; + } + if (typeof chunk === "string") { + return 0; + } + return -1; +} +exports.modeOf = modeOf; /***/ }), -/***/ 33461: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 23636: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -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); +"use strict"; -// src/index.ts -var src_exports = {}; -__export(src_exports, { - loadConfig: () => loadConfig -}); -module.exports = __toCommonJS(src_exports); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getAwsChunkedEncodingStream = void 0; +const stream_1 = __nccwpck_require__(12781); +const getAwsChunkedEncodingStream = (readableStream, options) => { + const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options; + const checksumRequired = base64Encoder !== undefined && + checksumAlgorithmFn !== undefined && + checksumLocationName !== undefined && + streamHasher !== undefined; + const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readableStream) : undefined; + const awsChunkedEncodingStream = new stream_1.Readable({ read: () => { } }); + readableStream.on("data", (data) => { + const length = bodyLengthChecker(data) || 0; + awsChunkedEncodingStream.push(`${length.toString(16)}\r\n`); + awsChunkedEncodingStream.push(data); + awsChunkedEncodingStream.push("\r\n"); + }); + readableStream.on("end", async () => { + awsChunkedEncodingStream.push(`0\r\n`); + if (checksumRequired) { + const checksum = base64Encoder(await digest); + awsChunkedEncodingStream.push(`${checksumLocationName}:${checksum}\r\n`); + awsChunkedEncodingStream.push(`\r\n`); + } + awsChunkedEncodingStream.push(null); + }); + return awsChunkedEncodingStream; +}; +exports.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream; -// src/configLoader.ts +/***/ }), -// src/fromEnv.ts -var import_property_provider = __nccwpck_require__(79721); +/***/ 56711: +/***/ ((__unused_webpack_module, exports) => { -// src/getSelectorName.ts -function getSelectorName(functionString) { - try { - const constants = new Set(Array.from(functionString.match(/([A-Z_]){3,}/g) ?? [])); - constants.delete("CONFIG"); - constants.delete("CONFIG_PREFIX_SEPARATOR"); - constants.delete("ENV"); - return [...constants].join(", "); - } catch (e) { - return functionString; - } -} -__name(getSelectorName, "getSelectorName"); +"use strict"; -// src/fromEnv.ts -var fromEnv = /* @__PURE__ */ __name((envVarSelector, logger) => async () => { - try { - const config = envVarSelector(process.env); - if (config === void 0) { - throw new Error(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.headStream = void 0; +async function headStream(stream, bytes) { + var _a; + let byteLengthCounter = 0; + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + byteLengthCounter += (_a = value === null || value === void 0 ? void 0 : value.byteLength) !== null && _a !== void 0 ? _a : 0; + } + if (byteLengthCounter >= bytes) { + break; + } + isDone = done; } - return config; - } catch (e) { - throw new import_property_provider.CredentialsProviderError( - e.message || `Not found in ENV: ${getSelectorName(envVarSelector.toString())}`, - { logger } - ); - } -}, "fromEnv"); - -// src/fromSharedConfigFiles.ts - -var import_shared_ini_file_loader = __nccwpck_require__(43507); -var fromSharedConfigFiles = /* @__PURE__ */ __name((configSelector, { preferredFile = "config", ...init } = {}) => async () => { - const profile = (0, import_shared_ini_file_loader.getProfileName)(init); - const { configFile, credentialsFile } = await (0, import_shared_ini_file_loader.loadSharedConfigFiles)(init); - const profileFromCredentials = credentialsFile[profile] || {}; - const profileFromConfig = configFile[profile] || {}; - const mergedProfile = preferredFile === "config" ? { ...profileFromCredentials, ...profileFromConfig } : { ...profileFromConfig, ...profileFromCredentials }; - try { - const cfgFile = preferredFile === "config" ? configFile : credentialsFile; - const configValue = configSelector(mergedProfile, cfgFile); - if (configValue === void 0) { - throw new Error(); + reader.releaseLock(); + const collected = new Uint8Array(Math.min(bytes, byteLengthCounter)); + let offset = 0; + for (const chunk of chunks) { + if (chunk.byteLength > collected.byteLength - offset) { + collected.set(chunk.subarray(0, collected.byteLength - offset), offset); + break; + } + else { + collected.set(chunk, offset); + } + offset += chunk.length; } - return configValue; - } catch (e) { - throw new import_property_provider.CredentialsProviderError( - e.message || `Not found in config files w/ profile [${profile}]: ${getSelectorName(configSelector.toString())}`, - { logger: init.logger } - ); - } -}, "fromSharedConfigFiles"); + return collected; +} +exports.headStream = headStream; -// src/fromStatic.ts -var isFunction = /* @__PURE__ */ __name((func) => typeof func === "function", "isFunction"); -var fromStatic = /* @__PURE__ */ __name((defaultValue) => isFunction(defaultValue) ? async () => await defaultValue() : (0, import_property_provider.fromStatic)(defaultValue), "fromStatic"); +/***/ }), -// src/configLoader.ts -var loadConfig = /* @__PURE__ */ __name(({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => (0, import_property_provider.memoize)( - (0, import_property_provider.chain)( - fromEnv(environmentVariableSelector), - fromSharedConfigFiles(configFileSelector, configuration), - fromStatic(defaultValue) - ) -), "loadConfig"); -// Annotate the CommonJS export names for ESM import in node: +/***/ 6708: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -0 && (0); +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.headStream = void 0; +const stream_1 = __nccwpck_require__(12781); +const headStream_browser_1 = __nccwpck_require__(56711); +const stream_type_check_1 = __nccwpck_require__(57578); +const headStream = (stream, bytes) => { + if ((0, stream_type_check_1.isReadableStream)(stream)) { + return (0, headStream_browser_1.headStream)(stream, bytes); + } + return new Promise((resolve, reject) => { + const collector = new Collector(); + collector.limit = bytes; + stream.pipe(collector); + stream.on("error", (err) => { + collector.end(); + reject(err); + }); + collector.on("error", reject); + collector.on("finish", function () { + const bytes = new Uint8Array(Buffer.concat(this.buffers)); + resolve(bytes); + }); + }); +}; +exports.headStream = headStream; +class Collector extends stream_1.Writable { + constructor() { + super(...arguments); + this.buffers = []; + this.limit = Infinity; + this.bytesBuffered = 0; + } + _write(chunk, encoding, callback) { + var _a; + this.buffers.push(chunk); + this.bytesBuffered += (_a = chunk.byteLength) !== null && _a !== void 0 ? _a : 0; + if (this.bytesBuffered >= this.limit) { + const excess = this.bytesBuffered - this.limit; + const tailBuffer = this.buffers[this.buffers.length - 1]; + this.buffers[this.buffers.length - 1] = tailBuffer.subarray(0, tailBuffer.byteLength - excess); + this.emit("finish"); + } + callback(); + } +} /***/ }), -/***/ 20258: +/***/ 96607: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -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 __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { @@ -243700,784 +241314,398 @@ var __copyProps = (to, from, except, desc) => { } 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 __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { - DEFAULT_REQUEST_TIMEOUT: () => DEFAULT_REQUEST_TIMEOUT, - NodeHttp2Handler: () => NodeHttp2Handler, - NodeHttpHandler: () => NodeHttpHandler, - streamCollector: () => streamCollector + Uint8ArrayBlobAdapter: () => Uint8ArrayBlobAdapter }); module.exports = __toCommonJS(src_exports); -// src/node-http-handler.ts -var import_protocol_http = __nccwpck_require__(64418); -var import_querystring_builder = __nccwpck_require__(68031); -var import_http = __nccwpck_require__(13685); -var import_https = __nccwpck_require__(95687); - -// src/constants.ts -var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"]; - -// src/get-transformed-headers.ts -var getTransformedHeaders = /* @__PURE__ */ __name((headers) => { - const transformedHeaders = {}; - for (const name of Object.keys(headers)) { - const headerValues = headers[name]; - transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues; - } - return transformedHeaders; -}, "getTransformedHeaders"); - -// src/timing.ts -var timing = { - setTimeout: (cb, ms) => setTimeout(cb, ms), - clearTimeout: (timeoutId) => clearTimeout(timeoutId) -}; - -// src/set-connection-timeout.ts -var DEFER_EVENT_LISTENER_TIME = 1e3; -var setConnectionTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = 0) => { - if (!timeoutInMs) { - return -1; - } - const registerTimeout = /* @__PURE__ */ __name((offset) => { - const timeoutId = timing.setTimeout(() => { - request.destroy(); - reject( - Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), { - name: "TimeoutError" - }) - ); - }, timeoutInMs - offset); - const doWithSocket = /* @__PURE__ */ __name((socket) => { - if (socket?.connecting) { - socket.on("connect", () => { - timing.clearTimeout(timeoutId); - }); - } else { - timing.clearTimeout(timeoutId); - } - }, "doWithSocket"); - if (request.socket) { - doWithSocket(request.socket); - } else { - request.on("socket", doWithSocket); - } - }, "registerTimeout"); - if (timeoutInMs < 2e3) { - registerTimeout(0); - return 0; - } - return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME); -}, "setConnectionTimeout"); - -// src/set-socket-keep-alive.ts -var DEFER_EVENT_LISTENER_TIME2 = 3e3; -var setSocketKeepAlive = /* @__PURE__ */ __name((request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME2) => { - if (keepAlive !== true) { - return -1; - } - const registerListener = /* @__PURE__ */ __name(() => { - if (request.socket) { - request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); - } else { - request.on("socket", (socket) => { - socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); - }); - } - }, "registerListener"); - if (deferTimeMs === 0) { - registerListener(); - return 0; - } - return timing.setTimeout(registerListener, deferTimeMs); -}, "setSocketKeepAlive"); - -// src/set-socket-timeout.ts -var DEFER_EVENT_LISTENER_TIME3 = 3e3; -var setSocketTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = DEFAULT_REQUEST_TIMEOUT) => { - const registerTimeout = /* @__PURE__ */ __name((offset) => { - const timeout = timeoutInMs - offset; - const onTimeout = /* @__PURE__ */ __name(() => { - request.destroy(); - reject(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" })); - }, "onTimeout"); - if (request.socket) { - request.socket.setTimeout(timeout, onTimeout); - request.on("close", () => request.socket?.removeListener("timeout", onTimeout)); - } else { - request.setTimeout(timeout, onTimeout); - } - }, "registerTimeout"); - if (0 < timeoutInMs && timeoutInMs < 6e3) { - registerTimeout(0); - return 0; - } - return timing.setTimeout( - registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME3), - DEFER_EVENT_LISTENER_TIME3 - ); -}, "setSocketTimeout"); - -// src/write-request-body.ts -var import_stream = __nccwpck_require__(12781); -var MIN_WAIT_TIME = 6e3; -async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME) { - const headers = request.headers ?? {}; - const expect = headers["Expect"] || headers["expect"]; - let timeoutId = -1; - let sendBody = true; - if (expect === "100-continue") { - sendBody = await Promise.race([ - new Promise((resolve) => { - timeoutId = Number(timing.setTimeout(() => resolve(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs))); - }), - new Promise((resolve) => { - httpRequest.on("continue", () => { - timing.clearTimeout(timeoutId); - resolve(true); - }); - httpRequest.on("response", () => { - timing.clearTimeout(timeoutId); - resolve(false); - }); - httpRequest.on("error", () => { - timing.clearTimeout(timeoutId); - resolve(false); - }); - }) - ]); - } - if (sendBody) { - writeBody(httpRequest, request.body); +// src/blob/transforms.ts +var import_util_base64 = __nccwpck_require__(75600); +var import_util_utf8 = __nccwpck_require__(41895); +function transformToString(payload, encoding = "utf-8") { + if (encoding === "base64") { + return (0, import_util_base64.toBase64)(payload); } + return (0, import_util_utf8.toUtf8)(payload); } -__name(writeRequestBody, "writeRequestBody"); -function writeBody(httpRequest, body) { - if (body instanceof import_stream.Readable) { - body.pipe(httpRequest); - return; - } - if (body) { - if (Buffer.isBuffer(body) || typeof body === "string") { - httpRequest.end(body); - return; - } - const uint8 = body; - if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") { - httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength)); - return; - } - httpRequest.end(Buffer.from(body)); - return; +__name(transformToString, "transformToString"); +function transformFromString(str, encoding) { + if (encoding === "base64") { + return Uint8ArrayBlobAdapter.mutate((0, import_util_base64.fromBase64)(str)); } - httpRequest.end(); + return Uint8ArrayBlobAdapter.mutate((0, import_util_utf8.fromUtf8)(str)); } -__name(writeBody, "writeBody"); - -// src/node-http-handler.ts -var DEFAULT_REQUEST_TIMEOUT = 0; -var NodeHttpHandler = class _NodeHttpHandler { - constructor(options) { - this.socketWarningTimestamp = 0; - // Node http handler is hard-coded to http/1.1: https://github.com/nodejs/node/blob/ff5664b83b89c55e4ab5d5f60068fb457f1f5872/lib/_http_server.js#L286 - this.metadata = { handlerProtocol: "http/1.1" }; - this.configProvider = new Promise((resolve, reject) => { - if (typeof options === "function") { - options().then((_options) => { - resolve(this.resolveDefaultConfig(_options)); - }).catch(reject); - } else { - resolve(this.resolveDefaultConfig(options)); - } - }); - } - static { - __name(this, "NodeHttpHandler"); - } - /** - * @returns the input if it is an HttpHandler of any class, - * or instantiates a new instance of this handler. - */ - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; - } - return new _NodeHttpHandler(instanceOrOptions); - } - /** - * @internal - * - * @param agent - http(s) agent in use by the NodeHttpHandler instance. - * @param socketWarningTimestamp - last socket usage check timestamp. - * @param logger - channel for the warning. - * @returns timestamp of last emitted warning. - */ - static checkSocketUsage(agent, socketWarningTimestamp, logger = console) { - const { sockets, requests, maxSockets } = agent; - if (typeof maxSockets !== "number" || maxSockets === Infinity) { - return socketWarningTimestamp; - } - const interval = 15e3; - if (Date.now() - interval < socketWarningTimestamp) { - return socketWarningTimestamp; - } - if (sockets && requests) { - for (const origin in sockets) { - const socketsInUse = sockets[origin]?.length ?? 0; - const requestsEnqueued = requests[origin]?.length ?? 0; - if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) { - logger?.warn?.( - `@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued. -See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html -or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.` - ); - return Date.now(); - } - } - } - return socketWarningTimestamp; - } - resolveDefaultConfig(options) { - const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent } = options || {}; - const keepAlive = true; - const maxSockets = 50; - return { - connectionTimeout, - requestTimeout: requestTimeout ?? socketTimeout, - socketAcquisitionWarningTimeout, - httpAgent: (() => { - if (httpAgent instanceof import_http.Agent || typeof httpAgent?.destroy === "function") { - return httpAgent; - } - return new import_http.Agent({ keepAlive, maxSockets, ...httpAgent }); - })(), - httpsAgent: (() => { - if (httpsAgent instanceof import_https.Agent || typeof httpsAgent?.destroy === "function") { - return httpsAgent; - } - return new import_https.Agent({ keepAlive, maxSockets, ...httpsAgent }); - })(), - logger: console - }; - } - destroy() { - this.config?.httpAgent?.destroy(); - this.config?.httpsAgent?.destroy(); - } - async handle(request, { abortSignal } = {}) { - if (!this.config) { - this.config = await this.configProvider; - } - return new Promise((_resolve, _reject) => { - let writeRequestBodyPromise = void 0; - const timeouts = []; - const resolve = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - timeouts.forEach(timing.clearTimeout); - _resolve(arg); - }, "resolve"); - const reject = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - timeouts.forEach(timing.clearTimeout); - _reject(arg); - }, "reject"); - if (!this.config) { - throw new Error("Node HTTP request handler config is not resolved"); - } - if (abortSignal?.aborted) { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - return; - } - const isSSL = request.protocol === "https:"; - const agent = isSSL ? this.config.httpsAgent : this.config.httpAgent; - timeouts.push( - timing.setTimeout( - () => { - this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage( - agent, - this.socketWarningTimestamp, - this.config.logger - ); - }, - this.config.socketAcquisitionWarningTimeout ?? (this.config.requestTimeout ?? 2e3) + (this.config.connectionTimeout ?? 1e3) - ) - ); - const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); - let auth = void 0; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}`; - } - let path = request.path; - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - let hostname = request.hostname ?? ""; - if (hostname[0] === "[" && hostname.endsWith("]")) { - hostname = request.hostname.slice(1, -1); - } else { - hostname = request.hostname; - } - const nodeHttpsOptions = { - headers: request.headers, - host: hostname, - method: request.method, - path, - port: request.port, - agent, - auth - }; - const requestFunc = isSSL ? import_https.request : import_http.request; - const req = requestFunc(nodeHttpsOptions, (res) => { - const httpResponse = new import_protocol_http.HttpResponse({ - statusCode: res.statusCode || -1, - reason: res.statusMessage, - headers: getTransformedHeaders(res.headers), - body: res - }); - resolve({ response: httpResponse }); - }); - req.on("error", (err) => { - if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) { - reject(Object.assign(err, { name: "TimeoutError" })); - } else { - reject(err); - } - }); - if (abortSignal) { - const onAbort = /* @__PURE__ */ __name(() => { - req.destroy(); - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - }, "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - req.once("close", () => signal.removeEventListener("abort", onAbort)); - } else { - abortSignal.onabort = onAbort; - } - } - timeouts.push(setConnectionTimeout(req, reject, this.config.connectionTimeout)); - timeouts.push(setSocketTimeout(req, reject, this.config.requestTimeout)); - const httpAgent = nodeHttpsOptions.agent; - if (typeof httpAgent === "object" && "keepAlive" in httpAgent) { - timeouts.push( - setSocketKeepAlive(req, { - // @ts-expect-error keepAlive is not public on httpAgent. - keepAlive: httpAgent.keepAlive, - // @ts-expect-error keepAliveMsecs is not public on httpAgent. - keepAliveMsecs: httpAgent.keepAliveMsecs - }) - ); - } - writeRequestBodyPromise = writeRequestBody(req, request, this.config.requestTimeout).catch((e) => { - timeouts.forEach(timing.clearTimeout); - return _reject(e); - }); - }); - } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config) => { - return { - ...config, - [key]: value - }; - }); - } - httpHandlerConfigs() { - return this.config ?? {}; - } -}; - -// src/node-http2-handler.ts - - -var import_http22 = __nccwpck_require__(85158); - -// src/node-http2-connection-manager.ts -var import_http2 = __toESM(__nccwpck_require__(85158)); - -// src/node-http2-connection-pool.ts -var NodeHttp2ConnectionPool = class { - constructor(sessions) { - this.sessions = []; - this.sessions = sessions ?? []; - } - static { - __name(this, "NodeHttp2ConnectionPool"); - } - poll() { - if (this.sessions.length > 0) { - return this.sessions.shift(); - } - } - offerLast(session) { - this.sessions.push(session); - } - contains(session) { - return this.sessions.includes(session); - } - remove(session) { - this.sessions = this.sessions.filter((s) => s !== session); - } - [Symbol.iterator]() { - return this.sessions[Symbol.iterator](); - } - destroy(connection) { - for (const session of this.sessions) { - if (session === connection) { - if (!session.destroyed) { - session.destroy(); - } - } - } - } -}; +__name(transformFromString, "transformFromString"); -// src/node-http2-connection-manager.ts -var NodeHttp2ConnectionManager = class { - constructor(config) { - this.sessionCache = /* @__PURE__ */ new Map(); - this.config = config; - if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) { - throw new RangeError("maxConcurrency must be greater than zero."); - } - } +// src/blob/Uint8ArrayBlobAdapter.ts +var Uint8ArrayBlobAdapter = class _Uint8ArrayBlobAdapter extends Uint8Array { static { - __name(this, "NodeHttp2ConnectionManager"); - } - lease(requestContext, connectionConfiguration) { - const url = this.getUrlString(requestContext); - const existingPool = this.sessionCache.get(url); - if (existingPool) { - const existingSession = existingPool.poll(); - if (existingSession && !this.config.disableConcurrency) { - return existingSession; - } - } - const session = import_http2.default.connect(url); - if (this.config.maxConcurrency) { - session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => { - if (err) { - throw new Error( - "Fail to set maxConcurrentStreams to " + this.config.maxConcurrency + "when creating new session for " + requestContext.destination.toString() - ); - } - }); - } - session.unref(); - const destroySessionCb = /* @__PURE__ */ __name(() => { - session.destroy(); - this.deleteSession(url, session); - }, "destroySessionCb"); - session.on("goaway", destroySessionCb); - session.on("error", destroySessionCb); - session.on("frameError", destroySessionCb); - session.on("close", () => this.deleteSession(url, session)); - if (connectionConfiguration.requestTimeout) { - session.setTimeout(connectionConfiguration.requestTimeout, destroySessionCb); - } - const connectionPool = this.sessionCache.get(url) || new NodeHttp2ConnectionPool(); - connectionPool.offerLast(session); - this.sessionCache.set(url, connectionPool); - return session; + __name(this, "Uint8ArrayBlobAdapter"); } /** - * Delete a session from the connection pool. - * @param authority The authority of the session to delete. - * @param session The session to delete. + * @param source - such as a string or Stream. + * @returns a new Uint8ArrayBlobAdapter extending Uint8Array. */ - deleteSession(authority, session) { - const existingConnectionPool = this.sessionCache.get(authority); - if (!existingConnectionPool) { - return; - } - if (!existingConnectionPool.contains(session)) { - return; - } - existingConnectionPool.remove(session); - this.sessionCache.set(authority, existingConnectionPool); - } - release(requestContext, session) { - const cacheKey = this.getUrlString(requestContext); - this.sessionCache.get(cacheKey)?.offerLast(session); - } - destroy() { - for (const [key, connectionPool] of this.sessionCache) { - for (const session of connectionPool) { - if (!session.destroyed) { - session.destroy(); - } - connectionPool.remove(session); - } - this.sessionCache.delete(key); - } - } - setMaxConcurrentStreams(maxConcurrentStreams) { - if (maxConcurrentStreams && maxConcurrentStreams <= 0) { - throw new RangeError("maxConcurrentStreams must be greater than zero."); - } - this.config.maxConcurrency = maxConcurrentStreams; - } - setDisableConcurrentStreams(disableConcurrentStreams) { - this.config.disableConcurrency = disableConcurrentStreams; - } - getUrlString(request) { - return request.destination.toString(); - } -}; - -// src/node-http2-handler.ts -var NodeHttp2Handler = class _NodeHttp2Handler { - constructor(options) { - this.metadata = { handlerProtocol: "h2" }; - this.connectionManager = new NodeHttp2ConnectionManager({}); - this.configProvider = new Promise((resolve, reject) => { - if (typeof options === "function") { - options().then((opts) => { - resolve(opts || {}); - }).catch(reject); - } else { - resolve(options || {}); - } - }); - } - static { - __name(this, "NodeHttp2Handler"); + static fromString(source, encoding = "utf-8") { + switch (typeof source) { + case "string": + return transformFromString(source, encoding); + default: + throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`); + } } /** - * @returns the input if it is an HttpHandler of any class, - * or instantiates a new instance of this handler. + * @param source - Uint8Array to be mutated. + * @returns the same Uint8Array but with prototype switched to Uint8ArrayBlobAdapter. */ - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; - } - return new _NodeHttp2Handler(instanceOrOptions); + static mutate(source) { + Object.setPrototypeOf(source, _Uint8ArrayBlobAdapter.prototype); + return source; } - destroy() { - this.connectionManager.destroy(); + /** + * @param encoding - default 'utf-8'. + * @returns the blob as string. + */ + transformToString(encoding = "utf-8") { + return transformToString(this, encoding); } - async handle(request, { abortSignal } = {}) { - if (!this.config) { - this.config = await this.configProvider; - this.connectionManager.setDisableConcurrentStreams(this.config.disableConcurrentStreams || false); - if (this.config.maxConcurrentStreams) { - this.connectionManager.setMaxConcurrentStreams(this.config.maxConcurrentStreams); - } +}; + +// src/index.ts +__reExport(src_exports, __nccwpck_require__(6982), module.exports); +__reExport(src_exports, __nccwpck_require__(21927), module.exports); +__reExport(src_exports, __nccwpck_require__(33259), module.exports); +__reExport(src_exports, __nccwpck_require__(23636), module.exports); +__reExport(src_exports, __nccwpck_require__(6708), module.exports); +__reExport(src_exports, __nccwpck_require__(4515), module.exports); +__reExport(src_exports, __nccwpck_require__(88321), module.exports); +__reExport(src_exports, __nccwpck_require__(57578), module.exports); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 12942: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.sdkStreamMixin = void 0; +const fetch_http_handler_1 = __nccwpck_require__(82687); +const util_base64_1 = __nccwpck_require__(75600); +const util_hex_encoding_1 = __nccwpck_require__(45364); +const util_utf8_1 = __nccwpck_require__(41895); +const stream_type_check_1 = __nccwpck_require__(57578); +const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; +const sdkStreamMixin = (stream) => { + var _a, _b; + if (!isBlobInstance(stream) && !(0, stream_type_check_1.isReadableStream)(stream)) { + const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; + throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`); } - const { requestTimeout, disableConcurrentStreams } = this.config; - return new Promise((_resolve, _reject) => { - let fulfilled = false; - let writeRequestBodyPromise = void 0; - const resolve = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - _resolve(arg); - }, "resolve"); - const reject = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - _reject(arg); - }, "reject"); - if (abortSignal?.aborted) { - fulfilled = true; - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - return; - } - const { hostname, method, port, protocol, query } = request; - let auth = ""; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}@`; - } - const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : ""}`; - const requestContext = { destination: new URL(authority) }; - const session = this.connectionManager.lease(requestContext, { - requestTimeout: this.config?.sessionTimeout, - disableConcurrentStreams: disableConcurrentStreams || false - }); - const rejectWithDestroy = /* @__PURE__ */ __name((err) => { - if (disableConcurrentStreams) { - this.destroySession(session); + let transformed = false; + const transformToByteArray = async () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); } - fulfilled = true; - reject(err); - }, "rejectWithDestroy"); - const queryString = (0, import_querystring_builder.buildQueryString)(query || {}); - let path = request.path; - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - const req = session.request({ - ...request.headers, - [import_http22.constants.HTTP2_HEADER_PATH]: path, - [import_http22.constants.HTTP2_HEADER_METHOD]: method - }); - session.ref(); - req.on("response", (headers) => { - const httpResponse = new import_protocol_http.HttpResponse({ - statusCode: headers[":status"] || -1, - headers: getTransformedHeaders(headers), - body: req - }); - fulfilled = true; - resolve({ response: httpResponse }); - if (disableConcurrentStreams) { - session.close(); - this.connectionManager.deleteSession(authority, session); + transformed = true; + return await (0, fetch_http_handler_1.streamCollector)(stream); + }; + const blobToWebStream = (blob) => { + if (typeof blob.stream !== "function") { + throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\n" + + "If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body"); } - }); - if (requestTimeout) { - req.setTimeout(requestTimeout, () => { - req.close(); - const timeoutError = new Error(`Stream timed out because of no activity for ${requestTimeout} ms`); - timeoutError.name = "TimeoutError"; - rejectWithDestroy(timeoutError); - }); - } - if (abortSignal) { - const onAbort = /* @__PURE__ */ __name(() => { - req.close(); - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - rejectWithDestroy(abortError); - }, "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - req.once("close", () => signal.removeEventListener("abort", onAbort)); - } else { - abortSignal.onabort = onAbort; + return blob.stream(); + }; + return Object.assign(stream, { + transformToByteArray: transformToByteArray, + transformToString: async (encoding) => { + const buf = await transformToByteArray(); + if (encoding === "base64") { + return (0, util_base64_1.toBase64)(buf); + } + else if (encoding === "hex") { + return (0, util_hex_encoding_1.toHex)(buf); + } + else if (encoding === undefined || encoding === "utf8" || encoding === "utf-8") { + return (0, util_utf8_1.toUtf8)(buf); + } + else if (typeof TextDecoder === "function") { + return new TextDecoder(encoding).decode(buf); + } + else { + throw new Error("TextDecoder is not available, please make sure polyfill is provided."); + } + }, + transformToWebStream: () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + transformed = true; + if (isBlobInstance(stream)) { + return blobToWebStream(stream); + } + else if ((0, stream_type_check_1.isReadableStream)(stream)) { + return stream; + } + else { + throw new Error(`Cannot transform payload to web stream, got ${stream}`); + } + }, + }); +}; +exports.sdkStreamMixin = sdkStreamMixin; +const isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob; + + +/***/ }), + +/***/ 4515: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.sdkStreamMixin = void 0; +const node_http_handler_1 = __nccwpck_require__(20258); +const util_buffer_from_1 = __nccwpck_require__(31381); +const stream_1 = __nccwpck_require__(12781); +const sdk_stream_mixin_browser_1 = __nccwpck_require__(12942); +const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; +const sdkStreamMixin = (stream) => { + var _a, _b; + if (!(stream instanceof stream_1.Readable)) { + try { + return (0, sdk_stream_mixin_browser_1.sdkStreamMixin)(stream); } - } - req.on("frameError", (type, code, id) => { - rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`)); - }); - req.on("error", rejectWithDestroy); - req.on("aborted", () => { - rejectWithDestroy( - new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${req.rstCode}.`) - ); - }); - req.on("close", () => { - session.unref(); - if (disableConcurrentStreams) { - session.destroy(); + catch (e) { + const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; + throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`); } - if (!fulfilled) { - rejectWithDestroy(new Error("Unexpected error: http2 request did not get a response")); + } + let transformed = false; + const transformToByteArray = async () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); } - }); - writeRequestBodyPromise = writeRequestBody(req, request, requestTimeout); - }); - } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config) => { - return { - ...config, - [key]: value - }; + transformed = true; + return await (0, node_http_handler_1.streamCollector)(stream); + }; + return Object.assign(stream, { + transformToByteArray, + transformToString: async (encoding) => { + const buf = await transformToByteArray(); + if (encoding === undefined || Buffer.isEncoding(encoding)) { + return (0, util_buffer_from_1.fromArrayBuffer)(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding); + } + else { + const decoder = new TextDecoder(encoding); + return decoder.decode(buf); + } + }, + transformToWebStream: () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + if (stream.readableFlowing !== null) { + throw new Error("The stream has been consumed by other callbacks."); + } + if (typeof stream_1.Readable.toWeb !== "function") { + throw new Error("Readable.toWeb() is not supported. Please ensure a polyfill is available."); + } + transformed = true; + return stream_1.Readable.toWeb(stream); + }, }); - } - httpHandlerConfigs() { - return this.config ?? {}; - } - /** - * Destroys a session. - * @param session - the session to destroy. - */ - destroySession(session) { - if (!session.destroyed) { - session.destroy(); +}; +exports.sdkStreamMixin = sdkStreamMixin; + + +/***/ }), + +/***/ 64693: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.splitStream = void 0; +async function splitStream(stream) { + if (typeof stream.stream === "function") { + stream = stream.stream(); } - } + const readableStream = stream; + return readableStream.tee(); +} +exports.splitStream = splitStream; + + +/***/ }), + +/***/ 88321: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.splitStream = void 0; +const stream_1 = __nccwpck_require__(12781); +const splitStream_browser_1 = __nccwpck_require__(64693); +const stream_type_check_1 = __nccwpck_require__(57578); +async function splitStream(stream) { + if ((0, stream_type_check_1.isReadableStream)(stream) || (0, stream_type_check_1.isBlob)(stream)) { + return (0, splitStream_browser_1.splitStream)(stream); + } + const stream1 = new stream_1.PassThrough(); + const stream2 = new stream_1.PassThrough(); + stream.pipe(stream1); + stream.pipe(stream2); + return [stream1, stream2]; +} +exports.splitStream = splitStream; + + +/***/ }), + +/***/ 57578: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isBlob = exports.isReadableStream = void 0; +const isReadableStream = (stream) => { + var _a; + return typeof ReadableStream === "function" && + (((_a = stream === null || stream === void 0 ? void 0 : stream.constructor) === null || _a === void 0 ? void 0 : _a.name) === ReadableStream.name || stream instanceof ReadableStream); +}; +exports.isReadableStream = isReadableStream; +const isBlob = (blob) => { + var _a; + return typeof Blob === "function" && (((_a = blob === null || blob === void 0 ? void 0 : blob.constructor) === null || _a === void 0 ? void 0 : _a.name) === Blob.name || blob instanceof Blob); }; +exports.isBlob = isBlob; -// src/stream-collector/collector.ts -var Collector = class extends import_stream.Writable { - constructor() { - super(...arguments); - this.bufferedBytes = []; - } - static { - __name(this, "Collector"); +/***/ }), + +/***/ 54197: +/***/ ((module) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +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 }); } - _write(chunk, encoding, callback) { - this.bufferedBytes.push(chunk); - callback(); + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + escapeUri: () => escapeUri, + escapeUriPath: () => escapeUriPath +}); +module.exports = __toCommonJS(src_exports); + +// src/escape-uri.ts +var escapeUri = /* @__PURE__ */ __name((uri) => ( + // AWS percent-encodes some extra non-standard characters in a URI + encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode) +), "escapeUri"); +var hexEncode = /* @__PURE__ */ __name((c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, "hexEncode"); + +// src/escape-uri-path.ts +var escapeUriPath = /* @__PURE__ */ __name((uri) => uri.split("/").map(escapeUri).join("/"), "escapeUriPath"); +// Annotate the CommonJS export names for ESM import in node: + +0 && (0); + + + +/***/ }), + +/***/ 41895: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +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); -// src/stream-collector/index.ts -var streamCollector = /* @__PURE__ */ __name((stream) => { - if (isReadableStreamInstance(stream)) { - return collectReadableStream(stream); +// src/index.ts +var src_exports = {}; +__export(src_exports, { + fromUtf8: () => fromUtf8, + toUint8Array: () => toUint8Array, + toUtf8: () => toUtf8 +}); +module.exports = __toCommonJS(src_exports); + +// src/fromUtf8.ts +var import_util_buffer_from = __nccwpck_require__(31381); +var fromUtf8 = /* @__PURE__ */ __name((input) => { + const buf = (0, import_util_buffer_from.fromString)(input, "utf8"); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); +}, "fromUtf8"); + +// src/toUint8Array.ts +var toUint8Array = /* @__PURE__ */ __name((data) => { + if (typeof data === "string") { + return fromUtf8(data); } - return new Promise((resolve, reject) => { - const collector = new Collector(); - stream.pipe(collector); - stream.on("error", (err) => { - collector.end(); - reject(err); - }); - collector.on("error", reject); - collector.on("finish", function() { - const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes)); - resolve(bytes); - }); - }); -}, "streamCollector"); -var isReadableStreamInstance = /* @__PURE__ */ __name((stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream, "isReadableStreamInstance"); -async function collectReadableStream(stream) { - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - let length = 0; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - length += value.length; - } - isDone = done; + if (ArrayBuffer.isView(data)) { + return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); } - const collected = new Uint8Array(length); - let offset = 0; - for (const chunk of chunks) { - collected.set(chunk, offset); - offset += chunk.length; + return new Uint8Array(data); +}, "toUint8Array"); + +// src/toUtf8.ts + +var toUtf8 = /* @__PURE__ */ __name((input) => { + if (typeof input === "string") { + return input; } - return collected; -} -__name(collectReadableStream, "collectReadableStream"); + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); + } + return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); +}, "toUtf8"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); @@ -244486,7 +241714,7 @@ __name(collectReadableStream, "collectReadableStream"); /***/ }), -/***/ 79721: +/***/ 78011: /***/ ((module) => { var __defProp = Object.defineProperty; @@ -244511,31401 +241739,33173 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var src_exports = {}; __export(src_exports, { - CredentialsProviderError: () => CredentialsProviderError, - ProviderError: () => ProviderError, - TokenProviderError: () => TokenProviderError, - chain: () => chain, - fromStatic: () => fromStatic, - memoize: () => memoize + WaiterState: () => WaiterState, + checkExceptions: () => checkExceptions, + createWaiter: () => createWaiter, + waiterServiceDefaults: () => waiterServiceDefaults }); module.exports = __toCommonJS(src_exports); -// src/ProviderError.ts -var ProviderError = class _ProviderError extends Error { - constructor(message, options = true) { - let logger; - let tryNextLink = true; - if (typeof options === "boolean") { - logger = void 0; - tryNextLink = options; - } else if (options != null && typeof options === "object") { - logger = options.logger; - tryNextLink = options.tryNextLink ?? true; - } - super(message); - this.name = "ProviderError"; - this.tryNextLink = tryNextLink; - Object.setPrototypeOf(this, _ProviderError.prototype); - logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); - } - static { - __name(this, "ProviderError"); - } - /** - * @deprecated use new operator. - */ - static from(error, options = true) { - return Object.assign(new this(error.message, options), error); - } +// src/utils/sleep.ts +var sleep = /* @__PURE__ */ __name((seconds) => { + return new Promise((resolve) => setTimeout(resolve, seconds * 1e3)); +}, "sleep"); + +// src/waiter.ts +var waiterServiceDefaults = { + minDelay: 2, + maxDelay: 120 }; +var WaiterState = /* @__PURE__ */ ((WaiterState2) => { + WaiterState2["ABORTED"] = "ABORTED"; + WaiterState2["FAILURE"] = "FAILURE"; + WaiterState2["SUCCESS"] = "SUCCESS"; + WaiterState2["RETRY"] = "RETRY"; + WaiterState2["TIMEOUT"] = "TIMEOUT"; + return WaiterState2; +})(WaiterState || {}); +var checkExceptions = /* @__PURE__ */ __name((result) => { + if (result.state === "ABORTED" /* ABORTED */) { + const abortError = new Error( + `${JSON.stringify({ + ...result, + reason: "Request was aborted" + })}` + ); + abortError.name = "AbortError"; + throw abortError; + } else if (result.state === "TIMEOUT" /* TIMEOUT */) { + const timeoutError = new Error( + `${JSON.stringify({ + ...result, + reason: "Waiter has timed out" + })}` + ); + timeoutError.name = "TimeoutError"; + throw timeoutError; + } else if (result.state !== "SUCCESS" /* SUCCESS */) { + throw new Error(`${JSON.stringify(result)}`); + } + return result; +}, "checkExceptions"); -// src/CredentialsProviderError.ts -var CredentialsProviderError = class _CredentialsProviderError extends ProviderError { - /** - * @override - */ - constructor(message, options = true) { - super(message, options); - this.name = "CredentialsProviderError"; - Object.setPrototypeOf(this, _CredentialsProviderError.prototype); +// src/poller.ts +var exponentialBackoffWithJitter = /* @__PURE__ */ __name((minDelay, maxDelay, attemptCeiling, attempt) => { + if (attempt > attemptCeiling) + return maxDelay; + const delay = minDelay * 2 ** (attempt - 1); + return randomInRange(minDelay, delay); +}, "exponentialBackoffWithJitter"); +var randomInRange = /* @__PURE__ */ __name((min, max) => min + Math.random() * (max - min), "randomInRange"); +var runPolling = /* @__PURE__ */ __name(async ({ minDelay, maxDelay, maxWaitTime, abortController, client, abortSignal }, input, acceptorChecks) => { + const observedResponses = {}; + const { state, reason } = await acceptorChecks(client, input); + if (reason) { + const message = createMessageFromResponse(reason); + observedResponses[message] |= 0; + observedResponses[message] += 1; } - static { - __name(this, "CredentialsProviderError"); + if (state !== "RETRY" /* RETRY */) { + return { state, reason, observedResponses }; } -}; - -// src/TokenProviderError.ts -var TokenProviderError = class _TokenProviderError extends ProviderError { - /** - * @override - */ - constructor(message, options = true) { - super(message, options); - this.name = "TokenProviderError"; - Object.setPrototypeOf(this, _TokenProviderError.prototype); + let currentAttempt = 1; + const waitUntil = Date.now() + maxWaitTime * 1e3; + const attemptCeiling = Math.log(maxDelay / minDelay) / Math.log(2) + 1; + while (true) { + if (abortController?.signal?.aborted || abortSignal?.aborted) { + const message = "AbortController signal aborted."; + observedResponses[message] |= 0; + observedResponses[message] += 1; + return { state: "ABORTED" /* ABORTED */, observedResponses }; + } + const delay = exponentialBackoffWithJitter(minDelay, maxDelay, attemptCeiling, currentAttempt); + if (Date.now() + delay * 1e3 > waitUntil) { + return { state: "TIMEOUT" /* TIMEOUT */, observedResponses }; + } + await sleep(delay); + const { state: state2, reason: reason2 } = await acceptorChecks(client, input); + if (reason2) { + const message = createMessageFromResponse(reason2); + observedResponses[message] |= 0; + observedResponses[message] += 1; + } + if (state2 !== "RETRY" /* RETRY */) { + return { state: state2, reason: reason2, observedResponses }; + } + currentAttempt += 1; } - static { - __name(this, "TokenProviderError"); +}, "runPolling"); +var createMessageFromResponse = /* @__PURE__ */ __name((reason) => { + if (reason?.$responseBodyText) { + return `Deserialization error for body: ${reason.$responseBodyText}`; } -}; + if (reason?.$metadata?.httpStatusCode) { + if (reason.$response || reason.message) { + return `${reason.$response.statusCode ?? reason.$metadata.httpStatusCode ?? "Unknown"}: ${reason.message}`; + } + return `${reason.$metadata.httpStatusCode}: OK`; + } + return String(reason?.message ?? JSON.stringify(reason) ?? "Unknown"); +}, "createMessageFromResponse"); -// src/chain.ts -var chain = /* @__PURE__ */ __name((...providers) => async () => { - if (providers.length === 0) { - throw new ProviderError("No providers in chain"); +// src/utils/validate.ts +var validateWaiterOptions = /* @__PURE__ */ __name((options) => { + if (options.maxWaitTime <= 0) { + throw new Error(`WaiterConfiguration.maxWaitTime must be greater than 0`); + } else if (options.minDelay <= 0) { + throw new Error(`WaiterConfiguration.minDelay must be greater than 0`); + } else if (options.maxDelay <= 0) { + throw new Error(`WaiterConfiguration.maxDelay must be greater than 0`); + } else if (options.maxWaitTime <= options.minDelay) { + throw new Error( + `WaiterConfiguration.maxWaitTime [${options.maxWaitTime}] must be greater than WaiterConfiguration.minDelay [${options.minDelay}] for this waiter` + ); + } else if (options.maxDelay < options.minDelay) { + throw new Error( + `WaiterConfiguration.maxDelay [${options.maxDelay}] must be greater than WaiterConfiguration.minDelay [${options.minDelay}] for this waiter` + ); } - let lastProviderError; - for (const provider of providers) { - try { - const credentials = await provider(); - return credentials; - } catch (err) { - lastProviderError = err; - if (err?.tryNextLink) { - continue; - } - throw err; +}, "validateWaiterOptions"); + +// src/createWaiter.ts +var abortTimeout = /* @__PURE__ */ __name(async (abortSignal) => { + return new Promise((resolve) => { + const onAbort = /* @__PURE__ */ __name(() => resolve({ state: "ABORTED" /* ABORTED */ }), "onAbort"); + if (typeof abortSignal.addEventListener === "function") { + abortSignal.addEventListener("abort", onAbort); + } else { + abortSignal.onabort = onAbort; } + }); +}, "abortTimeout"); +var createWaiter = /* @__PURE__ */ __name(async (options, input, acceptorChecks) => { + const params = { + ...waiterServiceDefaults, + ...options + }; + validateWaiterOptions(params); + const exitConditions = [runPolling(params, input, acceptorChecks)]; + if (options.abortController) { + exitConditions.push(abortTimeout(options.abortController.signal)); } - throw lastProviderError; -}, "chain"); + if (options.abortSignal) { + exitConditions.push(abortTimeout(options.abortSignal)); + } + return Promise.race(exitConditions); +}, "createWaiter"); +// Annotate the CommonJS export names for ESM import in node: -// src/fromStatic.ts -var fromStatic = /* @__PURE__ */ __name((staticValue) => () => Promise.resolve(staticValue), "fromStatic"); +0 && (0); -// src/memoize.ts -var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { - let resolved; - let pending; - let hasResult; - let isConstant = false; - const coalesceProvider = /* @__PURE__ */ __name(async () => { - if (!pending) { - pending = provider(); - } - try { - resolved = await pending; - hasResult = true; - isConstant = false; - } finally { - pending = void 0; + + +/***/ }), + +/***/ 48097: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const defer_to_connect_1 = __nccwpck_require__(96214); +const util_1 = __nccwpck_require__(73837); +const nodejsMajorVersion = Number(process.versions.node.split('.')[0]); +const timer = (request) => { + if (request.timings) { + return request.timings; } - return resolved; - }, "coalesceProvider"); - if (isExpired === void 0) { - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); - } - return resolved; + const timings = { + start: Date.now(), + socket: undefined, + lookup: undefined, + connect: undefined, + secureConnect: undefined, + upload: undefined, + response: undefined, + end: undefined, + error: undefined, + abort: undefined, + phases: { + wait: undefined, + dns: undefined, + tcp: undefined, + tls: undefined, + request: undefined, + firstByte: undefined, + download: undefined, + total: undefined + } }; - } - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); + request.timings = timings; + const handleError = (origin) => { + const emit = origin.emit.bind(origin); + origin.emit = (event, ...args) => { + // Catches the `error` event + if (event === 'error') { + timings.error = Date.now(); + timings.phases.total = timings.error - timings.start; + origin.emit = emit; + } + // Saves the original behavior + return emit(event, ...args); + }; + }; + handleError(request); + const onAbort = () => { + timings.abort = Date.now(); + // Let the `end` response event be responsible for setting the total phase, + // unless the Node.js major version is >= 13. + if (!timings.response || nodejsMajorVersion >= 13) { + timings.phases.total = Date.now() - timings.start; + } + }; + request.prependOnceListener('abort', onAbort); + const onSocket = (socket) => { + timings.socket = Date.now(); + timings.phases.wait = timings.socket - timings.start; + if (util_1.types.isProxy(socket)) { + return; + } + const lookupListener = () => { + timings.lookup = Date.now(); + timings.phases.dns = timings.lookup - timings.socket; + }; + socket.prependOnceListener('lookup', lookupListener); + defer_to_connect_1.default(socket, { + connect: () => { + timings.connect = Date.now(); + if (timings.lookup === undefined) { + socket.removeListener('lookup', lookupListener); + timings.lookup = timings.connect; + timings.phases.dns = timings.lookup - timings.socket; + } + timings.phases.tcp = timings.connect - timings.lookup; + // This callback is called before flushing any data, + // so we don't need to set `timings.phases.request` here. + }, + secureConnect: () => { + timings.secureConnect = Date.now(); + timings.phases.tls = timings.secureConnect - timings.connect; + } + }); + }; + if (request.socket) { + onSocket(request.socket); } - if (isConstant) { - return resolved; + else { + request.prependOnceListener('socket', onSocket); } - if (requiresRefresh && !requiresRefresh(resolved)) { - isConstant = true; - return resolved; + const onUpload = () => { + var _a; + timings.upload = Date.now(); + timings.phases.request = timings.upload - ((_a = timings.secureConnect) !== null && _a !== void 0 ? _a : timings.connect); + }; + const writableFinished = () => { + if (typeof request.writableFinished === 'boolean') { + return request.writableFinished; + } + // Node.js doesn't have `request.writableFinished` property + return request.finished && request.outputSize === 0 && (!request.socket || request.socket.writableLength === 0); + }; + if (writableFinished()) { + onUpload(); } - if (isExpired(resolved)) { - await coalesceProvider(); - return resolved; + else { + request.prependOnceListener('finish', onUpload); } - return resolved; - }; -}, "memoize"); -// Annotate the CommonJS export names for ESM import in node: + request.prependOnceListener('response', (response) => { + timings.response = Date.now(); + timings.phases.firstByte = timings.response - timings.upload; + response.timings = timings; + handleError(response); + response.prependOnceListener('end', () => { + timings.end = Date.now(); + timings.phases.download = timings.end - timings.response; + timings.phases.total = timings.end - timings.start; + }); + response.prependOnceListener('aborted', onAbort); + }); + return timings; +}; +exports["default"] = timer; +// For CommonJS default export support +module.exports = timer; +module.exports["default"] = timer; + + +/***/ }), + +/***/ 61231: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +const indentString = __nccwpck_require__(98043); +const cleanStack = __nccwpck_require__(27972); + +const cleanInternalStack = stack => stack.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, ''); + +class AggregateError extends Error { + constructor(errors) { + if (!Array.isArray(errors)) { + throw new TypeError(`Expected input to be an Array, got ${typeof errors}`); + } + + errors = [...errors].map(error => { + if (error instanceof Error) { + return error; + } + + if (error !== null && typeof error === 'object') { + // Handle plain error objects with message property and/or possibly other metadata + return Object.assign(new Error(error.message), error); + } + + return new Error(error); + }); + + let message = errors + .map(error => { + // The `stack` property is not standardized, so we can't assume it exists + return typeof error.stack === 'string' ? cleanInternalStack(cleanStack(error.stack)) : String(error); + }) + .join('\n'); + message = '\n' + indentString(message, 4); + super(message); + + this.name = 'AggregateError'; + + Object.defineProperty(this, '_errors', {value: errors}); + } + + * [Symbol.iterator]() { + for (const error of this._errors) { + yield error; + } + } +} + +module.exports = AggregateError; + + +/***/ }), + +/***/ 64941: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var compileSchema = __nccwpck_require__(875) + , resolve = __nccwpck_require__(63896) + , Cache = __nccwpck_require__(93679) + , SchemaObject = __nccwpck_require__(37605) + , stableStringify = __nccwpck_require__(30969) + , formats = __nccwpck_require__(66627) + , rules = __nccwpck_require__(68561) + , $dataMetaSchema = __nccwpck_require__(21412) + , util = __nccwpck_require__(76578); + +module.exports = Ajv; + +Ajv.prototype.validate = validate; +Ajv.prototype.compile = compile; +Ajv.prototype.addSchema = addSchema; +Ajv.prototype.addMetaSchema = addMetaSchema; +Ajv.prototype.validateSchema = validateSchema; +Ajv.prototype.getSchema = getSchema; +Ajv.prototype.removeSchema = removeSchema; +Ajv.prototype.addFormat = addFormat; +Ajv.prototype.errorsText = errorsText; + +Ajv.prototype._addSchema = _addSchema; +Ajv.prototype._compile = _compile; + +Ajv.prototype.compileAsync = __nccwpck_require__(80890); +var customKeyword = __nccwpck_require__(53297); +Ajv.prototype.addKeyword = customKeyword.add; +Ajv.prototype.getKeyword = customKeyword.get; +Ajv.prototype.removeKeyword = customKeyword.remove; +Ajv.prototype.validateKeyword = customKeyword.validate; + +var errorClasses = __nccwpck_require__(25726); +Ajv.ValidationError = errorClasses.Validation; +Ajv.MissingRefError = errorClasses.MissingRef; +Ajv.$dataMetaSchema = $dataMetaSchema; + +var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema'; + +var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ]; +var META_SUPPORT_DATA = ['/properties']; + +/** + * Creates validator instance. + * Usage: `Ajv(opts)` + * @param {Object} opts optional options + * @return {Object} ajv instance + */ +function Ajv(opts) { + if (!(this instanceof Ajv)) return new Ajv(opts); + opts = this._opts = util.copy(opts) || {}; + setLogger(this); + this._schemas = {}; + this._refs = {}; + this._fragments = {}; + this._formats = formats(opts.format); -0 && (0); + this._cache = opts.cache || new Cache; + this._loadingSchemas = {}; + this._compilations = []; + this.RULES = rules(); + this._getId = chooseGetId(opts); + opts.loopRequired = opts.loopRequired || Infinity; + if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true; + if (opts.serialize === undefined) opts.serialize = stableStringify; + this._metaOpts = getMetaSchemaOptions(this); + if (opts.formats) addInitialFormats(this); + if (opts.keywords) addInitialKeywords(this); + addDefaultMetaSchema(this); + if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta); + if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}}); + addInitialSchemas(this); +} -/***/ }), -/***/ 64418: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -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 }); +/** + * Validate data using schema + * Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize. + * @this Ajv + * @param {String|Object} schemaKeyRef key, ref or schema object + * @param {Any} data to be validated + * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`). + */ +function validate(schemaKeyRef, data) { + var v; + if (typeof schemaKeyRef == 'string') { + v = this.getSchema(schemaKeyRef); + if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"'); + } else { + var schemaObj = this._addSchema(schemaKeyRef); + v = schemaObj.validate || this._compile(schemaObj); } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - Field: () => Field, - Fields: () => Fields, - HttpRequest: () => HttpRequest, - HttpResponse: () => HttpResponse, - IHttpRequest: () => import_types.HttpRequest, - getHttpHandlerExtensionConfiguration: () => getHttpHandlerExtensionConfiguration, - isValidHostname: () => isValidHostname, - resolveHttpHandlerRuntimeConfig: () => resolveHttpHandlerRuntimeConfig -}); -module.exports = __toCommonJS(src_exports); -// src/extensions/httpExtensionConfiguration.ts -var getHttpHandlerExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return { - setHttpHandler(handler) { - runtimeConfig.httpHandler = handler; - }, - httpHandler() { - return runtimeConfig.httpHandler; - }, - updateHttpClientConfig(key, value) { - runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); - }, - httpHandlerConfigs() { - return runtimeConfig.httpHandler.httpHandlerConfigs(); - } - }; -}, "getHttpHandlerExtensionConfiguration"); -var resolveHttpHandlerRuntimeConfig = /* @__PURE__ */ __name((httpHandlerExtensionConfiguration) => { - return { - httpHandler: httpHandlerExtensionConfiguration.httpHandler() - }; -}, "resolveHttpHandlerRuntimeConfig"); + var valid = v(data); + if (v.$async !== true) this.errors = v.errors; + return valid; +} -// src/Field.ts -var import_types = __nccwpck_require__(55756); -var Field = class { - static { - __name(this, "Field"); - } - constructor({ name, kind = import_types.FieldPosition.HEADER, values = [] }) { - this.name = name; - this.kind = kind; - this.values = values; - } - /** - * Appends a value to the field. - * - * @param value The value to append. - */ - add(value) { - this.values.push(value); - } - /** - * Overwrite existing field values. - * - * @param values The new field values. - */ - set(values) { - this.values = values; - } - /** - * Remove all matching entries from list. - * - * @param value Value to remove. - */ - remove(value) { - this.values = this.values.filter((v) => v !== value); - } - /** - * Get comma-delimited string. - * - * @returns String representation of {@link Field}. - */ - toString() { - return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", "); - } - /** - * Get string values as a list - * - * @returns Values in {@link Field} as a list. - */ - get() { - return this.values; - } -}; -// src/Fields.ts -var Fields = class { - constructor({ fields = [], encoding = "utf-8" }) { - this.entries = {}; - fields.forEach(this.setField.bind(this)); - this.encoding = encoding; - } - static { - __name(this, "Fields"); - } - /** - * Set entry for a {@link Field} name. The `name` - * attribute will be used to key the collection. - * - * @param field The {@link Field} to set. - */ - setField(field) { - this.entries[field.name.toLowerCase()] = field; - } - /** - * Retrieve {@link Field} entry by name. - * - * @param name The name of the {@link Field} entry - * to retrieve - * @returns The {@link Field} if it exists. - */ - getField(name) { - return this.entries[name.toLowerCase()]; - } - /** - * Delete entry from collection. - * - * @param name Name of the entry to delete. - */ - removeField(name) { - delete this.entries[name.toLowerCase()]; - } - /** - * Helper function for retrieving specific types of fields. - * Used to grab all headers or all trailers. - * - * @param kind {@link FieldPosition} of entries to retrieve. - * @returns The {@link Field} entries with the specified - * {@link FieldPosition}. - */ - getByType(kind) { - return Object.values(this.entries).filter((field) => field.kind === kind); - } -}; +/** + * Create validating function for passed schema. + * @this Ajv + * @param {Object} schema schema object + * @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords. + * @return {Function} validating function + */ +function compile(schema, _meta) { + var schemaObj = this._addSchema(schema, undefined, _meta); + return schemaObj.validate || this._compile(schemaObj); +} -// src/httpRequest.ts -var HttpRequest = class _HttpRequest { - static { - __name(this, "HttpRequest"); - } - constructor(options) { - this.method = options.method || "GET"; - this.hostname = options.hostname || "localhost"; - this.port = options.port; - this.query = options.query || {}; - this.headers = options.headers || {}; - this.body = options.body; - this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:"; - this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/"; - this.username = options.username; - this.password = options.password; - this.fragment = options.fragment; - } - /** - * Note: this does not deep-clone the body. - */ - static clone(request) { - const cloned = new _HttpRequest({ - ...request, - headers: { ...request.headers } - }); - if (cloned.query) { - cloned.query = cloneQuery(cloned.query); - } - return cloned; - } - /** - * This method only actually asserts that request is the interface {@link IHttpRequest}, - * and not necessarily this concrete class. Left in place for API stability. - * - * Do not call instance methods on the input of this function, and - * do not assume it has the HttpRequest prototype. - */ - static isInstance(request) { - if (!request) { - return false; - } - const req = request; - return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object"; - } - /** - * @deprecated use static HttpRequest.clone(request) instead. It's not safe to call - * this method because {@link HttpRequest.isInstance} incorrectly - * asserts that IHttpRequest (interface) objects are of type HttpRequest (class). - */ - clone() { - return _HttpRequest.clone(this); +/** + * Adds schema to the instance. + * @this Ajv + * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored. + * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. + * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead. + * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. + * @return {Ajv} this for method chaining + */ +function addSchema(schema, key, _skipValidation, _meta) { + if (Array.isArray(schema)){ + for (var i=0; i { - const param = query[paramName]; - return { - ...carry, - [paramName]: Array.isArray(param) ? [...param] : param - }; - }, {}); + var id = this._getId(schema); + if (id !== undefined && typeof id != 'string') + throw new Error('schema id must be string'); + key = resolve.normalizeId(key || id); + checkUnique(this, key); + this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true); + return this; } -__name(cloneQuery, "cloneQuery"); -// src/httpResponse.ts -var HttpResponse = class { - static { - __name(this, "HttpResponse"); - } - constructor(options) { - this.statusCode = options.statusCode; - this.reason = options.reason; - this.headers = options.headers || {}; - this.body = options.body; - } - static isInstance(response) { - if (!response) - return false; - const resp = response; - return typeof resp.statusCode === "number" && typeof resp.headers === "object"; - } -}; -// src/isValidHostname.ts -function isValidHostname(hostname) { - const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; - return hostPattern.test(hostname); +/** + * Add schema that will be used to validate other schemas + * options in META_IGNORE_OPTIONS are alway set to false + * @this Ajv + * @param {Object} schema schema object + * @param {String} key optional schema key + * @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema + * @return {Ajv} this for method chaining + */ +function addMetaSchema(schema, key, skipValidation) { + this.addSchema(schema, key, skipValidation, true); + return this; } -__name(isValidHostname, "isValidHostname"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); +/** + * Validate schema + * @this Ajv + * @param {Object} schema schema to validate + * @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid + * @return {Boolean} true if schema is valid + */ +function validateSchema(schema, throwOrLogError) { + var $schema = schema.$schema; + if ($schema !== undefined && typeof $schema != 'string') + throw new Error('$schema must be a string'); + $schema = $schema || this._opts.defaultMeta || defaultMeta(this); + if (!$schema) { + this.logger.warn('meta-schema not available'); + this.errors = null; + return true; + } + var valid = this.validate($schema, schema); + if (!valid && throwOrLogError) { + var message = 'schema is invalid: ' + this.errorsText(); + if (this._opts.validateSchema == 'log') this.logger.error(message); + else throw new Error(message); + } + return valid; +} -/***/ }), -/***/ 68031: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function defaultMeta(self) { + var meta = self._opts.meta; + self._opts.defaultMeta = typeof meta == 'object' + ? self._getId(meta) || meta + : self.getSchema(META_SCHEMA_ID) + ? META_SCHEMA_ID + : undefined; + return self._opts.defaultMeta; +} -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -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); -// src/index.ts -var src_exports = {}; -__export(src_exports, { - buildQueryString: () => buildQueryString -}); -module.exports = __toCommonJS(src_exports); -var import_util_uri_escape = __nccwpck_require__(54197); -function buildQueryString(query) { - const parts = []; - for (let key of Object.keys(query).sort()) { - const value = query[key]; - key = (0, import_util_uri_escape.escapeUri)(key); - if (Array.isArray(value)) { - for (let i = 0, iLen = value.length; i < iLen; i++) { - parts.push(`${key}=${(0, import_util_uri_escape.escapeUri)(value[i])}`); - } - } else { - let qsEntry = key; - if (value || typeof value === "string") { - qsEntry += `=${(0, import_util_uri_escape.escapeUri)(value)}`; - } - parts.push(qsEntry); - } +/** + * Get compiled schema from the instance by `key` or `ref`. + * @this Ajv + * @param {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id). + * @return {Function} schema validating function (with property `schema`). + */ +function getSchema(keyRef) { + var schemaObj = _getSchemaObj(this, keyRef); + switch (typeof schemaObj) { + case 'object': return schemaObj.validate || this._compile(schemaObj); + case 'string': return this.getSchema(schemaObj); + case 'undefined': return _getSchemaFragment(this, keyRef); } - return parts.join("&"); } -__name(buildQueryString, "buildQueryString"); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +function _getSchemaFragment(self, ref) { + var res = resolve.schema.call(self, { schema: {} }, ref); + if (res) { + var schema = res.schema + , root = res.root + , baseId = res.baseId; + var v = compileSchema.call(self, schema, root, undefined, baseId); + self._fragments[ref] = new SchemaObject({ + ref: ref, + fragment: true, + schema: schema, + root: root, + baseId: baseId, + validate: v + }); + return v; + } +} -/***/ }), +function _getSchemaObj(self, keyRef) { + keyRef = resolve.normalizeId(keyRef); + return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef]; +} -/***/ 4769: -/***/ ((module) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -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 }); +/** + * Remove cached schema(s). + * If no parameter is passed all schemas but meta-schemas are removed. + * If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. + * Even if schema is referenced by other schemas it still can be removed as other schemas have local references. + * @this Ajv + * @param {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object + * @return {Ajv} this for method chaining + */ +function removeSchema(schemaKeyRef) { + if (schemaKeyRef instanceof RegExp) { + _removeAllSchemas(this, this._schemas, schemaKeyRef); + _removeAllSchemas(this, this._refs, schemaKeyRef); + return this; } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - parseQueryString: () => parseQueryString -}); -module.exports = __toCommonJS(src_exports); -function parseQueryString(querystring) { - const query = {}; - querystring = querystring.replace(/^\?/, ""); - if (querystring) { - for (const pair of querystring.split("&")) { - let [key, value = null] = pair.split("="); - key = decodeURIComponent(key); - if (value) { - value = decodeURIComponent(value); - } - if (!(key in query)) { - query[key] = value; - } else if (Array.isArray(query[key])) { - query[key].push(value); - } else { - query[key] = [query[key], value]; + switch (typeof schemaKeyRef) { + case 'undefined': + _removeAllSchemas(this, this._schemas); + _removeAllSchemas(this, this._refs); + this._cache.clear(); + return this; + case 'string': + var schemaObj = _getSchemaObj(this, schemaKeyRef); + if (schemaObj) this._cache.del(schemaObj.cacheKey); + delete this._schemas[schemaKeyRef]; + delete this._refs[schemaKeyRef]; + return this; + case 'object': + var serialize = this._opts.serialize; + var cacheKey = serialize ? serialize(schemaKeyRef) : schemaKeyRef; + this._cache.del(cacheKey); + var id = this._getId(schemaKeyRef); + if (id) { + id = resolve.normalizeId(id); + delete this._schemas[id]; + delete this._refs[id]; } + } + return this; +} + + +function _removeAllSchemas(self, schemas, regex) { + for (var keyRef in schemas) { + var schemaObj = schemas[keyRef]; + if (!schemaObj.meta && (!regex || regex.test(keyRef))) { + self._cache.del(schemaObj.cacheKey); + delete schemas[keyRef]; } } - return query; } -__name(parseQueryString, "parseQueryString"); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +/* @this Ajv */ +function _addSchema(schema, skipValidation, meta, shouldAddSchema) { + if (typeof schema != 'object' && typeof schema != 'boolean') + throw new Error('schema should be object or boolean'); + var serialize = this._opts.serialize; + var cacheKey = serialize ? serialize(schema) : schema; + var cached = this._cache.get(cacheKey); + if (cached) return cached; + shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false; -/***/ }), + var id = resolve.normalizeId(this._getId(schema)); + if (id && shouldAddSchema) checkUnique(this, id); -/***/ 6375: -/***/ ((module) => { + var willValidate = this._opts.validateSchema !== false && !skipValidation; + var recursiveMeta; + if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema))) + this.validateSchema(schema, true); -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -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); + var localRefs = resolve.ids.call(this, schema); -// src/index.ts -var src_exports = {}; -__export(src_exports, { - isClockSkewCorrectedError: () => isClockSkewCorrectedError, - isClockSkewError: () => isClockSkewError, - isRetryableByTrait: () => isRetryableByTrait, - isServerError: () => isServerError, - isThrottlingError: () => isThrottlingError, - isTransientError: () => isTransientError -}); -module.exports = __toCommonJS(src_exports); + var schemaObj = new SchemaObject({ + id: id, + schema: schema, + localRefs: localRefs, + cacheKey: cacheKey, + meta: meta + }); -// src/constants.ts -var CLOCK_SKEW_ERROR_CODES = [ - "AuthFailure", - "InvalidSignatureException", - "RequestExpired", - "RequestInTheFuture", - "RequestTimeTooSkewed", - "SignatureDoesNotMatch" -]; -var THROTTLING_ERROR_CODES = [ - "BandwidthLimitExceeded", - "EC2ThrottledException", - "LimitExceededException", - "PriorRequestNotComplete", - "ProvisionedThroughputExceededException", - "RequestLimitExceeded", - "RequestThrottled", - "RequestThrottledException", - "SlowDown", - "ThrottledException", - "Throttling", - "ThrottlingException", - "TooManyRequestsException", - "TransactionInProgressException" - // DynamoDB -]; -var TRANSIENT_ERROR_CODES = ["TimeoutError", "RequestTimeout", "RequestTimeoutException"]; -var TRANSIENT_ERROR_STATUS_CODES = [500, 502, 503, 504]; -var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT"]; + if (id[0] != '#' && shouldAddSchema) this._refs[id] = schemaObj; + this._cache.put(cacheKey, schemaObj); -// src/index.ts -var isRetryableByTrait = /* @__PURE__ */ __name((error) => error.$retryable !== void 0, "isRetryableByTrait"); -var isClockSkewError = /* @__PURE__ */ __name((error) => CLOCK_SKEW_ERROR_CODES.includes(error.name), "isClockSkewError"); -var isClockSkewCorrectedError = /* @__PURE__ */ __name((error) => error.$metadata?.clockSkewCorrected, "isClockSkewCorrectedError"); -var isThrottlingError = /* @__PURE__ */ __name((error) => error.$metadata?.httpStatusCode === 429 || THROTTLING_ERROR_CODES.includes(error.name) || error.$retryable?.throttling == true, "isThrottlingError"); -var isTransientError = /* @__PURE__ */ __name((error, depth = 0) => isClockSkewCorrectedError(error) || TRANSIENT_ERROR_CODES.includes(error.name) || NODEJS_TIMEOUT_ERROR_CODES.includes(error?.code || "") || TRANSIENT_ERROR_STATUS_CODES.includes(error.$metadata?.httpStatusCode || 0) || error.cause !== void 0 && depth <= 10 && isTransientError(error.cause, depth + 1), "isTransientError"); -var isServerError = /* @__PURE__ */ __name((error) => { - if (error.$metadata?.httpStatusCode !== void 0) { - const statusCode = error.$metadata.httpStatusCode; - if (500 <= statusCode && statusCode <= 599 && !isTransientError(error)) { - return true; - } - return false; - } - return false; -}, "isServerError"); -// Annotate the CommonJS export names for ESM import in node: + if (willValidate && recursiveMeta) this.validateSchema(schema, true); -0 && (0); + return schemaObj; +} +/* @this Ajv */ +function _compile(schemaObj, root) { + if (schemaObj.compiling) { + schemaObj.validate = callValidate; + callValidate.schema = schemaObj.schema; + callValidate.errors = null; + callValidate.root = root ? root : callValidate; + if (schemaObj.schema.$async === true) + callValidate.$async = true; + return callValidate; + } + schemaObj.compiling = true; -/***/ }), + var currentOpts; + if (schemaObj.meta) { + currentOpts = this._opts; + this._opts = this._metaOpts; + } -/***/ 68340: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + var v; + try { v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs); } + catch(e) { + delete schemaObj.validate; + throw e; + } + finally { + schemaObj.compiling = false; + if (schemaObj.meta) this._opts = currentOpts; + } -"use strict"; + schemaObj.validate = v; + schemaObj.refs = v.refs; + schemaObj.refVal = v.refVal; + schemaObj.root = v.root; + return v; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getHomeDir = void 0; -const os_1 = __nccwpck_require__(22037); -const path_1 = __nccwpck_require__(71017); -const homeDirCache = {}; -const getHomeDirCacheKey = () => { - if (process && process.geteuid) { - return `${process.geteuid()}`; - } - return "DEFAULT"; -}; -const getHomeDir = () => { - const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${path_1.sep}` } = process.env; - if (HOME) - return HOME; - if (USERPROFILE) - return USERPROFILE; - if (HOMEPATH) - return `${HOMEDRIVE}${HOMEPATH}`; - const homeDirCacheKey = getHomeDirCacheKey(); - if (!homeDirCache[homeDirCacheKey]) - homeDirCache[homeDirCacheKey] = (0, os_1.homedir)(); - return homeDirCache[homeDirCacheKey]; -}; -exports.getHomeDir = getHomeDir; + /* @this {*} - custom context, see passContext option */ + function callValidate() { + /* jshint validthis: true */ + var _validate = schemaObj.validate; + var result = _validate.apply(this, arguments); + callValidate.errors = _validate.errors; + return result; + } +} -/***/ }), -/***/ 24740: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function chooseGetId(opts) { + switch (opts.schemaId) { + case 'auto': return _get$IdOrId; + case 'id': return _getId; + default: return _get$Id; + } +} -"use strict"; +/* @this Ajv */ +function _getId(schema) { + if (schema.$id) this.logger.warn('schema $id ignored', schema.$id); + return schema.id; +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getSSOTokenFilepath = void 0; -const crypto_1 = __nccwpck_require__(6113); -const path_1 = __nccwpck_require__(71017); -const getHomeDir_1 = __nccwpck_require__(68340); -const getSSOTokenFilepath = (id) => { - const hasher = (0, crypto_1.createHash)("sha1"); - const cacheName = hasher.update(id).digest("hex"); - return (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "sso", "cache", `${cacheName}.json`); -}; -exports.getSSOTokenFilepath = getSSOTokenFilepath; +/* @this Ajv */ +function _get$Id(schema) { + if (schema.id) this.logger.warn('schema id ignored', schema.id); + return schema.$id; +} -/***/ }), +function _get$IdOrId(schema) { + if (schema.$id && schema.id && schema.$id != schema.id) + throw new Error('schema $id is different from id'); + return schema.$id || schema.id; +} -/***/ 69678: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +/** + * Convert array of error message objects to string + * @this Ajv + * @param {Array} errors optional array of validation errors, if not passed errors from the instance are used. + * @param {Object} options optional options with properties `separator` and `dataVar`. + * @return {String} human readable string with all errors descriptions + */ +function errorsText(errors, options) { + errors = errors || this.errors; + if (!errors) return 'No errors'; + options = options || {}; + var separator = options.separator === undefined ? ', ' : options.separator; + var dataVar = options.dataVar === undefined ? 'data' : options.dataVar; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getSSOTokenFromFile = void 0; -const fs_1 = __nccwpck_require__(57147); -const getSSOTokenFilepath_1 = __nccwpck_require__(24740); -const { readFile } = fs_1.promises; -const getSSOTokenFromFile = async (id) => { - const ssoTokenFilepath = (0, getSSOTokenFilepath_1.getSSOTokenFilepath)(id); - const ssoTokenText = await readFile(ssoTokenFilepath, "utf8"); - return JSON.parse(ssoTokenText); -}; -exports.getSSOTokenFromFile = getSSOTokenFromFile; + var text = ''; + for (var i=0; i { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -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 }); +function addDefaultMetaSchema(self) { + var $dataSchema; + if (self._opts.$data) { + $dataSchema = __nccwpck_require__(894); + self.addMetaSchema($dataSchema, $dataSchema.$id, true); } - return to; -}; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + if (self._opts.meta === false) return; + var metaSchema = __nccwpck_require__(6680); + if (self._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA); + self.addMetaSchema(metaSchema, META_SCHEMA_ID, true); + self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID; +} -// src/index.ts -var src_exports = {}; -__export(src_exports, { - CONFIG_PREFIX_SEPARATOR: () => CONFIG_PREFIX_SEPARATOR, - DEFAULT_PROFILE: () => DEFAULT_PROFILE, - ENV_PROFILE: () => ENV_PROFILE, - getProfileName: () => getProfileName, - loadSharedConfigFiles: () => loadSharedConfigFiles, - loadSsoSessionData: () => loadSsoSessionData, - parseKnownFiles: () => parseKnownFiles -}); -module.exports = __toCommonJS(src_exports); -__reExport(src_exports, __nccwpck_require__(68340), module.exports); -// src/getProfileName.ts -var ENV_PROFILE = "AWS_PROFILE"; -var DEFAULT_PROFILE = "default"; -var getProfileName = /* @__PURE__ */ __name((init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE, "getProfileName"); +function addInitialSchemas(self) { + var optsSchemas = self._opts.schemas; + if (!optsSchemas) return; + if (Array.isArray(optsSchemas)) self.addSchema(optsSchemas); + else for (var key in optsSchemas) self.addSchema(optsSchemas[key], key); +} -// src/index.ts -__reExport(src_exports, __nccwpck_require__(24740), module.exports); -__reExport(src_exports, __nccwpck_require__(69678), module.exports); -// src/loadSharedConfigFiles.ts +function addInitialFormats(self) { + for (var name in self._opts.formats) { + var format = self._opts.formats[name]; + self.addFormat(name, format); + } +} -// src/getConfigData.ts -var import_types = __nccwpck_require__(55756); -var getConfigData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => { - const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); - if (indexOfSeparator === -1) { - return false; - } - return Object.values(import_types.IniSectionType).includes(key.substring(0, indexOfSeparator)); -}).reduce( - (acc, [key, value]) => { - const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); - const updatedKey = key.substring(0, indexOfSeparator) === import_types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; - acc[updatedKey] = value; - return acc; - }, - { - // Populate default profile, if present. - ...data.default && { default: data.default } +function addInitialKeywords(self) { + for (var name in self._opts.keywords) { + var keyword = self._opts.keywords[name]; + self.addKeyword(name, keyword); } -), "getConfigData"); +} -// src/getConfigFilepath.ts -var import_path = __nccwpck_require__(71017); -var import_getHomeDir = __nccwpck_require__(68340); -var ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; -var getConfigFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CONFIG_PATH] || (0, import_path.join)((0, import_getHomeDir.getHomeDir)(), ".aws", "config"), "getConfigFilepath"); -// src/getCredentialsFilepath.ts +function checkUnique(self, id) { + if (self._schemas[id] || self._refs[id]) + throw new Error('schema with key or id "' + id + '" already exists'); +} -var import_getHomeDir2 = __nccwpck_require__(68340); -var ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; -var getCredentialsFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CREDENTIALS_PATH] || (0, import_path.join)((0, import_getHomeDir2.getHomeDir)(), ".aws", "credentials"), "getCredentialsFilepath"); -// src/loadSharedConfigFiles.ts -var import_getHomeDir3 = __nccwpck_require__(68340); +function getMetaSchemaOptions(self) { + var metaOpts = util.copy(self._opts); + for (var i=0; i { - const map = {}; - let currentSection; - let currentSubSection; - for (const iniLine of iniData.split(/\r?\n/)) { - const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); - const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; - if (isSection) { - currentSection = void 0; - currentSubSection = void 0; - const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); - const matches = prefixKeyRegex.exec(sectionName); - if (matches) { - const [, prefix, , name] = matches; - if (Object.values(import_types.IniSectionType).includes(prefix)) { - currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR); - } - } else { - currentSection = sectionName; - } - if (profileNameBlockList.includes(sectionName)) { - throw new Error(`Found invalid profile name "${sectionName}"`); - } - } else if (currentSection) { - const indexOfEqualsSign = trimmedLine.indexOf("="); - if (![0, -1].includes(indexOfEqualsSign)) { - const [name, value] = [ - trimmedLine.substring(0, indexOfEqualsSign).trim(), - trimmedLine.substring(indexOfEqualsSign + 1).trim() - ]; - if (value === "") { - currentSubSection = name; - } else { - if (currentSubSection && iniLine.trimStart() === iniLine) { - currentSubSection = void 0; - } - map[currentSection] = map[currentSection] || {}; - const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; - map[currentSection][key] = value; - } - } - } +function setLogger(self) { + var logger = self._opts.logger; + if (logger === false) { + self.logger = {log: noop, warn: noop, error: noop}; + } else { + if (logger === undefined) logger = console; + if (!(typeof logger == 'object' && logger.log && logger.warn && logger.error)) + throw new Error('logger must implement log, warn and error methods'); + self.logger = logger; } - return map; -}, "parseIni"); +} -// src/loadSharedConfigFiles.ts -var import_slurpFile = __nccwpck_require__(19155); -var swallowError = /* @__PURE__ */ __name(() => ({}), "swallowError"); -var CONFIG_PREFIX_SEPARATOR = "."; -var loadSharedConfigFiles = /* @__PURE__ */ __name(async (init = {}) => { - const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init; - const homeDir = (0, import_getHomeDir3.getHomeDir)(); - const relativeHomeDirPrefix = "~/"; - let resolvedFilepath = filepath; - if (filepath.startsWith(relativeHomeDirPrefix)) { - resolvedFilepath = (0, import_path.join)(homeDir, filepath.slice(2)); - } - let resolvedConfigFilepath = configFilepath; - if (configFilepath.startsWith(relativeHomeDirPrefix)) { - resolvedConfigFilepath = (0, import_path.join)(homeDir, configFilepath.slice(2)); - } - const parsedFiles = await Promise.all([ - (0, import_slurpFile.slurpFile)(resolvedConfigFilepath, { - ignoreCache: init.ignoreCache - }).then(parseIni).then(getConfigData).catch(swallowError), - (0, import_slurpFile.slurpFile)(resolvedFilepath, { - ignoreCache: init.ignoreCache - }).then(parseIni).catch(swallowError) - ]); - return { - configFile: parsedFiles[0], - credentialsFile: parsedFiles[1] - }; -}, "loadSharedConfigFiles"); -// src/getSsoSessionData.ts +function noop() {} -var getSsoSessionData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => key.startsWith(import_types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}), "getSsoSessionData"); -// src/loadSsoSessionData.ts -var import_slurpFile2 = __nccwpck_require__(19155); -var swallowError2 = /* @__PURE__ */ __name(() => ({}), "swallowError"); -var loadSsoSessionData = /* @__PURE__ */ __name(async (init = {}) => (0, import_slurpFile2.slurpFile)(init.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError2), "loadSsoSessionData"); +/***/ }), -// src/mergeConfigFiles.ts -var mergeConfigFiles = /* @__PURE__ */ __name((...files) => { - const merged = {}; - for (const file of files) { - for (const [key, values] of Object.entries(file)) { - if (merged[key] !== void 0) { - Object.assign(merged[key], values); - } else { - merged[key] = values; - } - } - } - return merged; -}, "mergeConfigFiles"); +/***/ 93679: +/***/ ((module) => { + +"use strict"; + + + +var Cache = module.exports = function Cache() { + this._cache = {}; +}; -// src/parseKnownFiles.ts -var parseKnownFiles = /* @__PURE__ */ __name(async (init) => { - const parsedFiles = await loadSharedConfigFiles(init); - return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); -}, "parseKnownFiles"); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +Cache.prototype.put = function Cache_put(key, value) { + this._cache[key] = value; +}; +Cache.prototype.get = function Cache_get(key) { + return this._cache[key]; +}; -/***/ }), -/***/ 19155: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Cache.prototype.del = function Cache_del(key) { + delete this._cache[key]; +}; -"use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.slurpFile = void 0; -const fs_1 = __nccwpck_require__(57147); -const { readFile } = fs_1.promises; -const filePromisesHash = {}; -const slurpFile = (path, options) => { - if (!filePromisesHash[path] || (options === null || options === void 0 ? void 0 : options.ignoreCache)) { - filePromisesHash[path] = readFile(path, "utf8"); - } - return filePromisesHash[path]; +Cache.prototype.clear = function Cache_clear() { + this._cache = {}; }; -exports.slurpFile = slurpFile; /***/ }), -/***/ 11528: +/***/ 80890: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -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); +"use strict"; -// src/index.ts -var src_exports = {}; -__export(src_exports, { - SignatureV4: () => SignatureV4, - clearCredentialCache: () => clearCredentialCache, - createScope: () => createScope, - getCanonicalHeaders: () => getCanonicalHeaders, - getCanonicalQuery: () => getCanonicalQuery, - getPayloadHash: () => getPayloadHash, - getSigningKey: () => getSigningKey, - moveHeadersToQuery: () => moveHeadersToQuery, - prepareRequest: () => prepareRequest -}); -module.exports = __toCommonJS(src_exports); -// src/SignatureV4.ts +var MissingRefError = (__nccwpck_require__(25726).MissingRef); -var import_util_middleware = __nccwpck_require__(2390); +module.exports = compileAsync; -var import_util_utf84 = __nccwpck_require__(41895); -// src/constants.ts -var ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm"; -var CREDENTIAL_QUERY_PARAM = "X-Amz-Credential"; -var AMZ_DATE_QUERY_PARAM = "X-Amz-Date"; -var SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders"; -var EXPIRES_QUERY_PARAM = "X-Amz-Expires"; -var SIGNATURE_QUERY_PARAM = "X-Amz-Signature"; -var TOKEN_QUERY_PARAM = "X-Amz-Security-Token"; -var AUTH_HEADER = "authorization"; -var AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase(); -var DATE_HEADER = "date"; -var GENERATED_HEADERS = [AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER]; -var SIGNATURE_HEADER = SIGNATURE_QUERY_PARAM.toLowerCase(); -var SHA256_HEADER = "x-amz-content-sha256"; -var TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase(); -var ALWAYS_UNSIGNABLE_HEADERS = { - authorization: true, - "cache-control": true, - connection: true, - expect: true, - from: true, - "keep-alive": true, - "max-forwards": true, - pragma: true, - referer: true, - te: true, - trailer: true, - "transfer-encoding": true, - upgrade: true, - "user-agent": true, - "x-amzn-trace-id": true -}; -var PROXY_HEADER_PATTERN = /^proxy-/; -var SEC_HEADER_PATTERN = /^sec-/; -var ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256"; -var EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD"; -var UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD"; -var MAX_CACHE_SIZE = 50; -var KEY_TYPE_IDENTIFIER = "aws4_request"; -var MAX_PRESIGNED_TTL = 60 * 60 * 24 * 7; +/** + * Creates validating function for passed schema with asynchronous loading of missing schemas. + * `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema. + * @this Ajv + * @param {Object} schema schema object + * @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped + * @param {Function} callback an optional node-style callback, it is called with 2 parameters: error (or null) and validating function. + * @return {Promise} promise that resolves with a validating function. + */ +function compileAsync(schema, meta, callback) { + /* eslint no-shadow: 0 */ + /* global Promise */ + /* jshint validthis: true */ + var self = this; + if (typeof this._opts.loadSchema != 'function') + throw new Error('options.loadSchema should be a function'); -// src/credentialDerivation.ts -var import_util_hex_encoding = __nccwpck_require__(45364); -var import_util_utf8 = __nccwpck_require__(41895); -var signingKeyCache = {}; -var cacheQueue = []; -var createScope = /* @__PURE__ */ __name((shortDate, region, service) => `${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`, "createScope"); -var getSigningKey = /* @__PURE__ */ __name(async (sha256Constructor, credentials, shortDate, region, service) => { - const credsHash = await hmac(sha256Constructor, credentials.secretAccessKey, credentials.accessKeyId); - const cacheKey = `${shortDate}:${region}:${service}:${(0, import_util_hex_encoding.toHex)(credsHash)}:${credentials.sessionToken}`; - if (cacheKey in signingKeyCache) { - return signingKeyCache[cacheKey]; - } - cacheQueue.push(cacheKey); - while (cacheQueue.length > MAX_CACHE_SIZE) { - delete signingKeyCache[cacheQueue.shift()]; - } - let key = `AWS4${credentials.secretAccessKey}`; - for (const signable of [shortDate, region, service, KEY_TYPE_IDENTIFIER]) { - key = await hmac(sha256Constructor, key, signable); + if (typeof meta == 'function') { + callback = meta; + meta = undefined; } - return signingKeyCache[cacheKey] = key; -}, "getSigningKey"); -var clearCredentialCache = /* @__PURE__ */ __name(() => { - cacheQueue.length = 0; - Object.keys(signingKeyCache).forEach((cacheKey) => { - delete signingKeyCache[cacheKey]; + + var p = loadMetaSchemaOf(schema).then(function () { + var schemaObj = self._addSchema(schema, undefined, meta); + return schemaObj.validate || _compileAsync(schemaObj); }); -}, "clearCredentialCache"); -var hmac = /* @__PURE__ */ __name((ctor, secret, data) => { - const hash = new ctor(secret); - hash.update((0, import_util_utf8.toUint8Array)(data)); - return hash.digest(); -}, "hmac"); -// src/getCanonicalHeaders.ts -var getCanonicalHeaders = /* @__PURE__ */ __name(({ headers }, unsignableHeaders, signableHeaders) => { - const canonical = {}; - for (const headerName of Object.keys(headers).sort()) { - if (headers[headerName] == void 0) { - continue; - } - const canonicalHeaderName = headerName.toLowerCase(); - if (canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS || unsignableHeaders?.has(canonicalHeaderName) || PROXY_HEADER_PATTERN.test(canonicalHeaderName) || SEC_HEADER_PATTERN.test(canonicalHeaderName)) { - if (!signableHeaders || signableHeaders && !signableHeaders.has(canonicalHeaderName)) { - continue; - } - } - canonical[canonicalHeaderName] = headers[headerName].trim().replace(/\s+/g, " "); + if (callback) { + p.then( + function(v) { callback(null, v); }, + callback + ); } - return canonical; -}, "getCanonicalHeaders"); -// src/getCanonicalQuery.ts -var import_util_uri_escape = __nccwpck_require__(54197); -var getCanonicalQuery = /* @__PURE__ */ __name(({ query = {} }) => { - const keys = []; - const serialized = {}; - for (const key of Object.keys(query)) { - if (key.toLowerCase() === SIGNATURE_HEADER) { - continue; - } - const encodedKey = (0, import_util_uri_escape.escapeUri)(key); - keys.push(encodedKey); - const value = query[key]; - if (typeof value === "string") { - serialized[encodedKey] = `${encodedKey}=${(0, import_util_uri_escape.escapeUri)(value)}`; - } else if (Array.isArray(value)) { - serialized[encodedKey] = value.slice(0).reduce((encoded, value2) => encoded.concat([`${encodedKey}=${(0, import_util_uri_escape.escapeUri)(value2)}`]), []).sort().join("&"); - } - } - return keys.sort().map((key) => serialized[key]).filter((serialized2) => serialized2).join("&"); -}, "getCanonicalQuery"); + return p; -// src/getPayloadHash.ts -var import_is_array_buffer = __nccwpck_require__(10780); -var import_util_utf82 = __nccwpck_require__(41895); -var getPayloadHash = /* @__PURE__ */ __name(async ({ headers, body }, hashConstructor) => { - for (const headerName of Object.keys(headers)) { - if (headerName.toLowerCase() === SHA256_HEADER) { - return headers[headerName]; - } - } - if (body == void 0) { - return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; - } else if (typeof body === "string" || ArrayBuffer.isView(body) || (0, import_is_array_buffer.isArrayBuffer)(body)) { - const hashCtor = new hashConstructor(); - hashCtor.update((0, import_util_utf82.toUint8Array)(body)); - return (0, import_util_hex_encoding.toHex)(await hashCtor.digest()); + function loadMetaSchemaOf(sch) { + var $schema = sch.$schema; + return $schema && !self.getSchema($schema) + ? compileAsync.call(self, { $ref: $schema }, true) + : Promise.resolve(); } - return UNSIGNED_PAYLOAD; -}, "getPayloadHash"); -// src/HeaderFormatter.ts -var import_util_utf83 = __nccwpck_require__(41895); -var HeaderFormatter = class { - static { - __name(this, "HeaderFormatter"); - } - format(headers) { - const chunks = []; - for (const headerName of Object.keys(headers)) { - const bytes = (0, import_util_utf83.fromUtf8)(headerName); - chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName])); - } - const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0)); - let position = 0; - for (const chunk of chunks) { - out.set(chunk, position); - position += chunk.byteLength; + function _compileAsync(schemaObj) { + try { return self._compile(schemaObj); } + catch(e) { + if (e instanceof MissingRefError) return loadMissingSchema(e); + throw e; } - return out; - } - formatHeaderValue(header) { - switch (header.type) { - case "boolean": - return Uint8Array.from([header.value ? 0 /* boolTrue */ : 1 /* boolFalse */]); - case "byte": - return Uint8Array.from([2 /* byte */, header.value]); - case "short": - const shortView = new DataView(new ArrayBuffer(3)); - shortView.setUint8(0, 3 /* short */); - shortView.setInt16(1, header.value, false); - return new Uint8Array(shortView.buffer); - case "integer": - const intView = new DataView(new ArrayBuffer(5)); - intView.setUint8(0, 4 /* integer */); - intView.setInt32(1, header.value, false); - return new Uint8Array(intView.buffer); - case "long": - const longBytes = new Uint8Array(9); - longBytes[0] = 5 /* long */; - longBytes.set(header.value.bytes, 1); - return longBytes; - case "binary": - const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); - binView.setUint8(0, 6 /* byteArray */); - binView.setUint16(1, header.value.byteLength, false); - const binBytes = new Uint8Array(binView.buffer); - binBytes.set(header.value, 3); - return binBytes; - case "string": - const utf8Bytes = (0, import_util_utf83.fromUtf8)(header.value); - const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); - strView.setUint8(0, 7 /* string */); - strView.setUint16(1, utf8Bytes.byteLength, false); - const strBytes = new Uint8Array(strView.buffer); - strBytes.set(utf8Bytes, 3); - return strBytes; - case "timestamp": - const tsBytes = new Uint8Array(9); - tsBytes[0] = 8 /* timestamp */; - tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1); - return tsBytes; - case "uuid": - if (!UUID_PATTERN.test(header.value)) { - throw new Error(`Invalid UUID received: ${header.value}`); + + + function loadMissingSchema(e) { + var ref = e.missingSchema; + if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved'); + + var schemaPromise = self._loadingSchemas[ref]; + if (!schemaPromise) { + schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref); + schemaPromise.then(removePromise, removePromise); + } + + return schemaPromise.then(function (sch) { + if (!added(ref)) { + return loadMetaSchemaOf(sch).then(function () { + if (!added(ref)) self.addSchema(sch, ref, undefined, meta); + }); } - const uuidBytes = new Uint8Array(17); - uuidBytes[0] = 9 /* uuid */; - uuidBytes.set((0, import_util_hex_encoding.fromHex)(header.value.replace(/\-/g, "")), 1); - return uuidBytes; - } - } -}; -var UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; -var Int64 = class _Int64 { - constructor(bytes) { - this.bytes = bytes; - if (bytes.byteLength !== 8) { - throw new Error("Int64 buffers must be exactly 8 bytes"); - } - } - static { - __name(this, "Int64"); - } - static fromNumber(number) { - if (number > 9223372036854776e3 || number < -9223372036854776e3) { - throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`); - } - const bytes = new Uint8Array(8); - for (let i = 7, remaining = Math.abs(Math.round(number)); i > -1 && remaining > 0; i--, remaining /= 256) { - bytes[i] = remaining; - } - if (number < 0) { - negate(bytes); - } - return new _Int64(bytes); - } - /** - * Called implicitly by infix arithmetic operators. - */ - valueOf() { - const bytes = this.bytes.slice(0); - const negative = bytes[0] & 128; - if (negative) { - negate(bytes); + }).then(function() { + return _compileAsync(schemaObj); + }); + + function removePromise() { + delete self._loadingSchemas[ref]; + } + + function added(ref) { + return self._refs[ref] || self._schemas[ref]; + } } - return parseInt((0, import_util_hex_encoding.toHex)(bytes), 16) * (negative ? -1 : 1); - } - toString() { - return String(this.valueOf()); - } -}; -function negate(bytes) { - for (let i = 0; i < 8; i++) { - bytes[i] ^= 255; - } - for (let i = 7; i > -1; i--) { - bytes[i]++; - if (bytes[i] !== 0) - break; } } -__name(negate, "negate"); -// src/headerUtil.ts -var hasHeader = /* @__PURE__ */ __name((soughtHeader, headers) => { - soughtHeader = soughtHeader.toLowerCase(); - for (const headerName of Object.keys(headers)) { - if (soughtHeader === headerName.toLowerCase()) { - return true; - } - } - return false; -}, "hasHeader"); -// src/moveHeadersToQuery.ts -var import_protocol_http = __nccwpck_require__(64418); -var moveHeadersToQuery = /* @__PURE__ */ __name((request, options = {}) => { - const { headers, query = {} } = import_protocol_http.HttpRequest.clone(request); - for (const name of Object.keys(headers)) { - const lname = name.toLowerCase(); - if (lname.slice(0, 6) === "x-amz-" && !options.unhoistableHeaders?.has(lname) || options.hoistableHeaders?.has(lname)) { - query[name] = headers[name]; - delete headers[name]; - } - } - return { - ...request, - headers, - query - }; -}, "moveHeadersToQuery"); +/***/ }), -// src/prepareRequest.ts +/***/ 25726: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var prepareRequest = /* @__PURE__ */ __name((request) => { - request = import_protocol_http.HttpRequest.clone(request); - for (const headerName of Object.keys(request.headers)) { - if (GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) { - delete request.headers[headerName]; - } - } - return request; -}, "prepareRequest"); +"use strict"; -// src/utilDate.ts -var iso8601 = /* @__PURE__ */ __name((time) => toDate(time).toISOString().replace(/\.\d{3}Z$/, "Z"), "iso8601"); -var toDate = /* @__PURE__ */ __name((time) => { - if (typeof time === "number") { - return new Date(time * 1e3); - } - if (typeof time === "string") { - if (Number(time)) { - return new Date(Number(time) * 1e3); - } - return new Date(time); - } - return time; -}, "toDate"); -// src/SignatureV4.ts -var SignatureV4 = class { - constructor({ - applyChecksum, - credentials, - region, - service, - sha256, - uriEscapePath = true - }) { - this.headerFormatter = new HeaderFormatter(); - this.service = service; - this.sha256 = sha256; - this.uriEscapePath = uriEscapePath; - this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true; - this.regionProvider = (0, import_util_middleware.normalizeProvider)(region); - this.credentialProvider = (0, import_util_middleware.normalizeProvider)(credentials); - } - static { - __name(this, "SignatureV4"); - } - async presign(originalRequest, options = {}) { - const { - signingDate = /* @__PURE__ */ new Date(), - expiresIn = 3600, - unsignableHeaders, - unhoistableHeaders, - signableHeaders, - hoistableHeaders, - signingRegion, - signingService - } = options; - const credentials = await this.credentialProvider(); - this.validateResolvedCredentials(credentials); - const region = signingRegion ?? await this.regionProvider(); - const { longDate, shortDate } = formatDate(signingDate); - if (expiresIn > MAX_PRESIGNED_TTL) { - return Promise.reject( - "Signature version 4 presigned URLs must have an expiration date less than one week in the future" - ); - } - const scope = createScope(shortDate, region, signingService ?? this.service); - const request = moveHeadersToQuery(prepareRequest(originalRequest), { unhoistableHeaders, hoistableHeaders }); - if (credentials.sessionToken) { - request.query[TOKEN_QUERY_PARAM] = credentials.sessionToken; - } - request.query[ALGORITHM_QUERY_PARAM] = ALGORITHM_IDENTIFIER; - request.query[CREDENTIAL_QUERY_PARAM] = `${credentials.accessKeyId}/${scope}`; - request.query[AMZ_DATE_QUERY_PARAM] = longDate; - request.query[EXPIRES_QUERY_PARAM] = expiresIn.toString(10); - const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); - request.query[SIGNED_HEADERS_QUERY_PARAM] = getCanonicalHeaderList(canonicalHeaders); - request.query[SIGNATURE_QUERY_PARAM] = await this.getSignature( - longDate, - scope, - this.getSigningKey(credentials, region, shortDate, signingService), - this.createCanonicalRequest(request, canonicalHeaders, await getPayloadHash(originalRequest, this.sha256)) - ); - return request; - } - async sign(toSign, options) { - if (typeof toSign === "string") { - return this.signString(toSign, options); - } else if (toSign.headers && toSign.payload) { - return this.signEvent(toSign, options); - } else if (toSign.message) { - return this.signMessage(toSign, options); - } else { - return this.signRequest(toSign, options); - } - } - async signEvent({ headers, payload }, { signingDate = /* @__PURE__ */ new Date(), priorSignature, signingRegion, signingService }) { - const region = signingRegion ?? await this.regionProvider(); - const { shortDate, longDate } = formatDate(signingDate); - const scope = createScope(shortDate, region, signingService ?? this.service); - const hashedPayload = await getPayloadHash({ headers: {}, body: payload }, this.sha256); - const hash = new this.sha256(); - hash.update(headers); - const hashedHeaders = (0, import_util_hex_encoding.toHex)(await hash.digest()); - const stringToSign = [ - EVENT_ALGORITHM_IDENTIFIER, - longDate, - scope, - priorSignature, - hashedHeaders, - hashedPayload - ].join("\n"); - return this.signString(stringToSign, { signingDate, signingRegion: region, signingService }); - } - async signMessage(signableMessage, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService }) { - const promise = this.signEvent( - { - headers: this.headerFormatter.format(signableMessage.message.headers), - payload: signableMessage.message.body - }, - { - signingDate, - signingRegion, - signingService, - priorSignature: signableMessage.priorSignature - } - ); - return promise.then((signature) => { - return { message: signableMessage.message, signature }; - }); - } - async signString(stringToSign, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService } = {}) { - const credentials = await this.credentialProvider(); - this.validateResolvedCredentials(credentials); - const region = signingRegion ?? await this.regionProvider(); - const { shortDate } = formatDate(signingDate); - const hash = new this.sha256(await this.getSigningKey(credentials, region, shortDate, signingService)); - hash.update((0, import_util_utf84.toUint8Array)(stringToSign)); - return (0, import_util_hex_encoding.toHex)(await hash.digest()); - } - async signRequest(requestToSign, { - signingDate = /* @__PURE__ */ new Date(), - signableHeaders, - unsignableHeaders, - signingRegion, - signingService - } = {}) { - const credentials = await this.credentialProvider(); - this.validateResolvedCredentials(credentials); - const region = signingRegion ?? await this.regionProvider(); - const request = prepareRequest(requestToSign); - const { longDate, shortDate } = formatDate(signingDate); - const scope = createScope(shortDate, region, signingService ?? this.service); - request.headers[AMZ_DATE_HEADER] = longDate; - if (credentials.sessionToken) { - request.headers[TOKEN_HEADER] = credentials.sessionToken; - } - const payloadHash = await getPayloadHash(request, this.sha256); - if (!hasHeader(SHA256_HEADER, request.headers) && this.applyChecksum) { - request.headers[SHA256_HEADER] = payloadHash; - } - const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); - const signature = await this.getSignature( - longDate, - scope, - this.getSigningKey(credentials, region, shortDate, signingService), - this.createCanonicalRequest(request, canonicalHeaders, payloadHash) - ); - request.headers[AUTH_HEADER] = `${ALGORITHM_IDENTIFIER} Credential=${credentials.accessKeyId}/${scope}, SignedHeaders=${getCanonicalHeaderList(canonicalHeaders)}, Signature=${signature}`; - return request; - } - createCanonicalRequest(request, canonicalHeaders, payloadHash) { - const sortedHeaders = Object.keys(canonicalHeaders).sort(); - return `${request.method} -${this.getCanonicalPath(request)} -${getCanonicalQuery(request)} -${sortedHeaders.map((name) => `${name}:${canonicalHeaders[name]}`).join("\n")} +var resolve = __nccwpck_require__(63896); -${sortedHeaders.join(";")} -${payloadHash}`; - } - async createStringToSign(longDate, credentialScope, canonicalRequest) { - const hash = new this.sha256(); - hash.update((0, import_util_utf84.toUint8Array)(canonicalRequest)); - const hashedRequest = await hash.digest(); - return `${ALGORITHM_IDENTIFIER} -${longDate} -${credentialScope} -${(0, import_util_hex_encoding.toHex)(hashedRequest)}`; - } - getCanonicalPath({ path }) { - if (this.uriEscapePath) { - const normalizedPathSegments = []; - for (const pathSegment of path.split("/")) { - if (pathSegment?.length === 0) - continue; - if (pathSegment === ".") - continue; - if (pathSegment === "..") { - normalizedPathSegments.pop(); - } else { - normalizedPathSegments.push(pathSegment); - } - } - const normalizedPath = `${path?.startsWith("/") ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && path?.endsWith("/") ? "/" : ""}`; - const doubleEncoded = (0, import_util_uri_escape.escapeUri)(normalizedPath); - return doubleEncoded.replace(/%2F/g, "/"); - } - return path; - } - async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) { - const stringToSign = await this.createStringToSign(longDate, credentialScope, canonicalRequest); - const hash = new this.sha256(await keyPromise); - hash.update((0, import_util_utf84.toUint8Array)(stringToSign)); - return (0, import_util_hex_encoding.toHex)(await hash.digest()); - } - getSigningKey(credentials, region, shortDate, service) { - return getSigningKey(this.sha256, credentials, shortDate, region, service || this.service); - } - validateResolvedCredentials(credentials) { - if (typeof credentials !== "object" || // @ts-expect-error: Property 'accessKeyId' does not exist on type 'object'.ts(2339) - typeof credentials.accessKeyId !== "string" || // @ts-expect-error: Property 'secretAccessKey' does not exist on type 'object'.ts(2339) - typeof credentials.secretAccessKey !== "string") { - throw new Error("Resolved credential object is not valid"); - } - } +module.exports = { + Validation: errorSubclass(ValidationError), + MissingRef: errorSubclass(MissingRefError) }; -var formatDate = /* @__PURE__ */ __name((now) => { - const longDate = iso8601(now).replace(/[\-:]/g, ""); - return { - longDate, - shortDate: longDate.slice(0, 8) - }; -}, "formatDate"); -var getCanonicalHeaderList = /* @__PURE__ */ __name((headers) => Object.keys(headers).sort().join(";"), "getCanonicalHeaderList"); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +function ValidationError(errors) { + this.message = 'validation failed'; + this.errors = errors; + this.ajv = this.validation = true; +} + + +MissingRefError.message = function (baseId, ref) { + return 'can\'t resolve reference ' + ref + ' from id ' + baseId; +}; + + +function MissingRefError(baseId, ref, message) { + this.message = message || MissingRefError.message(baseId, ref); + this.missingRef = resolve.url(baseId, ref); + this.missingSchema = resolve.normalizeId(resolve.fullPath(this.missingRef)); +} + + +function errorSubclass(Subclass) { + Subclass.prototype = Object.create(Error.prototype); + Subclass.prototype.constructor = Subclass; + return Subclass; +} /***/ }), -/***/ 63570: +/***/ 66627: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -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); +"use strict"; -// src/index.ts -var src_exports = {}; -__export(src_exports, { - Client: () => Client, - Command: () => Command, - LazyJsonString: () => LazyJsonString, - NoOpLogger: () => NoOpLogger, - SENSITIVE_STRING: () => SENSITIVE_STRING, - ServiceException: () => ServiceException, - _json: () => _json, - collectBody: () => import_protocols.collectBody, - convertMap: () => convertMap, - createAggregatedClient: () => createAggregatedClient, - dateToUtcString: () => dateToUtcString, - decorateServiceException: () => decorateServiceException, - emitWarningIfUnsupportedVersion: () => emitWarningIfUnsupportedVersion, - expectBoolean: () => expectBoolean, - expectByte: () => expectByte, - expectFloat32: () => expectFloat32, - expectInt: () => expectInt, - expectInt32: () => expectInt32, - expectLong: () => expectLong, - expectNonNull: () => expectNonNull, - expectNumber: () => expectNumber, - expectObject: () => expectObject, - expectShort: () => expectShort, - expectString: () => expectString, - expectUnion: () => expectUnion, - extendedEncodeURIComponent: () => import_protocols.extendedEncodeURIComponent, - getArrayIfSingleItem: () => getArrayIfSingleItem, - getDefaultClientConfiguration: () => getDefaultClientConfiguration, - getDefaultExtensionConfiguration: () => getDefaultExtensionConfiguration, - getValueFromTextNode: () => getValueFromTextNode, - handleFloat: () => handleFloat, - isSerializableHeaderValue: () => isSerializableHeaderValue, - limitedParseDouble: () => limitedParseDouble, - limitedParseFloat: () => limitedParseFloat, - limitedParseFloat32: () => limitedParseFloat32, - loadConfigsForDefaultMode: () => loadConfigsForDefaultMode, - logger: () => logger, - map: () => map, - parseBoolean: () => parseBoolean, - parseEpochTimestamp: () => parseEpochTimestamp, - parseRfc3339DateTime: () => parseRfc3339DateTime, - parseRfc3339DateTimeWithOffset: () => parseRfc3339DateTimeWithOffset, - parseRfc7231DateTime: () => parseRfc7231DateTime, - quoteHeader: () => quoteHeader, - resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig, - resolvedPath: () => import_protocols.resolvedPath, - serializeDateTime: () => serializeDateTime, - serializeFloat: () => serializeFloat, - splitEvery: () => splitEvery, - splitHeader: () => splitHeader, - strictParseByte: () => strictParseByte, - strictParseDouble: () => strictParseDouble, - strictParseFloat: () => strictParseFloat, - strictParseFloat32: () => strictParseFloat32, - strictParseInt: () => strictParseInt, - strictParseInt32: () => strictParseInt32, - strictParseLong: () => strictParseLong, - strictParseShort: () => strictParseShort, - take: () => take, - throwDefaultError: () => throwDefaultError, - withBaseException: () => withBaseException -}); -module.exports = __toCommonJS(src_exports); -// src/client.ts -var import_middleware_stack = __nccwpck_require__(97911); -var Client = class { - constructor(config) { - this.config = config; - this.middlewareStack = (0, import_middleware_stack.constructStack)(); - } - static { - __name(this, "Client"); - } - send(command, optionsOrCb, cb) { - const options = typeof optionsOrCb !== "function" ? optionsOrCb : void 0; - const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb; - const useHandlerCache = options === void 0 && this.config.cacheMiddleware === true; - let handler; - if (useHandlerCache) { - if (!this.handlers) { - this.handlers = /* @__PURE__ */ new WeakMap(); - } - const handlers = this.handlers; - if (handlers.has(command.constructor)) { - handler = handlers.get(command.constructor); - } else { - handler = command.resolveMiddleware(this.middlewareStack, this.config, options); - handlers.set(command.constructor, handler); - } - } else { - delete this.handlers; - handler = command.resolveMiddleware(this.middlewareStack, this.config, options); - } - if (callback) { - handler(command).then( - (result) => callback(null, result.output), - (err) => callback(err) - ).catch( - // prevent any errors thrown in the callback from triggering an - // unhandled promise rejection - () => { - } - ); - } else { - return handler(command).then((result) => result.output); - } - } - destroy() { - this.config?.requestHandler?.destroy?.(); - delete this.handlers; - } -}; +var util = __nccwpck_require__(76578); -// src/collect-stream-body.ts -var import_protocols = __nccwpck_require__(2241); +var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; +var DAYS = [0,31,28,31,30,31,30,31,31,30,31,30,31]; +var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i; +var HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i; +var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; +var URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; +// uri-template: https://tools.ietf.org/html/rfc6570 +var URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; +// For the source: https://gist.github.com/dperini/729294 +// For test cases: https://mathiasbynens.be/demo/url-regex +// @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983. +// var URL = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; +var URL = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i; +var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; +var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; +var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; +var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; -// src/command.ts -var import_types = __nccwpck_require__(55756); -var Command = class { - constructor() { - this.middlewareStack = (0, import_middleware_stack.constructStack)(); - } - static { - __name(this, "Command"); - } - /** - * Factory for Command ClassBuilder. - * @internal - */ - static classBuilder() { - return new ClassBuilder(); - } - /** - * @internal - */ - resolveMiddlewareWithContext(clientStack, configuration, options, { - middlewareFn, - clientName, - commandName, - inputFilterSensitiveLog, - outputFilterSensitiveLog, - smithyContext, - additionalContext, - CommandCtor - }) { - for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) { - this.middlewareStack.use(mw); - } - const stack = clientStack.concat(this.middlewareStack); - const { logger: logger2 } = configuration; - const handlerExecutionContext = { - logger: logger2, - clientName, - commandName, - inputFilterSensitiveLog, - outputFilterSensitiveLog, - [import_types.SMITHY_CONTEXT_KEY]: { - commandInstance: this, - ...smithyContext - }, - ...additionalContext - }; - const { requestHandler } = configuration; - return stack.resolve( - (request) => requestHandler.handle(request.request, options || {}), - handlerExecutionContext - ); - } -}; -var ClassBuilder = class { - constructor() { - this._init = () => { - }; - this._ep = {}; - this._middlewareFn = () => []; - this._commandName = ""; - this._clientName = ""; - this._additionalContext = {}; - this._smithyContext = {}; - this._inputFilterSensitiveLog = (_) => _; - this._outputFilterSensitiveLog = (_) => _; - this._serializer = null; - this._deserializer = null; - } - static { - __name(this, "ClassBuilder"); - } - /** - * Optional init callback. - */ - init(cb) { - this._init = cb; - } - /** - * Set the endpoint parameter instructions. - */ - ep(endpointParameterInstructions) { - this._ep = endpointParameterInstructions; - return this; - } - /** - * Add any number of middleware. - */ - m(middlewareSupplier) { - this._middlewareFn = middlewareSupplier; - return this; - } - /** - * Set the initial handler execution context Smithy field. - */ - s(service, operation, smithyContext = {}) { - this._smithyContext = { - service, - operation, - ...smithyContext - }; - return this; - } - /** - * Set the initial handler execution context. - */ - c(additionalContext = {}) { - this._additionalContext = additionalContext; - return this; - } - /** - * Set constant string identifiers for the operation. - */ - n(clientName, commandName) { - this._clientName = clientName; - this._commandName = commandName; - return this; - } - /** - * Set the input and output sensistive log filters. - */ - f(inputFilter = (_) => _, outputFilter = (_) => _) { - this._inputFilterSensitiveLog = inputFilter; - this._outputFilterSensitiveLog = outputFilter; - return this; - } - /** - * Sets the serializer. - */ - ser(serializer) { - this._serializer = serializer; - return this; - } - /** - * Sets the deserializer. - */ - de(deserializer) { - this._deserializer = deserializer; - return this; - } - /** - * @returns a Command class with the classBuilder properties. - */ - build() { - const closure = this; - let CommandRef; - return CommandRef = class extends Command { - /** - * @public - */ - constructor(...[input]) { - super(); - /** - * @internal - */ - // @ts-ignore used in middlewareFn closure. - this.serialize = closure._serializer; - /** - * @internal - */ - // @ts-ignore used in middlewareFn closure. - this.deserialize = closure._deserializer; - this.input = input ?? {}; - closure._init(this); - } - static { - __name(this, "CommandRef"); - } - /** - * @public - */ - static getEndpointParameterInstructions() { - return closure._ep; - } - /** - * @internal - */ - resolveMiddleware(stack, configuration, options) { - return this.resolveMiddlewareWithContext(stack, configuration, options, { - CommandCtor: CommandRef, - middlewareFn: closure._middlewareFn, - clientName: closure._clientName, - commandName: closure._commandName, - inputFilterSensitiveLog: closure._inputFilterSensitiveLog, - outputFilterSensitiveLog: closure._outputFilterSensitiveLog, - smithyContext: closure._smithyContext, - additionalContext: closure._additionalContext - }); - } - }; - } +module.exports = formats; + +function formats(mode) { + mode = mode == 'full' ? 'full' : 'fast'; + return util.copy(formats[mode]); +} + + +formats.fast = { + // date: http://tools.ietf.org/html/rfc3339#section-5.6 + date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/, + // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 + time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, + 'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, + // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js + uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, + 'uri-reference': /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, + 'uri-template': URITEMPLATE, + url: URL, + // email (sources from jsen validator): + // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 + // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation') + email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i, + hostname: HOSTNAME, + // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, + // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses + ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, + regex: regex, + // uuid: http://tools.ietf.org/html/rfc4122 + uuid: UUID, + // JSON-pointer: https://tools.ietf.org/html/rfc6901 + // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A + 'json-pointer': JSON_POINTER, + 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT, + // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 + 'relative-json-pointer': RELATIVE_JSON_POINTER }; -// src/constants.ts -var SENSITIVE_STRING = "***SensitiveInformation***"; -// src/create-aggregated-client.ts -var createAggregatedClient = /* @__PURE__ */ __name((commands, Client2) => { - for (const command of Object.keys(commands)) { - const CommandCtor = commands[command]; - const methodImpl = /* @__PURE__ */ __name(async function(args, optionsOrCb, cb) { - const command2 = new CommandCtor(args); - if (typeof optionsOrCb === "function") { - this.send(command2, optionsOrCb); - } else if (typeof cb === "function") { - if (typeof optionsOrCb !== "object") - throw new Error(`Expected http options but got ${typeof optionsOrCb}`); - this.send(command2, optionsOrCb || {}, cb); - } else { - return this.send(command2, optionsOrCb); - } - }, "methodImpl"); - const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, ""); - Client2.prototype[methodName] = methodImpl; - } -}, "createAggregatedClient"); +formats.full = { + date: date, + time: time, + 'date-time': date_time, + uri: uri, + 'uri-reference': URIREF, + 'uri-template': URITEMPLATE, + url: URL, + email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, + hostname: HOSTNAME, + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, + ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, + regex: regex, + uuid: UUID, + 'json-pointer': JSON_POINTER, + 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT, + 'relative-json-pointer': RELATIVE_JSON_POINTER +}; -// src/parse-utils.ts -var parseBoolean = /* @__PURE__ */ __name((value) => { - switch (value) { - case "true": - return true; - case "false": - return false; - default: - throw new Error(`Unable to parse boolean value "${value}"`); + +function isLeapYear(year) { + // https://tools.ietf.org/html/rfc3339#appendix-C + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +} + + +function date(str) { + // full-date from http://tools.ietf.org/html/rfc3339#section-5.6 + var matches = str.match(DATE); + if (!matches) return false; + + var year = +matches[1]; + var month = +matches[2]; + var day = +matches[3]; + + return month >= 1 && month <= 12 && day >= 1 && + day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]); +} + + +function time(str, full) { + var matches = str.match(TIME); + if (!matches) return false; + + var hour = matches[1]; + var minute = matches[2]; + var second = matches[3]; + var timeZone = matches[5]; + return ((hour <= 23 && minute <= 59 && second <= 59) || + (hour == 23 && minute == 59 && second == 60)) && + (!full || timeZone); +} + + +var DATE_TIME_SEPARATOR = /t|\s/i; +function date_time(str) { + // http://tools.ietf.org/html/rfc3339#section-5.6 + var dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true); +} + + +var NOT_URI_FRAGMENT = /\/|:/; +function uri(str) { + // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "." + return NOT_URI_FRAGMENT.test(str) && URI.test(str); +} + + +var Z_ANCHOR = /[^\\]\\Z/; +function regex(str) { + if (Z_ANCHOR.test(str)) return false; + try { + new RegExp(str); + return true; + } catch(e) { + return false; } -}, "parseBoolean"); -var expectBoolean = /* @__PURE__ */ __name((value) => { - if (value === null || value === void 0) { - return void 0; +} + + +/***/ }), + +/***/ 875: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var resolve = __nccwpck_require__(63896) + , util = __nccwpck_require__(76578) + , errorClasses = __nccwpck_require__(25726) + , stableStringify = __nccwpck_require__(30969); + +var validateGenerator = __nccwpck_require__(49585); + +/** + * Functions below are used inside compiled validations function + */ + +var ucs2length = util.ucs2length; +var equal = __nccwpck_require__(28206); + +// this error is thrown by async schemas to return validation errors via exception +var ValidationError = errorClasses.Validation; + +module.exports = compile; + + +/** + * Compiles schema to validation function + * @this Ajv + * @param {Object} schema schema object + * @param {Object} root object with information about the root schema for this schema + * @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution + * @param {String} baseId base ID for IDs in the schema + * @return {Function} validation function + */ +function compile(schema, root, localRefs, baseId) { + /* jshint validthis: true, evil: true */ + /* eslint no-shadow: 0 */ + var self = this + , opts = this._opts + , refVal = [ undefined ] + , refs = {} + , patterns = [] + , patternsHash = {} + , defaults = [] + , defaultsHash = {} + , customRules = []; + + function patternCode(i, patterns) { + var regExpCode = opts.regExp ? 'regExp' : 'new RegExp'; + return 'var pattern' + i + ' = ' + regExpCode + '(' + util.toQuotedString(patterns[i]) + ');'; } - if (typeof value === "number") { - if (value === 0 || value === 1) { - logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); + + root = root || { schema: schema, refVal: refVal, refs: refs }; + + var c = checkCompiling.call(this, schema, root, baseId); + var compilation = this._compilations[c.index]; + if (c.compiling) return (compilation.callValidate = callValidate); + + var formats = this._formats; + var RULES = this.RULES; + + try { + var v = localCompile(schema, root, localRefs, baseId); + compilation.validate = v; + var cv = compilation.callValidate; + if (cv) { + cv.schema = v.schema; + cv.errors = null; + cv.refs = v.refs; + cv.refVal = v.refVal; + cv.root = v.root; + cv.$async = v.$async; + if (opts.sourceCode) cv.source = v.source; } - if (value === 0) { - return false; + return v; + } finally { + endCompiling.call(this, schema, root, baseId); + } + + /* @this {*} - custom context, see passContext option */ + function callValidate() { + /* jshint validthis: true */ + var validate = compilation.validate; + var result = validate.apply(this, arguments); + callValidate.errors = validate.errors; + return result; + } + + function localCompile(_schema, _root, localRefs, baseId) { + var isRoot = !_root || (_root && _root.schema == _schema); + if (_root.schema != root.schema) + return compile.call(self, _schema, _root, localRefs, baseId); + + var $async = _schema.$async === true; + + var sourceCode = validateGenerator({ + isTop: true, + schema: _schema, + isRoot: isRoot, + baseId: baseId, + root: _root, + schemaPath: '', + errSchemaPath: '#', + errorPath: '""', + MissingRefError: errorClasses.MissingRef, + RULES: RULES, + validate: validateGenerator, + util: util, + resolve: resolve, + resolveRef: resolveRef, + usePattern: usePattern, + useDefault: useDefault, + useCustomRule: useCustomRule, + opts: opts, + formats: formats, + logger: self.logger, + self: self + }); + + sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) + + vars(defaults, defaultCode) + vars(customRules, customRuleCode) + + sourceCode; + + if (opts.processCode) sourceCode = opts.processCode(sourceCode, _schema); + // console.log('\n\n\n *** \n', JSON.stringify(sourceCode)); + var validate; + try { + var makeValidate = new Function( + 'self', + 'RULES', + 'formats', + 'root', + 'refVal', + 'defaults', + 'customRules', + 'equal', + 'ucs2length', + 'ValidationError', + 'regExp', + sourceCode + ); + + validate = makeValidate( + self, + RULES, + formats, + root, + refVal, + defaults, + customRules, + equal, + ucs2length, + ValidationError, + opts.regExp + ); + + refVal[0] = validate; + } catch(e) { + self.logger.error('Error compiling schema, function code:', sourceCode); + throw e; } - if (value === 1) { - return true; + + validate.schema = _schema; + validate.errors = null; + validate.refs = refs; + validate.refVal = refVal; + validate.root = isRoot ? validate : _root; + if ($async) validate.$async = true; + if (opts.sourceCode === true) { + validate.source = { + code: sourceCode, + patterns: patterns, + defaults: defaults + }; } + + return validate; } - if (typeof value === "string") { - const lower = value.toLowerCase(); - if (lower === "false" || lower === "true") { - logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); - } - if (lower === "false") { - return false; + + function resolveRef(baseId, ref, isRoot) { + ref = resolve.url(baseId, ref); + var refIndex = refs[ref]; + var _refVal, refCode; + if (refIndex !== undefined) { + _refVal = refVal[refIndex]; + refCode = 'refVal[' + refIndex + ']'; + return resolvedRef(_refVal, refCode); } - if (lower === "true") { - return true; + if (!isRoot && root.refs) { + var rootRefId = root.refs[ref]; + if (rootRefId !== undefined) { + _refVal = root.refVal[rootRefId]; + refCode = addLocalRef(ref, _refVal); + return resolvedRef(_refVal, refCode); + } } - } - if (typeof value === "boolean") { - return value; - } - throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`); -}, "expectBoolean"); -var expectNumber = /* @__PURE__ */ __name((value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "string") { - const parsed = parseFloat(value); - if (!Number.isNaN(parsed)) { - if (String(parsed) !== String(value)) { - logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`)); + + refCode = addLocalRef(ref); + var v = resolve.call(self, localCompile, root, ref); + if (v === undefined) { + var localSchema = localRefs && localRefs[ref]; + if (localSchema) { + v = resolve.inlineRef(localSchema, opts.inlineRefs) + ? localSchema + : compile.call(self, localSchema, root, localRefs, baseId); } - return parsed; } - } - if (typeof value === "number") { - return value; - } - throw new TypeError(`Expected number, got ${typeof value}: ${value}`); -}, "expectNumber"); -var MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23)); -var expectFloat32 = /* @__PURE__ */ __name((value) => { - const expected = expectNumber(value); - if (expected !== void 0 && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) { - if (Math.abs(expected) > MAX_FLOAT) { - throw new TypeError(`Expected 32-bit float, got ${value}`); + + if (v === undefined) { + removeLocalRef(ref); + } else { + replaceLocalRef(ref, v); + return resolvedRef(v, refCode); } } - return expected; -}, "expectFloat32"); -var expectLong = /* @__PURE__ */ __name((value) => { - if (value === null || value === void 0) { - return void 0; + + function addLocalRef(ref, v) { + var refId = refVal.length; + refVal[refId] = v; + refs[ref] = refId; + return 'refVal' + refId; } - if (Number.isInteger(value) && !Number.isNaN(value)) { - return value; + + function removeLocalRef(ref) { + delete refs[ref]; } - throw new TypeError(`Expected integer, got ${typeof value}: ${value}`); -}, "expectLong"); -var expectInt = expectLong; -var expectInt32 = /* @__PURE__ */ __name((value) => expectSizedInt(value, 32), "expectInt32"); -var expectShort = /* @__PURE__ */ __name((value) => expectSizedInt(value, 16), "expectShort"); -var expectByte = /* @__PURE__ */ __name((value) => expectSizedInt(value, 8), "expectByte"); -var expectSizedInt = /* @__PURE__ */ __name((value, size) => { - const expected = expectLong(value); - if (expected !== void 0 && castInt(expected, size) !== expected) { - throw new TypeError(`Expected ${size}-bit integer, got ${value}`); + + function replaceLocalRef(ref, v) { + var refId = refs[ref]; + refVal[refId] = v; } - return expected; -}, "expectSizedInt"); -var castInt = /* @__PURE__ */ __name((value, size) => { - switch (size) { - case 32: - return Int32Array.of(value)[0]; - case 16: - return Int16Array.of(value)[0]; - case 8: - return Int8Array.of(value)[0]; + + function resolvedRef(refVal, code) { + return typeof refVal == 'object' || typeof refVal == 'boolean' + ? { code: code, schema: refVal, inline: true } + : { code: code, $async: refVal && !!refVal.$async }; } -}, "castInt"); -var expectNonNull = /* @__PURE__ */ __name((value, location) => { - if (value === null || value === void 0) { - if (location) { - throw new TypeError(`Expected a non-null value for ${location}`); + + function usePattern(regexStr) { + var index = patternsHash[regexStr]; + if (index === undefined) { + index = patternsHash[regexStr] = patterns.length; + patterns[index] = regexStr; } - throw new TypeError("Expected a non-null value"); - } - return value; -}, "expectNonNull"); -var expectObject = /* @__PURE__ */ __name((value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "object" && !Array.isArray(value)) { - return value; - } - const receivedType = Array.isArray(value) ? "array" : typeof value; - throw new TypeError(`Expected object, got ${receivedType}: ${value}`); -}, "expectObject"); -var expectString = /* @__PURE__ */ __name((value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "string") { - return value; - } - if (["boolean", "number", "bigint"].includes(typeof value)) { - logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`)); - return String(value); - } - throw new TypeError(`Expected string, got ${typeof value}: ${value}`); -}, "expectString"); -var expectUnion = /* @__PURE__ */ __name((value) => { - if (value === null || value === void 0) { - return void 0; - } - const asObject = expectObject(value); - const setKeys = Object.entries(asObject).filter(([, v]) => v != null).map(([k]) => k); - if (setKeys.length === 0) { - throw new TypeError(`Unions must have exactly one non-null member. None were found.`); - } - if (setKeys.length > 1) { - throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`); - } - return asObject; -}, "expectUnion"); -var strictParseDouble = /* @__PURE__ */ __name((value) => { - if (typeof value == "string") { - return expectNumber(parseNumber(value)); - } - return expectNumber(value); -}, "strictParseDouble"); -var strictParseFloat = strictParseDouble; -var strictParseFloat32 = /* @__PURE__ */ __name((value) => { - if (typeof value == "string") { - return expectFloat32(parseNumber(value)); - } - return expectFloat32(value); -}, "strictParseFloat32"); -var NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g; -var parseNumber = /* @__PURE__ */ __name((value) => { - const matches = value.match(NUMBER_REGEX); - if (matches === null || matches[0].length !== value.length) { - throw new TypeError(`Expected real number, got implicit NaN`); - } - return parseFloat(value); -}, "parseNumber"); -var limitedParseDouble = /* @__PURE__ */ __name((value) => { - if (typeof value == "string") { - return parseFloatString(value); - } - return expectNumber(value); -}, "limitedParseDouble"); -var handleFloat = limitedParseDouble; -var limitedParseFloat = limitedParseDouble; -var limitedParseFloat32 = /* @__PURE__ */ __name((value) => { - if (typeof value == "string") { - return parseFloatString(value); - } - return expectFloat32(value); -}, "limitedParseFloat32"); -var parseFloatString = /* @__PURE__ */ __name((value) => { - switch (value) { - case "NaN": - return NaN; - case "Infinity": - return Infinity; - case "-Infinity": - return -Infinity; - default: - throw new Error(`Unable to parse float value: ${value}`); - } -}, "parseFloatString"); -var strictParseLong = /* @__PURE__ */ __name((value) => { - if (typeof value === "string") { - return expectLong(parseNumber(value)); - } - return expectLong(value); -}, "strictParseLong"); -var strictParseInt = strictParseLong; -var strictParseInt32 = /* @__PURE__ */ __name((value) => { - if (typeof value === "string") { - return expectInt32(parseNumber(value)); - } - return expectInt32(value); -}, "strictParseInt32"); -var strictParseShort = /* @__PURE__ */ __name((value) => { - if (typeof value === "string") { - return expectShort(parseNumber(value)); - } - return expectShort(value); -}, "strictParseShort"); -var strictParseByte = /* @__PURE__ */ __name((value) => { - if (typeof value === "string") { - return expectByte(parseNumber(value)); + return 'pattern' + index; } - return expectByte(value); -}, "strictParseByte"); -var stackTraceWarning = /* @__PURE__ */ __name((message) => { - return String(new TypeError(message).stack || message).split("\n").slice(0, 5).filter((s) => !s.includes("stackTraceWarning")).join("\n"); -}, "stackTraceWarning"); -var logger = { - warn: console.warn -}; -// src/date-utils.ts -var DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; -var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; -function dateToUtcString(date) { - const year = date.getUTCFullYear(); - const month = date.getUTCMonth(); - const dayOfWeek = date.getUTCDay(); - const dayOfMonthInt = date.getUTCDate(); - const hoursInt = date.getUTCHours(); - const minutesInt = date.getUTCMinutes(); - const secondsInt = date.getUTCSeconds(); - const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`; - const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`; - const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`; - const secondsString = secondsInt < 10 ? `0${secondsInt}` : `${secondsInt}`; - return `${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year} ${hoursString}:${minutesString}:${secondsString} GMT`; -} -__name(dateToUtcString, "dateToUtcString"); -var RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/); -var parseRfc3339DateTime = /* @__PURE__ */ __name((value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value !== "string") { - throw new TypeError("RFC-3339 date-times must be expressed as strings"); - } - const match = RFC3339.exec(value); - if (!match) { - throw new TypeError("Invalid RFC-3339 date-time value"); - } - const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match; - const year = strictParseShort(stripLeadingZeroes(yearStr)); - const month = parseDateValue(monthStr, "month", 1, 12); - const day = parseDateValue(dayStr, "day", 1, 31); - return buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); -}, "parseRfc3339DateTime"); -var RFC3339_WITH_OFFSET = new RegExp( - /^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/ -); -var parseRfc3339DateTimeWithOffset = /* @__PURE__ */ __name((value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value !== "string") { - throw new TypeError("RFC-3339 date-times must be expressed as strings"); - } - const match = RFC3339_WITH_OFFSET.exec(value); - if (!match) { - throw new TypeError("Invalid RFC-3339 date-time value"); - } - const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match; - const year = strictParseShort(stripLeadingZeroes(yearStr)); - const month = parseDateValue(monthStr, "month", 1, 12); - const day = parseDateValue(dayStr, "day", 1, 31); - const date = buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); - if (offsetStr.toUpperCase() != "Z") { - date.setTime(date.getTime() - parseOffsetToMilliseconds(offsetStr)); - } - return date; -}, "parseRfc3339DateTimeWithOffset"); -var IMF_FIXDATE = new RegExp( - /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/ -); -var RFC_850_DATE = new RegExp( - /^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/ -); -var ASC_TIME = new RegExp( - /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/ -); -var parseRfc7231DateTime = /* @__PURE__ */ __name((value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value !== "string") { - throw new TypeError("RFC-7231 date-times must be expressed as strings"); - } - let match = IMF_FIXDATE.exec(value); - if (match) { - const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; - return buildDate( - strictParseShort(stripLeadingZeroes(yearStr)), - parseMonthByShortName(monthStr), - parseDateValue(dayStr, "day", 1, 31), - { hours, minutes, seconds, fractionalMilliseconds } - ); - } - match = RFC_850_DATE.exec(value); - if (match) { - const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; - return adjustRfc850Year( - buildDate(parseTwoDigitYear(yearStr), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { - hours, - minutes, - seconds, - fractionalMilliseconds - }) - ); - } - match = ASC_TIME.exec(value); - if (match) { - const [_, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match; - return buildDate( - strictParseShort(stripLeadingZeroes(yearStr)), - parseMonthByShortName(monthStr), - parseDateValue(dayStr.trimLeft(), "day", 1, 31), - { hours, minutes, seconds, fractionalMilliseconds } - ); - } - throw new TypeError("Invalid RFC-7231 date-time value"); -}, "parseRfc7231DateTime"); -var parseEpochTimestamp = /* @__PURE__ */ __name((value) => { - if (value === null || value === void 0) { - return void 0; - } - let valueAsDouble; - if (typeof value === "number") { - valueAsDouble = value; - } else if (typeof value === "string") { - valueAsDouble = strictParseDouble(value); - } else if (typeof value === "object" && value.tag === 1) { - valueAsDouble = value.value; - } else { - throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation"); - } - if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) { - throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics"); - } - return new Date(Math.round(valueAsDouble * 1e3)); -}, "parseEpochTimestamp"); -var buildDate = /* @__PURE__ */ __name((year, month, day, time) => { - const adjustedMonth = month - 1; - validateDayOfMonth(year, adjustedMonth, day); - return new Date( - Date.UTC( - year, - adjustedMonth, - day, - parseDateValue(time.hours, "hour", 0, 23), - parseDateValue(time.minutes, "minute", 0, 59), - // seconds can go up to 60 for leap seconds - parseDateValue(time.seconds, "seconds", 0, 60), - parseMilliseconds(time.fractionalMilliseconds) - ) - ); -}, "buildDate"); -var parseTwoDigitYear = /* @__PURE__ */ __name((value) => { - const thisYear = (/* @__PURE__ */ new Date()).getUTCFullYear(); - const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort(stripLeadingZeroes(value)); - if (valueInThisCentury < thisYear) { - return valueInThisCentury + 100; - } - return valueInThisCentury; -}, "parseTwoDigitYear"); -var FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1e3; -var adjustRfc850Year = /* @__PURE__ */ __name((input) => { - if (input.getTime() - (/* @__PURE__ */ new Date()).getTime() > FIFTY_YEARS_IN_MILLIS) { - return new Date( - Date.UTC( - input.getUTCFullYear() - 100, - input.getUTCMonth(), - input.getUTCDate(), - input.getUTCHours(), - input.getUTCMinutes(), - input.getUTCSeconds(), - input.getUTCMilliseconds() - ) - ); - } - return input; -}, "adjustRfc850Year"); -var parseMonthByShortName = /* @__PURE__ */ __name((value) => { - const monthIdx = MONTHS.indexOf(value); - if (monthIdx < 0) { - throw new TypeError(`Invalid month: ${value}`); - } - return monthIdx + 1; -}, "parseMonthByShortName"); -var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; -var validateDayOfMonth = /* @__PURE__ */ __name((year, month, day) => { - let maxDays = DAYS_IN_MONTH[month]; - if (month === 1 && isLeapYear(year)) { - maxDays = 29; - } - if (day > maxDays) { - throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`); - } -}, "validateDayOfMonth"); -var isLeapYear = /* @__PURE__ */ __name((year) => { - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); -}, "isLeapYear"); -var parseDateValue = /* @__PURE__ */ __name((value, type, lower, upper) => { - const dateVal = strictParseByte(stripLeadingZeroes(value)); - if (dateVal < lower || dateVal > upper) { - throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`); - } - return dateVal; -}, "parseDateValue"); -var parseMilliseconds = /* @__PURE__ */ __name((value) => { - if (value === null || value === void 0) { - return 0; - } - return strictParseFloat32("0." + value) * 1e3; -}, "parseMilliseconds"); -var parseOffsetToMilliseconds = /* @__PURE__ */ __name((value) => { - const directionStr = value[0]; - let direction = 1; - if (directionStr == "+") { - direction = 1; - } else if (directionStr == "-") { - direction = -1; - } else { - throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`); - } - const hour = Number(value.substring(1, 3)); - const minute = Number(value.substring(4, 6)); - return direction * (hour * 60 + minute) * 60 * 1e3; -}, "parseOffsetToMilliseconds"); -var stripLeadingZeroes = /* @__PURE__ */ __name((value) => { - let idx = 0; - while (idx < value.length - 1 && value.charAt(idx) === "0") { - idx++; - } - if (idx === 0) { - return value; + function useDefault(value) { + switch (typeof value) { + case 'boolean': + case 'number': + return '' + value; + case 'string': + return util.toQuotedString(value); + case 'object': + if (value === null) return 'null'; + var valueStr = stableStringify(value); + var index = defaultsHash[valueStr]; + if (index === undefined) { + index = defaultsHash[valueStr] = defaults.length; + defaults[index] = value; + } + return 'default' + index; + } } - return value.slice(idx); -}, "stripLeadingZeroes"); -// src/exceptions.ts -var ServiceException = class _ServiceException extends Error { - static { - __name(this, "ServiceException"); - } - constructor(options) { - super(options.message); - Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype); - this.name = options.name; - this.$fault = options.$fault; - this.$metadata = options.$metadata; - } - /** - * Checks if a value is an instance of ServiceException (duck typed) - */ - static isInstance(value) { - if (!value) - return false; - const candidate = value; - return _ServiceException.prototype.isPrototypeOf(candidate) || Boolean(candidate.$fault) && Boolean(candidate.$metadata) && (candidate.$fault === "client" || candidate.$fault === "server"); - } - /** - * Custom instanceof check to support the operator for ServiceException base class - */ - static [Symbol.hasInstance](instance) { - if (!instance) - return false; - const candidate = instance; - if (this === _ServiceException) { - return _ServiceException.isInstance(instance); - } - if (_ServiceException.isInstance(instance)) { - if (candidate.name && this.name) { - return this.prototype.isPrototypeOf(instance) || candidate.name === this.name; + function useCustomRule(rule, schema, parentSchema, it) { + if (self._opts.validateSchema !== false) { + var deps = rule.definition.dependencies; + if (deps && !deps.every(function(keyword) { + return Object.prototype.hasOwnProperty.call(parentSchema, keyword); + })) + throw new Error('parent schema must have all required keywords: ' + deps.join(',')); + + var validateSchema = rule.definition.validateSchema; + if (validateSchema) { + var valid = validateSchema(schema); + if (!valid) { + var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors); + if (self._opts.validateSchema == 'log') self.logger.error(message); + else throw new Error(message); + } } - return this.prototype.isPrototypeOf(instance); } - return false; - } -}; -var decorateServiceException = /* @__PURE__ */ __name((exception, additions = {}) => { - Object.entries(additions).filter(([, v]) => v !== void 0).forEach(([k, v]) => { - if (exception[k] == void 0 || exception[k] === "") { - exception[k] = v; + + var compile = rule.definition.compile + , inline = rule.definition.inline + , macro = rule.definition.macro; + + var validate; + if (compile) { + validate = compile.call(self, schema, parentSchema, it); + } else if (macro) { + validate = macro.call(self, schema, parentSchema, it); + if (opts.validateSchema !== false) self.validateSchema(validate, true); + } else if (inline) { + validate = inline.call(self, it, rule.keyword, schema, parentSchema); + } else { + validate = rule.definition.validate; + if (!validate) return; } - }); - const message = exception.message || exception.Message || "UnknownError"; - exception.message = message; - delete exception.Message; - return exception; -}, "decorateServiceException"); -// src/default-error-handler.ts -var throwDefaultError = /* @__PURE__ */ __name(({ output, parsedBody, exceptionCtor, errorCode }) => { - const $metadata = deserializeMetadata(output); - const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : void 0; - const response = new exceptionCtor({ - name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError", - $fault: "client", - $metadata - }); - throw decorateServiceException(response, parsedBody); -}, "throwDefaultError"); -var withBaseException = /* @__PURE__ */ __name((ExceptionCtor) => { - return ({ output, parsedBody, errorCode }) => { - throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode }); - }; -}, "withBaseException"); -var deserializeMetadata = /* @__PURE__ */ __name((output) => ({ - httpStatusCode: output.statusCode, - requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], - extendedRequestId: output.headers["x-amz-id-2"], - cfId: output.headers["x-amz-cf-id"] -}), "deserializeMetadata"); + if (validate === undefined) + throw new Error('custom keyword "' + rule.keyword + '"failed to compile'); -// src/defaults-mode.ts -var loadConfigsForDefaultMode = /* @__PURE__ */ __name((mode) => { - switch (mode) { - case "standard": - return { - retryMode: "standard", - connectionTimeout: 3100 - }; - case "in-region": - return { - retryMode: "standard", - connectionTimeout: 1100 - }; - case "cross-region": - return { - retryMode: "standard", - connectionTimeout: 3100 - }; - case "mobile": - return { - retryMode: "standard", - connectionTimeout: 3e4 - }; - default: - return {}; + var index = customRules.length; + customRules[index] = validate; + + return { + code: 'customRule' + index, + validate: validate + }; } -}, "loadConfigsForDefaultMode"); +} -// src/emitWarningIfUnsupportedVersion.ts -var warningEmitted = false; -var emitWarningIfUnsupportedVersion = /* @__PURE__ */ __name((version) => { - if (version && !warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 16) { - warningEmitted = true; + +/** + * Checks if the schema is currently compiled + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean) + */ +function checkCompiling(schema, root, baseId) { + /* jshint validthis: true */ + var index = compIndex.call(this, schema, root, baseId); + if (index >= 0) return { index: index, compiling: true }; + index = this._compilations.length; + this._compilations[index] = { + schema: schema, + root: root, + baseId: baseId + }; + return { index: index, compiling: false }; +} + + +/** + * Removes the schema from the currently compiled list + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + */ +function endCompiling(schema, root, baseId) { + /* jshint validthis: true */ + var i = compIndex.call(this, schema, root, baseId); + if (i >= 0) this._compilations.splice(i, 1); +} + + +/** + * Index of schema compilation in the currently compiled list + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + * @return {Integer} compilation index + */ +function compIndex(schema, root, baseId) { + /* jshint validthis: true */ + for (var i=0; i { - const checksumAlgorithms = []; - for (const id in import_types.AlgorithmId) { - const algorithmId = import_types.AlgorithmId[id]; - if (runtimeConfig[algorithmId] === void 0) { - continue; - } - checksumAlgorithms.push({ - algorithmId: () => algorithmId, - checksumConstructor: () => runtimeConfig[algorithmId] - }); - } - return { - addChecksumAlgorithm(algo) { - checksumAlgorithms.push(algo); - }, - checksumAlgorithms() { - return checksumAlgorithms; - } - }; -}, "getChecksumConfiguration"); -var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { - const runtimeConfig = {}; - clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { - runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); - }); - return runtimeConfig; -}, "resolveChecksumRuntimeConfig"); +/***/ }), -// src/extensions/retry.ts -var getRetryConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return { - setRetryStrategy(retryStrategy) { - runtimeConfig.retryStrategy = retryStrategy; - }, - retryStrategy() { - return runtimeConfig.retryStrategy; - } - }; -}, "getRetryConfiguration"); -var resolveRetryRuntimeConfig = /* @__PURE__ */ __name((retryStrategyConfiguration) => { - const runtimeConfig = {}; - runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy(); - return runtimeConfig; -}, "resolveRetryRuntimeConfig"); +/***/ 63896: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// src/extensions/defaultExtensionConfiguration.ts -var getDefaultExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return Object.assign(getChecksumConfiguration(runtimeConfig), getRetryConfiguration(runtimeConfig)); -}, "getDefaultExtensionConfiguration"); -var getDefaultClientConfiguration = getDefaultExtensionConfiguration; -var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { - return Object.assign(resolveChecksumRuntimeConfig(config), resolveRetryRuntimeConfig(config)); -}, "resolveDefaultRuntimeConfig"); +"use strict"; -// src/get-array-if-single-item.ts -var getArrayIfSingleItem = /* @__PURE__ */ __name((mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray], "getArrayIfSingleItem"); -// src/get-value-from-text-node.ts -var getValueFromTextNode = /* @__PURE__ */ __name((obj) => { - const textNodeName = "#text"; - for (const key in obj) { - if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== void 0) { - obj[key] = obj[key][textNodeName]; - } else if (typeof obj[key] === "object" && obj[key] !== null) { - obj[key] = getValueFromTextNode(obj[key]); - } - } - return obj; -}, "getValueFromTextNode"); +var URI = __nccwpck_require__(70020) + , equal = __nccwpck_require__(28206) + , util = __nccwpck_require__(76578) + , SchemaObject = __nccwpck_require__(37605) + , traverse = __nccwpck_require__(52533); -// src/is-serializable-header-value.ts -var isSerializableHeaderValue = /* @__PURE__ */ __name((value) => { - return value != null; -}, "isSerializableHeaderValue"); +module.exports = resolve; -// src/lazy-json.ts -var LazyJsonString = /* @__PURE__ */ __name(function LazyJsonString2(val) { - const str = Object.assign(new String(val), { - deserializeJSON() { - return JSON.parse(String(val)); - }, - toString() { - return String(val); - }, - toJSON() { - return String(val); - } - }); - return str; -}, "LazyJsonString"); -LazyJsonString.from = (object) => { - if (object && typeof object === "object" && (object instanceof LazyJsonString || "deserializeJSON" in object)) { - return object; - } else if (typeof object === "string" || Object.getPrototypeOf(object) === String.prototype) { - return LazyJsonString(String(object)); - } - return LazyJsonString(JSON.stringify(object)); -}; -LazyJsonString.fromObject = LazyJsonString.from; +resolve.normalizeId = normalizeId; +resolve.fullPath = getFullPath; +resolve.url = resolveUrl; +resolve.ids = resolveIds; +resolve.inlineRef = inlineRef; +resolve.schema = resolveSchema; -// src/NoOpLogger.ts -var NoOpLogger = class { - static { - __name(this, "NoOpLogger"); - } - trace() { - } - debug() { +/** + * [resolve and compile the references ($ref)] + * @this Ajv + * @param {Function} compile reference to schema compilation funciton (localCompile) + * @param {Object} root object with information about the root schema for the current schema + * @param {String} ref reference to resolve + * @return {Object|Function} schema object (if the schema can be inlined) or validation function + */ +function resolve(compile, root, ref) { + /* jshint validthis: true */ + var refVal = this._refs[ref]; + if (typeof refVal == 'string') { + if (this._refs[refVal]) refVal = this._refs[refVal]; + else return resolve.call(this, compile, root, refVal); } - info() { + + refVal = refVal || this._schemas[ref]; + if (refVal instanceof SchemaObject) { + return inlineRef(refVal.schema, this._opts.inlineRefs) + ? refVal.schema + : refVal.validate || this._compile(refVal); } - warn() { + + var res = resolveSchema.call(this, root, ref); + var schema, v, baseId; + if (res) { + schema = res.schema; + root = res.root; + baseId = res.baseId; } - error() { + + if (schema instanceof SchemaObject) { + v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId); + } else if (schema !== undefined) { + v = inlineRef(schema, this._opts.inlineRefs) + ? schema + : compile.call(this, schema, root, undefined, baseId); } -}; -// src/object-mapping.ts -function map(arg0, arg1, arg2) { - let target; - let filter; - let instructions; - if (typeof arg1 === "undefined" && typeof arg2 === "undefined") { - target = {}; - instructions = arg0; - } else { - target = arg0; - if (typeof arg1 === "function") { - filter = arg1; - instructions = arg2; - return mapWithFilter(target, filter, instructions); + return v; +} + + +/** + * Resolve schema, its root and baseId + * @this Ajv + * @param {Object} root root object with properties schema, refVal, refs + * @param {String} ref reference to resolve + * @return {Object} object with properties schema, root, baseId + */ +function resolveSchema(root, ref) { + /* jshint validthis: true */ + var p = URI.parse(ref) + , refPath = _getFullPath(p) + , baseId = getFullPath(this._getId(root.schema)); + if (Object.keys(root.schema).length === 0 || refPath !== baseId) { + var id = normalizeId(refPath); + var refVal = this._refs[id]; + if (typeof refVal == 'string') { + return resolveRecursive.call(this, root, refVal, p); + } else if (refVal instanceof SchemaObject) { + if (!refVal.validate) this._compile(refVal); + root = refVal; } else { - instructions = arg1; - } - } - for (const key of Object.keys(instructions)) { - if (!Array.isArray(instructions[key])) { - target[key] = instructions[key]; - continue; + refVal = this._schemas[id]; + if (refVal instanceof SchemaObject) { + if (!refVal.validate) this._compile(refVal); + if (id == normalizeId(ref)) + return { schema: refVal, root: root, baseId: baseId }; + root = refVal; + } else { + return; + } } - applyInstruction(target, null, instructions, key); + if (!root.schema) return; + baseId = getFullPath(this._getId(root.schema)); } - return target; + return getJsonPointer.call(this, p, baseId, root.schema, root); } -__name(map, "map"); -var convertMap = /* @__PURE__ */ __name((target) => { - const output = {}; - for (const [k, v] of Object.entries(target || {})) { - output[k] = [, v]; - } - return output; -}, "convertMap"); -var take = /* @__PURE__ */ __name((source, instructions) => { - const out = {}; - for (const key in instructions) { - applyInstruction(out, source, instructions, key); + + +/* @this Ajv */ +function resolveRecursive(root, ref, parsedRef) { + /* jshint validthis: true */ + var res = resolveSchema.call(this, root, ref); + if (res) { + var schema = res.schema; + var baseId = res.baseId; + root = res.root; + var id = this._getId(schema); + if (id) baseId = resolveUrl(baseId, id); + return getJsonPointer.call(this, parsedRef, baseId, schema, root); } - return out; -}, "take"); -var mapWithFilter = /* @__PURE__ */ __name((target, filter, instructions) => { - return map( - target, - Object.entries(instructions).reduce( - (_instructions, [key, value]) => { - if (Array.isArray(value)) { - _instructions[key] = value; - } else { - if (typeof value === "function") { - _instructions[key] = [filter, value()]; - } else { - _instructions[key] = [filter, value]; +} + + +var PREVENT_SCOPE_CHANGE = util.toHash(['properties', 'patternProperties', 'enum', 'dependencies', 'definitions']); +/* @this Ajv */ +function getJsonPointer(parsedRef, baseId, schema, root) { + /* jshint validthis: true */ + parsedRef.fragment = parsedRef.fragment || ''; + if (parsedRef.fragment.slice(0,1) != '/') return; + var parts = parsedRef.fragment.split('/'); + + for (var i = 1; i < parts.length; i++) { + var part = parts[i]; + if (part) { + part = util.unescapeFragment(part); + schema = schema[part]; + if (schema === undefined) break; + var id; + if (!PREVENT_SCOPE_CHANGE[part]) { + id = this._getId(schema); + if (id) baseId = resolveUrl(baseId, id); + if (schema.$ref) { + var $ref = resolveUrl(baseId, schema.$ref); + var res = resolveSchema.call(this, root, $ref); + if (res) { + schema = res.schema; + root = res.root; + baseId = res.baseId; } } - return _instructions; - }, - {} - ) - ); -}, "mapWithFilter"); -var applyInstruction = /* @__PURE__ */ __name((target, source, instructions, targetKey) => { - if (source !== null) { - let instruction = instructions[targetKey]; - if (typeof instruction === "function") { - instruction = [, instruction]; - } - const [filter2 = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction; - if (typeof filter2 === "function" && filter2(source[sourceKey]) || typeof filter2 !== "function" && !!filter2) { - target[targetKey] = valueFn(source[sourceKey]); - } - return; - } - let [filter, value] = instructions[targetKey]; - if (typeof value === "function") { - let _value; - const defaultFilterPassed = filter === void 0 && (_value = value()) != null; - const customFilterPassed = typeof filter === "function" && !!filter(void 0) || typeof filter !== "function" && !!filter; - if (defaultFilterPassed) { - target[targetKey] = _value; - } else if (customFilterPassed) { - target[targetKey] = value(); - } - } else { - const defaultFilterPassed = filter === void 0 && value != null; - const customFilterPassed = typeof filter === "function" && !!filter(value) || typeof filter !== "function" && !!filter; - if (defaultFilterPassed || customFilterPassed) { - target[targetKey] = value; + } } } -}, "applyInstruction"); -var nonNullish = /* @__PURE__ */ __name((_) => _ != null, "nonNullish"); -var pass = /* @__PURE__ */ __name((_) => _, "pass"); - -// src/quote-header.ts -function quoteHeader(part) { - if (part.includes(",") || part.includes('"')) { - part = `"${part.replace(/"/g, '\\"')}"`; - } - return part; + if (schema !== undefined && schema !== root.schema) + return { schema: schema, root: root, baseId: baseId }; } -__name(quoteHeader, "quoteHeader"); -// src/resolve-path.ts +var SIMPLE_INLINED = util.toHash([ + 'type', 'format', 'pattern', + 'maxLength', 'minLength', + 'maxProperties', 'minProperties', + 'maxItems', 'minItems', + 'maximum', 'minimum', + 'uniqueItems', 'multipleOf', + 'required', 'enum' +]); +function inlineRef(schema, limit) { + if (limit === false) return false; + if (limit === undefined || limit === true) return checkNoRef(schema); + else if (limit) return countKeys(schema) <= limit; +} -// src/ser-utils.ts -var serializeFloat = /* @__PURE__ */ __name((value) => { - if (value !== value) { - return "NaN"; - } - switch (value) { - case Infinity: - return "Infinity"; - case -Infinity: - return "-Infinity"; - default: - return value; - } -}, "serializeFloat"); -var serializeDateTime = /* @__PURE__ */ __name((date) => date.toISOString().replace(".000Z", "Z"), "serializeDateTime"); -// src/serde-json.ts -var _json = /* @__PURE__ */ __name((obj) => { - if (obj == null) { - return {}; - } - if (Array.isArray(obj)) { - return obj.filter((_) => _ != null).map(_json); - } - if (typeof obj === "object") { - const target = {}; - for (const key of Object.keys(obj)) { - if (obj[key] == null) { - continue; - } - target[key] = _json(obj[key]); +function checkNoRef(schema) { + var item; + if (Array.isArray(schema)) { + for (var i=0; i { - const z = value.length; - const values = []; - let withinQuotes = false; - let prevChar = void 0; - let anchor = 0; - for (let i = 0; i < z; ++i) { - const char = value[i]; - switch (char) { - case `"`: - if (prevChar !== "\\") { - withinQuotes = !withinQuotes; - } - break; - case ",": - if (!withinQuotes) { - values.push(value.slice(anchor, i)); - anchor = i + 1; - } - break; - default: - } - prevChar = char; - } - values.push(value.slice(anchor)); - return values.map((v) => { - v = v.trim(); - const z2 = v.length; - if (z2 < 2) { - return v; - } - if (v[0] === `"` && v[z2 - 1] === `"`) { - v = v.slice(1, z2 - 1); - } - return v.replace(/\\"/g, '"'); - }); -}, "splitHeader"); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +function getFullPath(id, normalize) { + if (normalize !== false) id = normalizeId(id); + var p = URI.parse(id); + return _getFullPath(p); +} +function _getFullPath(p) { + return URI.serialize(p).split('#')[0] + '#'; +} -/***/ }), -/***/ 55756: -/***/ ((module) => { +var TRAILING_SLASH_HASH = /#\/?$/; +function normalizeId(id) { + return id ? id.replace(TRAILING_SLASH_HASH, '') : ''; +} -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -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); -// src/index.ts -var src_exports = {}; -__export(src_exports, { - AlgorithmId: () => AlgorithmId, - EndpointURLScheme: () => EndpointURLScheme, - FieldPosition: () => FieldPosition, - HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, - HttpAuthLocation: () => HttpAuthLocation, - IniSectionType: () => IniSectionType, - RequestHandlerProtocol: () => RequestHandlerProtocol, - SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, - getDefaultClientConfiguration: () => getDefaultClientConfiguration, - resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig -}); -module.exports = __toCommonJS(src_exports); +function resolveUrl(baseId, id) { + id = normalizeId(id); + return URI.resolve(baseId, id); +} -// src/auth/auth.ts -var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { - HttpAuthLocation2["HEADER"] = "header"; - HttpAuthLocation2["QUERY"] = "query"; - return HttpAuthLocation2; -})(HttpAuthLocation || {}); -// src/auth/HttpApiKeyAuth.ts -var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { - HttpApiKeyAuthLocation2["HEADER"] = "header"; - HttpApiKeyAuthLocation2["QUERY"] = "query"; - return HttpApiKeyAuthLocation2; -})(HttpApiKeyAuthLocation || {}); +/* @this Ajv */ +function resolveIds(schema) { + var schemaId = normalizeId(this._getId(schema)); + var baseIds = {'': schemaId}; + var fullPaths = {'': getFullPath(schemaId, false)}; + var localRefs = {}; + var self = this; -// src/endpoint.ts -var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { - EndpointURLScheme2["HTTP"] = "http"; - EndpointURLScheme2["HTTPS"] = "https"; - return EndpointURLScheme2; -})(EndpointURLScheme || {}); + traverse(schema, {allKeys: true}, function(sch, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (jsonPtr === '') return; + var id = self._getId(sch); + var baseId = baseIds[parentJsonPtr]; + var fullPath = fullPaths[parentJsonPtr] + '/' + parentKeyword; + if (keyIndex !== undefined) + fullPath += '/' + (typeof keyIndex == 'number' ? keyIndex : util.escapeFragment(keyIndex)); -// src/extensions/checksum.ts -var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { - AlgorithmId2["MD5"] = "md5"; - AlgorithmId2["CRC32"] = "crc32"; - AlgorithmId2["CRC32C"] = "crc32c"; - AlgorithmId2["SHA1"] = "sha1"; - AlgorithmId2["SHA256"] = "sha256"; - return AlgorithmId2; -})(AlgorithmId || {}); -var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const checksumAlgorithms = []; - if (runtimeConfig.sha256 !== void 0) { - checksumAlgorithms.push({ - algorithmId: () => "sha256" /* SHA256 */, - checksumConstructor: () => runtimeConfig.sha256 - }); - } - if (runtimeConfig.md5 != void 0) { - checksumAlgorithms.push({ - algorithmId: () => "md5" /* MD5 */, - checksumConstructor: () => runtimeConfig.md5 - }); - } - return { - addChecksumAlgorithm(algo) { - checksumAlgorithms.push(algo); - }, - checksumAlgorithms() { - return checksumAlgorithms; + if (typeof id == 'string') { + id = baseId = normalizeId(baseId ? URI.resolve(baseId, id) : id); + + var refVal = self._refs[id]; + if (typeof refVal == 'string') refVal = self._refs[refVal]; + if (refVal && refVal.schema) { + if (!equal(sch, refVal.schema)) + throw new Error('id "' + id + '" resolves to more than one schema'); + } else if (id != normalizeId(fullPath)) { + if (id[0] == '#') { + if (localRefs[id] && !equal(sch, localRefs[id])) + throw new Error('id "' + id + '" resolves to more than one schema'); + localRefs[id] = sch; + } else { + self._refs[id] = fullPath; + } + } } - }; -}, "getChecksumConfiguration"); -var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { - const runtimeConfig = {}; - clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { - runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + baseIds[jsonPtr] = baseId; + fullPaths[jsonPtr] = fullPath; }); - return runtimeConfig; -}, "resolveChecksumRuntimeConfig"); - -// src/extensions/defaultClientConfiguration.ts -var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return getChecksumConfiguration(runtimeConfig); -}, "getDefaultClientConfiguration"); -var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { - return resolveChecksumRuntimeConfig(config); -}, "resolveDefaultRuntimeConfig"); - -// src/http.ts -var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { - FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; - FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; - return FieldPosition2; -})(FieldPosition || {}); - -// src/middleware.ts -var SMITHY_CONTEXT_KEY = "__smithy_context"; - -// src/profile.ts -var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { - IniSectionType2["PROFILE"] = "profile"; - IniSectionType2["SSO_SESSION"] = "sso-session"; - IniSectionType2["SERVICES"] = "services"; - return IniSectionType2; -})(IniSectionType || {}); - -// src/transfer.ts -var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { - RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; - RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; - RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; - return RequestHandlerProtocol2; -})(RequestHandlerProtocol || {}); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); + return localRefs; +} /***/ }), -/***/ 14681: +/***/ 68561: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -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); +"use strict"; -// src/index.ts -var src_exports = {}; -__export(src_exports, { - parseUrl: () => parseUrl -}); -module.exports = __toCommonJS(src_exports); -var import_querystring_parser = __nccwpck_require__(4769); -var parseUrl = /* @__PURE__ */ __name((url) => { - if (typeof url === "string") { - return parseUrl(new URL(url)); - } - const { hostname, pathname, port, protocol, search } = url; - let query; - if (search) { - query = (0, import_querystring_parser.parseQueryString)(search); - } - return { - hostname, - port: port ? parseInt(port) : void 0, - protocol, - path: pathname, - query - }; -}, "parseUrl"); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +var ruleModules = __nccwpck_require__(85810) + , toHash = (__nccwpck_require__(76578).toHash); +module.exports = function rules() { + var RULES = [ + { type: 'number', + rules: [ { 'maximum': ['exclusiveMaximum'] }, + { 'minimum': ['exclusiveMinimum'] }, 'multipleOf', 'format'] }, + { type: 'string', + rules: [ 'maxLength', 'minLength', 'pattern', 'format' ] }, + { type: 'array', + rules: [ 'maxItems', 'minItems', 'items', 'contains', 'uniqueItems' ] }, + { type: 'object', + rules: [ 'maxProperties', 'minProperties', 'required', 'dependencies', 'propertyNames', + { 'properties': ['additionalProperties', 'patternProperties'] } ] }, + { rules: [ '$ref', 'const', 'enum', 'not', 'anyOf', 'oneOf', 'allOf', 'if' ] } + ]; + var ALL = [ 'type', '$comment' ]; + var KEYWORDS = [ + '$schema', '$id', 'id', '$data', '$async', 'title', + 'description', 'default', 'definitions', + 'examples', 'readOnly', 'writeOnly', + 'contentMediaType', 'contentEncoding', + 'additionalItems', 'then', 'else' + ]; + var TYPES = [ 'number', 'integer', 'string', 'array', 'object', 'boolean', 'null' ]; + RULES.all = toHash(ALL); + RULES.types = toHash(TYPES); -/***/ }), + RULES.forEach(function (group) { + group.rules = group.rules.map(function (keyword) { + var implKeywords; + if (typeof keyword == 'object') { + var key = Object.keys(keyword)[0]; + implKeywords = keyword[key]; + keyword = key; + implKeywords.forEach(function (k) { + ALL.push(k); + RULES.all[k] = true; + }); + } + ALL.push(keyword); + var rule = RULES.all[keyword] = { + keyword: keyword, + code: ruleModules[keyword], + implements: implKeywords + }; + return rule; + }); -/***/ 30305: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + RULES.all.$comment = { + keyword: '$comment', + code: ruleModules.$comment + }; -"use strict"; + if (group.type) RULES.types[group.type] = group; + }); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fromBase64 = void 0; -const util_buffer_from_1 = __nccwpck_require__(31381); -const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; -const fromBase64 = (input) => { - if ((input.length * 3) % 4 !== 0) { - throw new TypeError(`Incorrect padding on base64 string.`); - } - if (!BASE64_REGEX.exec(input)) { - throw new TypeError(`Invalid base64 string.`); - } - const buffer = (0, util_buffer_from_1.fromString)(input, "base64"); - return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); + RULES.keywords = toHash(ALL.concat(KEYWORDS)); + RULES.custom = {}; + + return RULES; }; -exports.fromBase64 = fromBase64; /***/ }), -/***/ 75600: +/***/ 37605: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -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 __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +"use strict"; -// src/index.ts -var src_exports = {}; -module.exports = __toCommonJS(src_exports); -__reExport(src_exports, __nccwpck_require__(30305), module.exports); -__reExport(src_exports, __nccwpck_require__(74730), module.exports); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +var util = __nccwpck_require__(76578); + +module.exports = SchemaObject; +function SchemaObject(obj) { + util.copy(obj, this); +} /***/ }), -/***/ 74730: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 64580: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toBase64 = void 0; -const util_buffer_from_1 = __nccwpck_require__(31381); -const util_utf8_1 = __nccwpck_require__(41895); -const toBase64 = (_input) => { - let input; - if (typeof _input === "string") { - input = (0, util_utf8_1.fromUtf8)(_input); - } - else { - input = _input; - } - if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { - throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); + +// https://mathiasbynens.be/notes/javascript-encoding +// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode +module.exports = function ucs2length(str) { + var length = 0 + , len = str.length + , pos = 0 + , value; + while (pos < len) { + length++; + value = str.charCodeAt(pos++); + if (value >= 0xD800 && value <= 0xDBFF && pos < len) { + // high surrogate, and there is a next character + value = str.charCodeAt(pos); + if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate } - return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); + } + return length; }; -exports.toBase64 = toBase64; /***/ }), -/***/ 68075: +/***/ 76578: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -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); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - calculateBodyLength: () => calculateBodyLength -}); -module.exports = __toCommonJS(src_exports); +"use strict"; -// src/calculateBodyLength.ts -var import_fs = __nccwpck_require__(57147); -var calculateBodyLength = /* @__PURE__ */ __name((body) => { - if (!body) { - return 0; - } - if (typeof body === "string") { - return Buffer.byteLength(body); - } else if (typeof body.byteLength === "number") { - return body.byteLength; - } else if (typeof body.size === "number") { - return body.size; - } else if (typeof body.start === "number" && typeof body.end === "number") { - return body.end + 1 - body.start; - } else if (typeof body.path === "string" || Buffer.isBuffer(body.path)) { - return (0, import_fs.lstatSync)(body.path).size; - } else if (typeof body.fd === "number") { - return (0, import_fs.fstatSync)(body.fd).size; - } - throw new Error(`Body Length computation failed for ${body}`); -}, "calculateBodyLength"); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +module.exports = { + copy: copy, + checkDataType: checkDataType, + checkDataTypes: checkDataTypes, + coerceToTypes: coerceToTypes, + toHash: toHash, + getProperty: getProperty, + escapeQuotes: escapeQuotes, + equal: __nccwpck_require__(28206), + ucs2length: __nccwpck_require__(64580), + varOccurences: varOccurences, + varReplace: varReplace, + schemaHasRules: schemaHasRules, + schemaHasRulesExcept: schemaHasRulesExcept, + schemaUnknownRules: schemaUnknownRules, + toQuotedString: toQuotedString, + getPathExpr: getPathExpr, + getPath: getPath, + getData: getData, + unescapeFragment: unescapeFragment, + unescapeJsonPointer: unescapeJsonPointer, + escapeFragment: escapeFragment, + escapeJsonPointer: escapeJsonPointer +}; -/***/ }), +function copy(o, to) { + to = to || {}; + for (var key in o) to[key] = o[key]; + return to; +} -/***/ 31381: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -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 }); +function checkDataType(dataType, data, strictNumbers, negate) { + var EQUAL = negate ? ' !== ' : ' === ' + , AND = negate ? ' || ' : ' && ' + , OK = negate ? '!' : '' + , NOT = negate ? '' : '!'; + switch (dataType) { + case 'null': return data + EQUAL + 'null'; + case 'array': return OK + 'Array.isArray(' + data + ')'; + case 'object': return '(' + OK + data + AND + + 'typeof ' + data + EQUAL + '"object"' + AND + + NOT + 'Array.isArray(' + data + '))'; + case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND + + NOT + '(' + data + ' % 1)' + + AND + data + EQUAL + data + + (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')'; + case 'number': return '(typeof ' + data + EQUAL + '"' + dataType + '"' + + (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')'; + default: return 'typeof ' + data + EQUAL + '"' + dataType + '"'; } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +} -// src/index.ts -var src_exports = {}; -__export(src_exports, { - fromArrayBuffer: () => fromArrayBuffer, - fromString: () => fromString -}); -module.exports = __toCommonJS(src_exports); -var import_is_array_buffer = __nccwpck_require__(10780); -var import_buffer = __nccwpck_require__(14300); -var fromArrayBuffer = /* @__PURE__ */ __name((input, offset = 0, length = input.byteLength - offset) => { - if (!(0, import_is_array_buffer.isArrayBuffer)(input)) { - throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); - } - return import_buffer.Buffer.from(input, offset, length); -}, "fromArrayBuffer"); -var fromString = /* @__PURE__ */ __name((input, encoding) => { - if (typeof input !== "string") { - throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); + +function checkDataTypes(dataTypes, data, strictNumbers) { + switch (dataTypes.length) { + case 1: return checkDataType(dataTypes[0], data, strictNumbers, true); + default: + var code = ''; + var types = toHash(dataTypes); + if (types.array && types.object) { + code = types.null ? '(': '(!' + data + ' || '; + code += 'typeof ' + data + ' !== "object")'; + delete types.null; + delete types.array; + delete types.object; + } + if (types.number) delete types.integer; + for (var t in types) + code += (code ? ' && ' : '' ) + checkDataType(t, data, strictNumbers, true); + + return code; } - return encoding ? import_buffer.Buffer.from(input, encoding) : import_buffer.Buffer.from(input); -}, "fromString"); -// Annotate the CommonJS export names for ESM import in node: +} -0 && (0); +var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]); +function coerceToTypes(optionCoerceTypes, dataTypes) { + if (Array.isArray(dataTypes)) { + var types = []; + for (var i=0; i { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -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); +var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; +var SINGLE_QUOTE = /'|\\/g; +function getProperty(key) { + return typeof key == 'number' + ? '[' + key + ']' + : IDENTIFIER.test(key) + ? '.' + key + : "['" + escapeQuotes(key) + "']"; +} -// src/index.ts -var src_exports = {}; -__export(src_exports, { - SelectorType: () => SelectorType, - booleanSelector: () => booleanSelector, - numberSelector: () => numberSelector -}); -module.exports = __toCommonJS(src_exports); -// src/booleanSelector.ts -var booleanSelector = /* @__PURE__ */ __name((obj, key, type) => { - if (!(key in obj)) - return void 0; - if (obj[key] === "true") - return true; - if (obj[key] === "false") - return false; - throw new Error(`Cannot load ${type} "${key}". Expected "true" or "false", got ${obj[key]}.`); -}, "booleanSelector"); +function escapeQuotes(str) { + return str.replace(SINGLE_QUOTE, '\\$&') + .replace(/\n/g, '\\n') + .replace(/\r/g, '\\r') + .replace(/\f/g, '\\f') + .replace(/\t/g, '\\t'); +} -// src/numberSelector.ts -var numberSelector = /* @__PURE__ */ __name((obj, key, type) => { - if (!(key in obj)) - return void 0; - const numberValue = parseInt(obj[key], 10); - if (Number.isNaN(numberValue)) { - throw new TypeError(`Cannot load ${type} '${key}'. Expected number, got '${obj[key]}'.`); - } - return numberValue; -}, "numberSelector"); -// src/types.ts -var SelectorType = /* @__PURE__ */ ((SelectorType2) => { - SelectorType2["ENV"] = "env"; - SelectorType2["CONFIG"] = "shared config entry"; - return SelectorType2; -})(SelectorType || {}); -// Annotate the CommonJS export names for ESM import in node: +function varOccurences(str, dataVar) { + dataVar += '[^0-9]'; + var matches = str.match(new RegExp(dataVar, 'g')); + return matches ? matches.length : 0; +} -0 && (0); +function varReplace(str, dataVar, expr) { + dataVar += '([^0-9])'; + expr = expr.replace(/\$/g, '$$$$'); + return str.replace(new RegExp(dataVar, 'g'), expr + '$1'); +} -/***/ }), +function schemaHasRules(schema, rules) { + if (typeof schema == 'boolean') return !schema; + for (var key in schema) if (rules[key]) return true; +} -/***/ 72429: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -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 __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -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); +function schemaHasRulesExcept(schema, rules, exceptKeyword) { + if (typeof schema == 'boolean') return !schema && exceptKeyword != 'not'; + for (var key in schema) if (key != exceptKeyword && rules[key]) return true; +} -// src/index.ts -var src_exports = {}; -__export(src_exports, { - resolveDefaultsModeConfig: () => resolveDefaultsModeConfig -}); -module.exports = __toCommonJS(src_exports); -// src/resolveDefaultsModeConfig.ts -var import_config_resolver = __nccwpck_require__(53098); -var import_node_config_provider = __nccwpck_require__(33461); -var import_property_provider = __nccwpck_require__(79721); +function schemaUnknownRules(schema, rules) { + if (typeof schema == 'boolean') return; + for (var key in schema) if (!rules[key]) return key; +} -// src/constants.ts -var AWS_EXECUTION_ENV = "AWS_EXECUTION_ENV"; -var AWS_REGION_ENV = "AWS_REGION"; -var AWS_DEFAULT_REGION_ENV = "AWS_DEFAULT_REGION"; -var ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED"; -var DEFAULTS_MODE_OPTIONS = ["in-region", "cross-region", "mobile", "standard", "legacy"]; -var IMDS_REGION_PATH = "/latest/meta-data/placement/region"; -// src/defaultsModeConfig.ts -var AWS_DEFAULTS_MODE_ENV = "AWS_DEFAULTS_MODE"; -var AWS_DEFAULTS_MODE_CONFIG = "defaults_mode"; -var NODE_DEFAULTS_MODE_CONFIG_OPTIONS = { - environmentVariableSelector: (env) => { - return env[AWS_DEFAULTS_MODE_ENV]; - }, - configFileSelector: (profile) => { - return profile[AWS_DEFAULTS_MODE_CONFIG]; - }, - default: "legacy" -}; +function toQuotedString(str) { + return '\'' + escapeQuotes(str) + '\''; +} -// src/resolveDefaultsModeConfig.ts -var resolveDefaultsModeConfig = /* @__PURE__ */ __name(({ - region = (0, import_node_config_provider.loadConfig)(import_config_resolver.NODE_REGION_CONFIG_OPTIONS), - defaultsMode = (0, import_node_config_provider.loadConfig)(NODE_DEFAULTS_MODE_CONFIG_OPTIONS) -} = {}) => (0, import_property_provider.memoize)(async () => { - const mode = typeof defaultsMode === "function" ? await defaultsMode() : defaultsMode; - switch (mode?.toLowerCase()) { - case "auto": - return resolveNodeDefaultsModeAuto(region); - case "in-region": - case "cross-region": - case "mobile": - case "standard": - case "legacy": - return Promise.resolve(mode?.toLocaleLowerCase()); - case void 0: - return Promise.resolve("legacy"); - default: - throw new Error( - `Invalid parameter for "defaultsMode", expect ${DEFAULTS_MODE_OPTIONS.join(", ")}, got ${mode}` - ); - } -}), "resolveDefaultsModeConfig"); -var resolveNodeDefaultsModeAuto = /* @__PURE__ */ __name(async (clientRegion) => { - if (clientRegion) { - const resolvedRegion = typeof clientRegion === "function" ? await clientRegion() : clientRegion; - const inferredRegion = await inferPhysicalRegion(); - if (!inferredRegion) { - return "standard"; - } - if (resolvedRegion === inferredRegion) { - return "in-region"; - } else { - return "cross-region"; - } - } - return "standard"; -}, "resolveNodeDefaultsModeAuto"); -var inferPhysicalRegion = /* @__PURE__ */ __name(async () => { - if (process.env[AWS_EXECUTION_ENV] && (process.env[AWS_REGION_ENV] || process.env[AWS_DEFAULT_REGION_ENV])) { - return process.env[AWS_REGION_ENV] ?? process.env[AWS_DEFAULT_REGION_ENV]; - } - if (!process.env[ENV_IMDS_DISABLED]) { - try { - const { getInstanceMetadataEndpoint, httpRequest } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(7477))); - const endpoint = await getInstanceMetadataEndpoint(); - return (await httpRequest({ ...endpoint, path: IMDS_REGION_PATH })).toString(); - } catch (e) { - } - } -}, "inferPhysicalRegion"); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +function getPathExpr(currentPath, expr, jsonPointers, isNumber) { + var path = jsonPointers // false by default + ? '\'/\' + ' + expr + (isNumber ? '' : '.replace(/~/g, \'~0\').replace(/\\//g, \'~1\')') + : (isNumber ? '\'[\' + ' + expr + ' + \']\'' : '\'[\\\'\' + ' + expr + ' + \'\\\']\''); + return joinPaths(currentPath, path); +} +function getPath(currentPath, prop, jsonPointers) { + var path = jsonPointers // false by default + ? toQuotedString('/' + escapeJsonPointer(prop)) + : toQuotedString(getProperty(prop)); + return joinPaths(currentPath, path); +} -/***/ }), -/***/ 45473: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; +var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; +function getData($data, lvl, paths) { + var up, jsonPointer, data, matches; + if ($data === '') return 'rootData'; + if ($data[0] == '/') { + if (!JSON_POINTER.test($data)) throw new Error('Invalid JSON-pointer: ' + $data); + jsonPointer = $data; + data = 'rootData'; + } else { + matches = $data.match(RELATIVE_JSON_POINTER); + if (!matches) throw new Error('Invalid JSON-pointer: ' + $data); + up = +matches[1]; + jsonPointer = matches[2]; + if (jsonPointer == '#') { + if (up >= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl); + return paths[lvl - up]; + } -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -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 }); + if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl); + data = 'data' + ((lvl - up) || ''); + if (!jsonPointer) return data; } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - EndpointCache: () => EndpointCache, - EndpointError: () => EndpointError, - customEndpointFunctions: () => customEndpointFunctions, - isIpAddress: () => isIpAddress, - isValidHostLabel: () => isValidHostLabel, - resolveEndpoint: () => resolveEndpoint -}); -module.exports = __toCommonJS(src_exports); -// src/cache/EndpointCache.ts -var EndpointCache = class { - /** - * @param [size] - desired average maximum capacity. A buffer of 10 additional keys will be allowed - * before keys are dropped. - * @param [params] - list of params to consider as part of the cache key. - * - * If the params list is not populated, no caching will happen. - * This may be out of order depending on how the object is created and arrives to this class. - */ - constructor({ size, params }) { - this.data = /* @__PURE__ */ new Map(); - this.parameters = []; - this.capacity = size ?? 50; - if (params) { - this.parameters = params; - } - } - static { - __name(this, "EndpointCache"); - } - /** - * @param endpointParams - query for endpoint. - * @param resolver - provider of the value if not present. - * @returns endpoint corresponding to the query. - */ - get(endpointParams, resolver) { - const key = this.hash(endpointParams); - if (key === false) { - return resolver(); - } - if (!this.data.has(key)) { - if (this.data.size > this.capacity + 10) { - const keys = this.data.keys(); - let i = 0; - while (true) { - const { value, done } = keys.next(); - this.data.delete(value); - if (done || ++i > 10) { - break; - } - } - } - this.data.set(key, resolver()); - } - return this.data.get(key); - } - size() { - return this.data.size; - } - /** - * @returns cache key or false if not cachable. - */ - hash(endpointParams) { - let buffer = ""; - const { parameters } = this; - if (parameters.length === 0) { - return false; - } - for (const param of parameters) { - const val = String(endpointParams[param] ?? ""); - if (val.includes("|;")) { - return false; - } - buffer += val + "|;"; + var expr = data; + var segments = jsonPointer.split('/'); + for (var i=0; i IP_V4_REGEX.test(value) || value.startsWith("[") && value.endsWith("]"), "isIpAddress"); -// src/lib/isValidHostLabel.ts -var VALID_HOST_LABEL_REGEX = new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`); -var isValidHostLabel = /* @__PURE__ */ __name((value, allowSubDomains = false) => { - if (!allowSubDomains) { - return VALID_HOST_LABEL_REGEX.test(value); - } - const labels = value.split("."); - for (const label of labels) { - if (!isValidHostLabel(label)) { - return false; - } - } - return true; -}, "isValidHostLabel"); +function joinPaths (a, b) { + if (a == '""') return b; + return (a + ' + ' + b).replace(/([^\\])' \+ '/g, '$1'); +} -// src/utils/customEndpointFunctions.ts -var customEndpointFunctions = {}; -// src/debug/debugId.ts -var debugId = "endpoints"; +function unescapeFragment(str) { + return unescapeJsonPointer(decodeURIComponent(str)); +} -// src/debug/toDebugString.ts -function toDebugString(input) { - if (typeof input !== "object" || input == null) { - return input; - } - if ("ref" in input) { - return `$${toDebugString(input.ref)}`; - } - if ("fn" in input) { - return `${input.fn}(${(input.argv || []).map(toDebugString).join(", ")})`; - } - return JSON.stringify(input, null, 2); + +function escapeFragment(str) { + return encodeURIComponent(escapeJsonPointer(str)); } -__name(toDebugString, "toDebugString"); -// src/types/EndpointError.ts -var EndpointError = class extends Error { - static { - __name(this, "EndpointError"); - } - constructor(message) { - super(message); - this.name = "EndpointError"; - } -}; -// src/lib/booleanEquals.ts -var booleanEquals = /* @__PURE__ */ __name((value1, value2) => value1 === value2, "booleanEquals"); +function escapeJsonPointer(str) { + return str.replace(/~/g, '~0').replace(/\//g, '~1'); +} -// src/lib/getAttrPathList.ts -var getAttrPathList = /* @__PURE__ */ __name((path) => { - const parts = path.split("."); - const pathList = []; - for (const part of parts) { - const squareBracketIndex = part.indexOf("["); - if (squareBracketIndex !== -1) { - if (part.indexOf("]") !== part.length - 1) { - throw new EndpointError(`Path: '${path}' does not end with ']'`); - } - const arrayIndex = part.slice(squareBracketIndex + 1, -1); - if (Number.isNaN(parseInt(arrayIndex))) { - throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path}'`); - } - if (squareBracketIndex !== 0) { - pathList.push(part.slice(0, squareBracketIndex)); - } - pathList.push(arrayIndex); - } else { - pathList.push(part); - } - } - return pathList; -}, "getAttrPathList"); -// src/lib/getAttr.ts -var getAttr = /* @__PURE__ */ __name((value, path) => getAttrPathList(path).reduce((acc, index) => { - if (typeof acc !== "object") { - throw new EndpointError(`Index '${index}' in '${path}' not found in '${JSON.stringify(value)}'`); - } else if (Array.isArray(acc)) { - return acc[parseInt(index)]; - } - return acc[index]; -}, value), "getAttr"); +function unescapeJsonPointer(str) { + return str.replace(/~1/g, '/').replace(/~0/g, '~'); +} -// src/lib/isSet.ts -var isSet = /* @__PURE__ */ __name((value) => value != null, "isSet"); -// src/lib/not.ts -var not = /* @__PURE__ */ __name((value) => !value, "not"); +/***/ }), -// src/lib/parseURL.ts -var import_types3 = __nccwpck_require__(55756); -var DEFAULT_PORTS = { - [import_types3.EndpointURLScheme.HTTP]: 80, - [import_types3.EndpointURLScheme.HTTPS]: 443 -}; -var parseURL = /* @__PURE__ */ __name((value) => { - const whatwgURL = (() => { - try { - if (value instanceof URL) { - return value; - } - if (typeof value === "object" && "hostname" in value) { - const { hostname: hostname2, port, protocol: protocol2 = "", path = "", query = {} } = value; - const url = new URL(`${protocol2}//${hostname2}${port ? `:${port}` : ""}${path}`); - url.search = Object.entries(query).map(([k, v]) => `${k}=${v}`).join("&"); - return url; - } - return new URL(value); - } catch (error) { - return null; - } - })(); - if (!whatwgURL) { - console.error(`Unable to parse ${JSON.stringify(value)} as a whatwg URL.`); - return null; - } - const urlString = whatwgURL.href; - const { host, hostname, pathname, protocol, search } = whatwgURL; - if (search) { - return null; - } - const scheme = protocol.slice(0, -1); - if (!Object.values(import_types3.EndpointURLScheme).includes(scheme)) { - return null; - } - const isIp = isIpAddress(hostname); - const inputContainsDefaultPort = urlString.includes(`${host}:${DEFAULT_PORTS[scheme]}`) || typeof value === "string" && value.includes(`${host}:${DEFAULT_PORTS[scheme]}`); - const authority = `${host}${inputContainsDefaultPort ? `:${DEFAULT_PORTS[scheme]}` : ``}`; - return { - scheme, - authority, - path: pathname, - normalizedPath: pathname.endsWith("/") ? pathname : `${pathname}/`, - isIp - }; -}, "parseURL"); +/***/ 21412: +/***/ ((module) => { -// src/lib/stringEquals.ts -var stringEquals = /* @__PURE__ */ __name((value1, value2) => value1 === value2, "stringEquals"); +"use strict"; -// src/lib/substring.ts -var substring = /* @__PURE__ */ __name((input, start, stop, reverse) => { - if (start >= stop || input.length < stop) { - return null; - } - if (!reverse) { - return input.substring(start, stop); - } - return input.substring(input.length - stop, input.length - start); -}, "substring"); -// src/lib/uriEncode.ts -var uriEncode = /* @__PURE__ */ __name((value) => encodeURIComponent(value).replace(/[!*'()]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`), "uriEncode"); +var KEYWORDS = [ + 'multipleOf', + 'maximum', + 'exclusiveMaximum', + 'minimum', + 'exclusiveMinimum', + 'maxLength', + 'minLength', + 'pattern', + 'additionalItems', + 'maxItems', + 'minItems', + 'uniqueItems', + 'maxProperties', + 'minProperties', + 'required', + 'additionalProperties', + 'enum', + 'format', + 'const' +]; -// src/utils/endpointFunctions.ts -var endpointFunctions = { - booleanEquals, - getAttr, - isSet, - isValidHostLabel, - not, - parseURL, - stringEquals, - substring, - uriEncode -}; +module.exports = function (metaSchema, keywordsJsonPointers) { + for (var i=0; i { - const evaluatedTemplateArr = []; - const templateContext = { - ...options.endpointParams, - ...options.referenceRecord - }; - let currentIndex = 0; - while (currentIndex < template.length) { - const openingBraceIndex = template.indexOf("{", currentIndex); - if (openingBraceIndex === -1) { - evaluatedTemplateArr.push(template.slice(currentIndex)); - break; - } - evaluatedTemplateArr.push(template.slice(currentIndex, openingBraceIndex)); - const closingBraceIndex = template.indexOf("}", openingBraceIndex); - if (closingBraceIndex === -1) { - evaluatedTemplateArr.push(template.slice(openingBraceIndex)); - break; - } - if (template[openingBraceIndex + 1] === "{" && template[closingBraceIndex + 1] === "}") { - evaluatedTemplateArr.push(template.slice(openingBraceIndex + 1, closingBraceIndex)); - currentIndex = closingBraceIndex + 2; - } - const parameterName = template.substring(openingBraceIndex + 1, closingBraceIndex); - if (parameterName.includes("#")) { - const [refName, attrName] = parameterName.split("#"); - evaluatedTemplateArr.push(getAttr(templateContext[refName], attrName)); - } else { - evaluatedTemplateArr.push(templateContext[parameterName]); + for (j=0; j { - const referenceRecord = { - ...options.endpointParams, - ...options.referenceRecord - }; - return referenceRecord[ref]; -}, "getReferenceValue"); + return metaSchema; +}; -// src/utils/evaluateExpression.ts -var evaluateExpression = /* @__PURE__ */ __name((obj, keyName, options) => { - if (typeof obj === "string") { - return evaluateTemplate(obj, options); - } else if (obj["fn"]) { - return callFunction(obj, options); - } else if (obj["ref"]) { - return getReferenceValue(obj, options); - } - throw new EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`); -}, "evaluateExpression"); -// src/utils/callFunction.ts -var callFunction = /* @__PURE__ */ __name(({ fn, argv }, options) => { - const evaluatedArgs = argv.map( - (arg) => ["boolean", "number"].includes(typeof arg) ? arg : evaluateExpression(arg, "arg", options) - ); - const fnSegments = fn.split("."); - if (fnSegments[0] in customEndpointFunctions && fnSegments[1] != null) { - return customEndpointFunctions[fnSegments[0]][fnSegments[1]](...evaluatedArgs); - } - return endpointFunctions[fn](...evaluatedArgs); -}, "callFunction"); +/***/ }), -// src/utils/evaluateCondition.ts -var evaluateCondition = /* @__PURE__ */ __name(({ assign, ...fnArgs }, options) => { - if (assign && assign in options.referenceRecord) { - throw new EndpointError(`'${assign}' is already defined in Reference Record.`); - } - const value = callFunction(fnArgs, options); - options.logger?.debug?.(`${debugId} evaluateCondition: ${toDebugString(fnArgs)} = ${toDebugString(value)}`); - return { - result: value === "" ? true : !!value, - ...assign != null && { toAssign: { name: assign, value } } - }; -}, "evaluateCondition"); +/***/ 10458: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// src/utils/evaluateConditions.ts -var evaluateConditions = /* @__PURE__ */ __name((conditions = [], options) => { - const conditionsReferenceRecord = {}; - for (const condition of conditions) { - const { result, toAssign } = evaluateCondition(condition, { - ...options, - referenceRecord: { - ...options.referenceRecord, - ...conditionsReferenceRecord - } - }); - if (!result) { - return { result }; - } - if (toAssign) { - conditionsReferenceRecord[toAssign.name] = toAssign.value; - options.logger?.debug?.(`${debugId} assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`); +"use strict"; + + +var metaSchema = __nccwpck_require__(6680); + +module.exports = { + $id: 'https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js', + definitions: { + simpleTypes: metaSchema.definitions.simpleTypes + }, + type: 'object', + dependencies: { + schema: ['validate'], + $data: ['validate'], + statements: ['inline'], + valid: {not: {required: ['macro']}} + }, + properties: { + type: metaSchema.properties.type, + schema: {type: 'boolean'}, + statements: {type: 'boolean'}, + dependencies: { + type: 'array', + items: {type: 'string'} + }, + metaSchema: {type: 'object'}, + modifying: {type: 'boolean'}, + valid: {type: 'boolean'}, + $data: {type: 'boolean'}, + async: {type: 'boolean'}, + errors: { + anyOf: [ + {type: 'boolean'}, + {const: 'full'} + ] } } - return { result: true, referenceRecord: conditionsReferenceRecord }; -}, "evaluateConditions"); +}; -// src/utils/getEndpointHeaders.ts -var getEndpointHeaders = /* @__PURE__ */ __name((headers, options) => Object.entries(headers).reduce( - (acc, [headerKey, headerVal]) => ({ - ...acc, - [headerKey]: headerVal.map((headerValEntry) => { - const processedExpr = evaluateExpression(headerValEntry, "Header value entry", options); - if (typeof processedExpr !== "string") { - throw new EndpointError(`Header '${headerKey}' value '${processedExpr}' is not a string`); - } - return processedExpr; - }) - }), - {} -), "getEndpointHeaders"); -// src/utils/getEndpointProperty.ts -var getEndpointProperty = /* @__PURE__ */ __name((property, options) => { - if (Array.isArray(property)) { - return property.map((propertyEntry) => getEndpointProperty(propertyEntry, options)); - } - switch (typeof property) { - case "string": - return evaluateTemplate(property, options); - case "object": - if (property === null) { - throw new EndpointError(`Unexpected endpoint property: ${property}`); - } - return getEndpointProperties(property, options); - case "boolean": - return property; - default: - throw new EndpointError(`Unexpected endpoint property type: ${typeof property}`); - } -}, "getEndpointProperty"); +/***/ }), -// src/utils/getEndpointProperties.ts -var getEndpointProperties = /* @__PURE__ */ __name((properties, options) => Object.entries(properties).reduce( - (acc, [propertyKey, propertyVal]) => ({ - ...acc, - [propertyKey]: getEndpointProperty(propertyVal, options) - }), - {} -), "getEndpointProperties"); +/***/ 7404: +/***/ ((module) => { -// src/utils/getEndpointUrl.ts -var getEndpointUrl = /* @__PURE__ */ __name((endpointUrl, options) => { - const expression = evaluateExpression(endpointUrl, "Endpoint URL", options); - if (typeof expression === "string") { - try { - return new URL(expression); - } catch (error) { - console.error(`Failed to construct URL with ${expression}`, error); - throw error; - } - } - throw new EndpointError(`Endpoint URL must be a string, got ${typeof expression}`); -}, "getEndpointUrl"); +"use strict"; -// src/utils/evaluateEndpointRule.ts -var evaluateEndpointRule = /* @__PURE__ */ __name((endpointRule, options) => { - const { conditions, endpoint } = endpointRule; - const { result, referenceRecord } = evaluateConditions(conditions, options); - if (!result) { - return; +module.exports = function generate__limit(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; } - const endpointRuleOptions = { - ...options, - referenceRecord: { ...options.referenceRecord, ...referenceRecord } - }; - const { url, properties, headers } = endpoint; - options.logger?.debug?.(`${debugId} Resolving endpoint from template: ${toDebugString(endpoint)}`); - return { - ...headers != void 0 && { - headers: getEndpointHeaders(headers, endpointRuleOptions) - }, - ...properties != void 0 && { - properties: getEndpointProperties(properties, endpointRuleOptions) - }, - url: getEndpointUrl(url, endpointRuleOptions) - }; -}, "evaluateEndpointRule"); - -// src/utils/evaluateErrorRule.ts -var evaluateErrorRule = /* @__PURE__ */ __name((errorRule, options) => { - const { conditions, error } = errorRule; - const { result, referenceRecord } = evaluateConditions(conditions, options); - if (!result) { - return; + var $isMax = $keyword == 'maximum', + $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum', + $schemaExcl = it.schema[$exclusiveKeyword], + $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data, + $op = $isMax ? '<' : '>', + $notOp = $isMax ? '>' : '<', + $errorKeyword = undefined; + if (!($isData || typeof $schema == 'number' || $schema === undefined)) { + throw new Error($keyword + ' must be number'); } - throw new EndpointError( - evaluateExpression(error, "Error", { - ...options, - referenceRecord: { ...options.referenceRecord, ...referenceRecord } - }) - ); -}, "evaluateErrorRule"); - -// src/utils/evaluateTreeRule.ts -var evaluateTreeRule = /* @__PURE__ */ __name((treeRule, options) => { - const { conditions, rules } = treeRule; - const { result, referenceRecord } = evaluateConditions(conditions, options); - if (!result) { - return; + if (!($isDataExcl || $schemaExcl === undefined || typeof $schemaExcl == 'number' || typeof $schemaExcl == 'boolean')) { + throw new Error($exclusiveKeyword + ' must be number or boolean'); } - return evaluateRules(rules, { - ...options, - referenceRecord: { ...options.referenceRecord, ...referenceRecord } - }); -}, "evaluateTreeRule"); - -// src/utils/evaluateRules.ts -var evaluateRules = /* @__PURE__ */ __name((rules, options) => { - for (const rule of rules) { - if (rule.type === "endpoint") { - const endpointOrUndefined = evaluateEndpointRule(rule, options); - if (endpointOrUndefined) { - return endpointOrUndefined; + if ($isDataExcl) { + var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), + $exclusive = 'exclusive' + $lvl, + $exclType = 'exclType' + $lvl, + $exclIsNumber = 'exclIsNumber' + $lvl, + $opExpr = 'op' + $lvl, + $opStr = '\' + ' + $opExpr + ' + \''; + out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; '; + $schemaValueExcl = 'schemaExcl' + $lvl; + out += ' var ' + ($exclusive) + '; var ' + ($exclType) + ' = typeof ' + ($schemaValueExcl) + '; if (' + ($exclType) + ' != \'boolean\' && ' + ($exclType) + ' != \'undefined\' && ' + ($exclType) + ' != \'number\') { '; + var $errorKeyword = $exclusiveKeyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' '; } - } else if (rule.type === "error") { - evaluateErrorRule(rule, options); - } else if (rule.type === "tree") { - const endpointOrUndefined = evaluateTreeRule(rule, options); - if (endpointOrUndefined) { - return endpointOrUndefined; + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } + out += ' } '; } else { - throw new EndpointError(`Unknown endpoint rule: ${rule}`); + out += ' {} '; } - } - throw new EndpointError(`Rules evaluation failed`); -}, "evaluateRules"); - -// src/resolveEndpoint.ts -var resolveEndpoint = /* @__PURE__ */ __name((ruleSetObject, options) => { - const { endpointParams, logger } = options; - const { parameters, rules } = ruleSetObject; - options.logger?.debug?.(`${debugId} Initial EndpointParams: ${toDebugString(endpointParams)}`); - const paramsWithDefault = Object.entries(parameters).filter(([, v]) => v.default != null).map(([k, v]) => [k, v.default]); - if (paramsWithDefault.length > 0) { - for (const [paramKey, paramDefaultValue] of paramsWithDefault) { - endpointParams[paramKey] = endpointParams[paramKey] ?? paramDefaultValue; + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } - } - const requiredParams = Object.entries(parameters).filter(([, v]) => v.required).map(([k]) => k); - for (const requiredParam of requiredParams) { - if (endpointParams[requiredParam] == null) { - throw new EndpointError(`Missing required parameter: '${requiredParam}'`); + out += ' } else if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($exclType) + ' == \'number\' ? ( (' + ($exclusive) + ' = ' + ($schemaValue) + ' === undefined || ' + ($schemaValueExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ') ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValueExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) : ( (' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\'; '; + if ($schema === undefined) { + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $schemaValue = $schemaValueExcl; + $isData = $isDataExcl; + } + } else { + var $exclIsNumber = typeof $schemaExcl == 'number', + $opStr = $op; + if ($exclIsNumber && $isData) { + var $opExpr = '\'' + $opStr + '\''; + out += ' if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ( ' + ($schemaValue) + ' === undefined || ' + ($schemaExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ' ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { '; + } else { + if ($exclIsNumber && $schema === undefined) { + $exclusive = true; + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $schemaValue = $schemaExcl; + $notOp += '='; + } else { + if ($exclIsNumber) $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema); + if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) { + $exclusive = true; + $errorKeyword = $exclusiveKeyword; + $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; + $notOp += '='; + } else { + $exclusive = false; + $opStr += '='; + } + } + var $opExpr = '\'' + $opStr + '\''; + out += ' if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') { '; } } - const endpoint = evaluateRules(rules, { endpointParams, logger, referenceRecord: {} }); - options.logger?.debug?.(`${debugId} Resolved endpoint: ${toDebugString(endpoint)}`); - return endpoint; -}, "resolveEndpoint"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 45364: -/***/ ((module) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -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); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - fromHex: () => fromHex, - toHex: () => toHex -}); -module.exports = __toCommonJS(src_exports); -var SHORT_TO_HEX = {}; -var HEX_TO_SHORT = {}; -for (let i = 0; i < 256; i++) { - let encodedByte = i.toString(16).toLowerCase(); - if (encodedByte.length === 1) { - encodedByte = `0${encodedByte}`; - } - SHORT_TO_HEX[i] = encodedByte; - HEX_TO_SHORT[encodedByte] = i; -} -function fromHex(encoded) { - if (encoded.length % 2 !== 0) { - throw new Error("Hex encoded strings must have an even number length"); + $errorKeyword = $errorKeyword || $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be ' + ($opStr) + ' '; + if ($isData) { + out += '\' + ' + ($schemaValue); + } else { + out += '' + ($schemaValue) + '\''; + } + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; } - const out = new Uint8Array(encoded.length / 2); - for (let i = 0; i < encoded.length; i += 2) { - const encodedByte = encoded.slice(i, i + 2).toLowerCase(); - if (encodedByte in HEX_TO_SHORT) { - out[i / 2] = HEX_TO_SHORT[encodedByte]; + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; } else { - throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); + out += ' validate.errors = [' + (__err) + ']; return false; '; } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } - return out; -} -__name(fromHex, "fromHex"); -function toHex(bytes) { - let out = ""; - for (let i = 0; i < bytes.byteLength; i++) { - out += SHORT_TO_HEX[bytes[i]]; + out += ' } '; + if ($breakOnError) { + out += ' else { '; } return out; } -__name(toHex, "toHex"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 2390: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -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); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - getSmithyContext: () => getSmithyContext, - normalizeProvider: () => normalizeProvider -}); -module.exports = __toCommonJS(src_exports); - -// src/getSmithyContext.ts -var import_types = __nccwpck_require__(55756); -var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); - -// src/normalizeProvider.ts -var normalizeProvider = /* @__PURE__ */ __name((input) => { - if (typeof input === "function") - return input; - const promisified = Promise.resolve(input); - return () => promisified; -}, "normalizeProvider"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - /***/ }), -/***/ 84902: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -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); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - AdaptiveRetryStrategy: () => AdaptiveRetryStrategy, - ConfiguredRetryStrategy: () => ConfiguredRetryStrategy, - DEFAULT_MAX_ATTEMPTS: () => DEFAULT_MAX_ATTEMPTS, - DEFAULT_RETRY_DELAY_BASE: () => DEFAULT_RETRY_DELAY_BASE, - DEFAULT_RETRY_MODE: () => DEFAULT_RETRY_MODE, - DefaultRateLimiter: () => DefaultRateLimiter, - INITIAL_RETRY_TOKENS: () => INITIAL_RETRY_TOKENS, - INVOCATION_ID_HEADER: () => INVOCATION_ID_HEADER, - MAXIMUM_RETRY_DELAY: () => MAXIMUM_RETRY_DELAY, - NO_RETRY_INCREMENT: () => NO_RETRY_INCREMENT, - REQUEST_HEADER: () => REQUEST_HEADER, - RETRY_COST: () => RETRY_COST, - RETRY_MODES: () => RETRY_MODES, - StandardRetryStrategy: () => StandardRetryStrategy, - THROTTLING_RETRY_DELAY_BASE: () => THROTTLING_RETRY_DELAY_BASE, - TIMEOUT_RETRY_COST: () => TIMEOUT_RETRY_COST -}); -module.exports = __toCommonJS(src_exports); +/***/ 64683: +/***/ ((module) => { -// src/config.ts -var RETRY_MODES = /* @__PURE__ */ ((RETRY_MODES2) => { - RETRY_MODES2["STANDARD"] = "standard"; - RETRY_MODES2["ADAPTIVE"] = "adaptive"; - return RETRY_MODES2; -})(RETRY_MODES || {}); -var DEFAULT_MAX_ATTEMPTS = 3; -var DEFAULT_RETRY_MODE = "standard" /* STANDARD */; +"use strict"; -// src/DefaultRateLimiter.ts -var import_service_error_classification = __nccwpck_require__(6375); -var DefaultRateLimiter = class _DefaultRateLimiter { - constructor(options) { - // Pre-set state variables - this.currentCapacity = 0; - this.enabled = false; - this.lastMaxRate = 0; - this.measuredTxRate = 0; - this.requestCount = 0; - this.lastTimestamp = 0; - this.timeWindow = 0; - this.beta = options?.beta ?? 0.7; - this.minCapacity = options?.minCapacity ?? 1; - this.minFillRate = options?.minFillRate ?? 0.5; - this.scaleConstant = options?.scaleConstant ?? 0.4; - this.smooth = options?.smooth ?? 0.8; - const currentTimeInSeconds = this.getCurrentTimeInSeconds(); - this.lastThrottleTime = currentTimeInSeconds; - this.lastTxRateBucket = Math.floor(this.getCurrentTimeInSeconds()); - this.fillRate = this.minFillRate; - this.maxCapacity = this.minCapacity; - } - static { - __name(this, "DefaultRateLimiter"); - } - static { - /** - * Only used in testing. - */ - this.setTimeoutFn = setTimeout; +module.exports = function generate__limitItems(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; } - getCurrentTimeInSeconds() { - return Date.now() / 1e3; + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); } - async getSendToken() { - return this.acquireTokenBucket(1); + var $op = $keyword == 'maxItems' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; } - async acquireTokenBucket(amount) { - if (!this.enabled) { - return; - } - this.refillTokenBucket(); - if (amount > this.currentCapacity) { - const delay = (amount - this.currentCapacity) / this.fillRate * 1e3; - await new Promise((resolve) => _DefaultRateLimiter.setTimeoutFn(resolve, delay)); + out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have '; + if ($keyword == 'maxItems') { + out += 'more'; + } else { + out += 'fewer'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' items\' '; } - this.currentCapacity = this.currentCapacity - amount; - } - refillTokenBucket() { - const timestamp = this.getCurrentTimeInSeconds(); - if (!this.lastTimestamp) { - this.lastTimestamp = timestamp; - return; + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } - const fillAmount = (timestamp - this.lastTimestamp) * this.fillRate; - this.currentCapacity = Math.min(this.maxCapacity, this.currentCapacity + fillAmount); - this.lastTimestamp = timestamp; + out += ' } '; + } else { + out += ' {} '; } - updateClientSendingRate(response) { - let calculatedRate; - this.updateMeasuredRate(); - if ((0, import_service_error_classification.isThrottlingError)(response)) { - const rateToUse = !this.enabled ? this.measuredTxRate : Math.min(this.measuredTxRate, this.fillRate); - this.lastMaxRate = rateToUse; - this.calculateTimeWindow(); - this.lastThrottleTime = this.getCurrentTimeInSeconds(); - calculatedRate = this.cubicThrottle(rateToUse); - this.enableTokenBucket(); + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; } else { - this.calculateTimeWindow(); - calculatedRate = this.cubicSuccess(this.getCurrentTimeInSeconds()); + out += ' validate.errors = [' + (__err) + ']; return false; '; } - const newRate = Math.min(calculatedRate, 2 * this.measuredTxRate); - this.updateTokenBucketRate(newRate); + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } - calculateTimeWindow() { - this.timeWindow = this.getPrecise(Math.pow(this.lastMaxRate * (1 - this.beta) / this.scaleConstant, 1 / 3)); + out += '} '; + if ($breakOnError) { + out += ' else { '; } - cubicThrottle(rateToUse) { - return this.getPrecise(rateToUse * this.beta); + return out; +} + + +/***/ }), + +/***/ 52114: +/***/ ((module) => { + +"use strict"; + +module.exports = function generate__limitLength(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; } - cubicSuccess(timestamp) { - return this.getPrecise( - this.scaleConstant * Math.pow(timestamp - this.lastThrottleTime - this.timeWindow, 3) + this.lastMaxRate - ); + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); } - enableTokenBucket() { - this.enabled = true; + var $op = $keyword == 'maxLength' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; } - updateTokenBucketRate(newRate) { - this.refillTokenBucket(); - this.fillRate = Math.max(newRate, this.minFillRate); - this.maxCapacity = Math.max(newRate, this.minCapacity); - this.currentCapacity = Math.min(this.currentCapacity, this.maxCapacity); + if (it.opts.unicode === false) { + out += ' ' + ($data) + '.length '; + } else { + out += ' ucs2length(' + ($data) + ') '; } - updateMeasuredRate() { - const t = this.getCurrentTimeInSeconds(); - const timeBucket = Math.floor(t * 2) / 2; - this.requestCount++; - if (timeBucket > this.lastTxRateBucket) { - const currentRate = this.requestCount / (timeBucket - this.lastTxRateBucket); - this.measuredTxRate = this.getPrecise(currentRate * this.smooth + this.measuredTxRate * (1 - this.smooth)); - this.requestCount = 0; - this.lastTxRateBucket = timeBucket; + out += ' ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be '; + if ($keyword == 'maxLength') { + out += 'longer'; + } else { + out += 'shorter'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' characters\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } + out += ' } '; + } else { + out += ' {} '; } - getPrecise(num) { - return parseFloat(num.toFixed(8)); + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } -}; + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} -// src/constants.ts -var DEFAULT_RETRY_DELAY_BASE = 100; -var MAXIMUM_RETRY_DELAY = 20 * 1e3; -var THROTTLING_RETRY_DELAY_BASE = 500; -var INITIAL_RETRY_TOKENS = 500; -var RETRY_COST = 5; -var TIMEOUT_RETRY_COST = 10; -var NO_RETRY_INCREMENT = 1; -var INVOCATION_ID_HEADER = "amz-sdk-invocation-id"; -var REQUEST_HEADER = "amz-sdk-request"; -// src/defaultRetryBackoffStrategy.ts -var getDefaultRetryBackoffStrategy = /* @__PURE__ */ __name(() => { - let delayBase = DEFAULT_RETRY_DELAY_BASE; - const computeNextBackoffDelay = /* @__PURE__ */ __name((attempts) => { - return Math.floor(Math.min(MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase)); - }, "computeNextBackoffDelay"); - const setDelayBase = /* @__PURE__ */ __name((delay) => { - delayBase = delay; - }, "setDelayBase"); - return { - computeNextBackoffDelay, - setDelayBase - }; -}, "getDefaultRetryBackoffStrategy"); +/***/ }), -// src/defaultRetryToken.ts -var createDefaultRetryToken = /* @__PURE__ */ __name(({ - retryDelay, - retryCount, - retryCost -}) => { - const getRetryCount = /* @__PURE__ */ __name(() => retryCount, "getRetryCount"); - const getRetryDelay = /* @__PURE__ */ __name(() => Math.min(MAXIMUM_RETRY_DELAY, retryDelay), "getRetryDelay"); - const getRetryCost = /* @__PURE__ */ __name(() => retryCost, "getRetryCost"); - return { - getRetryCount, - getRetryDelay, - getRetryCost - }; -}, "createDefaultRetryToken"); +/***/ 71142: +/***/ ((module) => { -// src/StandardRetryStrategy.ts -var StandardRetryStrategy = class { - constructor(maxAttempts) { - this.maxAttempts = maxAttempts; - this.mode = "standard" /* STANDARD */; - this.capacity = INITIAL_RETRY_TOKENS; - this.retryBackoffStrategy = getDefaultRetryBackoffStrategy(); - this.maxAttemptsProvider = typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts; +"use strict"; + +module.exports = function generate__limitProperties(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; } - static { - __name(this, "StandardRetryStrategy"); + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async acquireInitialRetryToken(retryTokenScope) { - return createDefaultRetryToken({ - retryDelay: DEFAULT_RETRY_DELAY_BASE, - retryCount: 0 - }); + var $op = $keyword == 'maxProperties' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; } - async refreshRetryTokenForRetry(token, errorInfo) { - const maxAttempts = await this.getMaxAttempts(); - if (this.shouldRetry(token, errorInfo, maxAttempts)) { - const errorType = errorInfo.errorType; - this.retryBackoffStrategy.setDelayBase( - errorType === "THROTTLING" ? THROTTLING_RETRY_DELAY_BASE : DEFAULT_RETRY_DELAY_BASE - ); - const delayFromErrorType = this.retryBackoffStrategy.computeNextBackoffDelay(token.getRetryCount()); - const retryDelay = errorInfo.retryAfterHint ? Math.max(errorInfo.retryAfterHint.getTime() - Date.now() || 0, delayFromErrorType) : delayFromErrorType; - const capacityCost = this.getCapacityCost(errorType); - this.capacity -= capacityCost; - return createDefaultRetryToken({ - retryDelay, - retryCount: token.getRetryCount() + 1, - retryCost: capacityCost - }); + out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have '; + if ($keyword == 'maxProperties') { + out += 'more'; + } else { + out += 'fewer'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' properties\' '; } - throw new Error("No retry token available"); - } - recordSuccess(token) { - this.capacity = Math.max(INITIAL_RETRY_TOKENS, this.capacity + (token.getRetryCost() ?? NO_RETRY_INCREMENT)); - } - /** - * @returns the current available retry capacity. - * - * This number decreases when retries are executed and refills when requests or retries succeed. - */ - getCapacity() { - return this.capacity; - } - async getMaxAttempts() { - try { - return await this.maxAttemptsProvider(); - } catch (error) { - console.warn(`Max attempts provider could not resolve. Using default of ${DEFAULT_MAX_ATTEMPTS}`); - return DEFAULT_MAX_ATTEMPTS; + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } + out += ' } '; + } else { + out += ' {} '; } - shouldRetry(tokenToRenew, errorInfo, maxAttempts) { - const attempts = tokenToRenew.getRetryCount() + 1; - return attempts < maxAttempts && this.capacity >= this.getCapacityCost(errorInfo.errorType) && this.isRetryableError(errorInfo.errorType); - } - getCapacityCost(errorType) { - return errorType === "TRANSIENT" ? TIMEOUT_RETRY_COST : RETRY_COST; + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } - isRetryableError(errorType) { - return errorType === "THROTTLING" || errorType === "TRANSIENT"; + out += '} '; + if ($breakOnError) { + out += ' else { '; } -}; + return out; +} -// src/AdaptiveRetryStrategy.ts -var AdaptiveRetryStrategy = class { - constructor(maxAttemptsProvider, options) { - this.maxAttemptsProvider = maxAttemptsProvider; - this.mode = "adaptive" /* ADAPTIVE */; - const { rateLimiter } = options ?? {}; - this.rateLimiter = rateLimiter ?? new DefaultRateLimiter(); - this.standardRetryStrategy = new StandardRetryStrategy(maxAttemptsProvider); - } - static { - __name(this, "AdaptiveRetryStrategy"); - } - async acquireInitialRetryToken(retryTokenScope) { - await this.rateLimiter.getSendToken(); - return this.standardRetryStrategy.acquireInitialRetryToken(retryTokenScope); - } - async refreshRetryTokenForRetry(tokenToRenew, errorInfo) { - this.rateLimiter.updateClientSendingRate(errorInfo); - return this.standardRetryStrategy.refreshRetryTokenForRetry(tokenToRenew, errorInfo); - } - recordSuccess(token) { - this.rateLimiter.updateClientSendingRate({}); - this.standardRetryStrategy.recordSuccess(token); - } -}; -// src/ConfiguredRetryStrategy.ts -var ConfiguredRetryStrategy = class extends StandardRetryStrategy { - static { - __name(this, "ConfiguredRetryStrategy"); +/***/ }), + +/***/ 89443: +/***/ ((module) => { + +"use strict"; + +module.exports = function generate_allOf(it, $keyword, $ruleType) { + var out = ' '; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $currentBaseId = $it.baseId, + $allSchemasEmpty = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + $allSchemasEmpty = false; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } } - /** - * @param maxAttempts - the maximum number of retry attempts allowed. - * e.g., if set to 3, then 4 total requests are possible. - * @param computeNextBackoffDelay - a millisecond delay for each retry or a function that takes the retry attempt - * and returns the delay. - * - * @example exponential backoff. - * ```js - * new Client({ - * retryStrategy: new ConfiguredRetryStrategy(3, (attempt) => attempt ** 2) - * }); - * ``` - * @example constant delay. - * ```js - * new Client({ - * retryStrategy: new ConfiguredRetryStrategy(3, 2000) - * }); - * ``` - */ - constructor(maxAttempts, computeNextBackoffDelay = DEFAULT_RETRY_DELAY_BASE) { - super(typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts); - if (typeof computeNextBackoffDelay === "number") { - this.computeNextBackoffDelay = () => computeNextBackoffDelay; + if ($breakOnError) { + if ($allSchemasEmpty) { + out += ' if (true) { '; } else { - this.computeNextBackoffDelay = computeNextBackoffDelay; + out += ' ' + ($closingBraces.slice(0, -1)) + ' '; } } - async refreshRetryTokenForRetry(tokenToRenew, errorInfo) { - const token = await super.refreshRetryTokenForRetry(tokenToRenew, errorInfo); - token.getRetryDelay = () => this.computeNextBackoffDelay(token.getRetryCount()); - return token; - } -}; -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - + return out; +} /***/ }), -/***/ 39361: -/***/ ((__unused_webpack_module, exports) => { +/***/ 63093: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ByteArrayCollector = void 0; -class ByteArrayCollector { - constructor(allocByteArray) { - this.allocByteArray = allocByteArray; - this.byteLength = 0; - this.byteArrays = []; +module.exports = function generate_anyOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $noEmptySchema = $schema.every(function($sch) { + return (it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)); + }); + if ($noEmptySchema) { + var $currentBaseId = $it.baseId; + out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { '; + $closingBraces += '}'; + } } - push(byteArray) { - this.byteArrays.push(byteArray); - this.byteLength += byteArray.byteLength; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should match some schema in anyOf\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; } - flush() { - if (this.byteArrays.length === 1) { - const bytes = this.byteArrays[0]; - this.reset(); - return bytes; - } - const aggregation = this.allocByteArray(this.byteLength); - let cursor = 0; - for (let i = 0; i < this.byteArrays.length; ++i) { - const bytes = this.byteArrays[i]; - aggregation.set(bytes, cursor); - cursor += bytes.byteLength; - } - this.reset(); - return aggregation; + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } } - reset() { - this.byteArrays = []; - this.byteLength = 0; + out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + if (it.opts.allErrors) { + out += ' } '; + } + } else { + if ($breakOnError) { + out += ' if (true) { '; } + } + return out; } -exports.ByteArrayCollector = ByteArrayCollector; /***/ }), -/***/ 78551: -/***/ ((__unused_webpack_module, exports) => { +/***/ 30134: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ChecksumStream = void 0; -const ReadableStreamRef = typeof ReadableStream === "function" ? ReadableStream : function () { }; -class ChecksumStream extends ReadableStreamRef { +module.exports = function generate_comment(it, $keyword, $ruleType) { + var out = ' '; + var $schema = it.schema[$keyword]; + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $comment = it.util.toQuotedString($schema); + if (it.opts.$comment === true) { + out += ' console.log(' + ($comment) + ');'; + } else if (typeof it.opts.$comment == 'function') { + out += ' self._opts.$comment(' + ($comment) + ', ' + (it.util.toQuotedString($errSchemaPath)) + ', validate.root.schema);'; + } + return out; } -exports.ChecksumStream = ChecksumStream; /***/ }), -/***/ 6982: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 1661: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ChecksumStream = void 0; -const util_base64_1 = __nccwpck_require__(75600); -const stream_1 = __nccwpck_require__(12781); -class ChecksumStream extends stream_1.Duplex { - constructor({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) { - var _a, _b; - super(); - if (typeof source.pipe === "function") { - this.source = source; - } - else { - throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); - } - this.base64Encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; - this.expectedChecksum = expectedChecksum; - this.checksum = checksum; - this.checksumSourceLocation = checksumSourceLocation; - this.source.pipe(this); +module.exports = function generate_const(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!$isData) { + out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';'; + } + out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('const') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValue: schema' + ($lvl) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be equal to constant\' '; } - _read(size) { } - _write(chunk, encoding, callback) { - try { - this.checksum.update(chunk); - this.push(chunk); - } - catch (e) { - return callback(e); - } - return callback(); + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } - async _final(callback) { - try { - const digest = await this.checksum.digest(); - const received = this.base64Encoder(digest); - if (this.expectedChecksum !== received) { - return callback(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${received}"` + - ` in response header "${this.checksumSourceLocation}".`)); - } - } - catch (e) { - return callback(e); - } - this.push(null); - return callback(); + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' }'; + if ($breakOnError) { + out += ' else { '; + } + return out; } -exports.ChecksumStream = ChecksumStream; /***/ }), -/***/ 72313: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 55964: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createChecksumStream = void 0; -const util_base64_1 = __nccwpck_require__(75600); -const stream_type_check_1 = __nccwpck_require__(57578); -const ChecksumStream_browser_1 = __nccwpck_require__(78551); -const createChecksumStream = ({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) => { - var _a, _b; - if (!(0, stream_type_check_1.isReadableStream)(source)) { - throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); +module.exports = function generate_contains(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $idx = 'i' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $currentBaseId = it.baseId, + $nonEmptySchema = (it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all)); + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if ($nonEmptySchema) { + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + ($nextValid) + ' = false; for (var ' + ($idx) + ' = 0; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; } - const encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; - if (typeof TransformStream !== "function") { - throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream."); + out += ' if (' + ($nextValid) + ') break; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($closingBraces) + ' if (!' + ($nextValid) + ') {'; + } else { + out += ' if (' + ($data) + '.length == 0) {'; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('contains') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should contain a valid item\' '; } - const transform = new TransformStream({ - start() { }, - async transform(chunk, controller) { - checksum.update(chunk); - controller.enqueue(chunk); - }, - async flush(controller) { - const digest = await checksum.digest(); - const received = encoder(digest); - if (expectedChecksum !== received) { - const error = new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}"` + - ` in response header "${checksumSourceLocation}".`); - controller.error(error); - } - else { - controller.terminate(); - } - }, - }); - source.pipeThrough(transform); - const readable = transform.readable; - Object.setPrototypeOf(readable, ChecksumStream_browser_1.ChecksumStream.prototype); - return readable; -}; -exports.createChecksumStream = createChecksumStream; - - -/***/ }), - -/***/ 21927: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createChecksumStream = void 0; -const stream_type_check_1 = __nccwpck_require__(57578); -const ChecksumStream_1 = __nccwpck_require__(6982); -const createChecksumStream_browser_1 = __nccwpck_require__(72313); -function createChecksumStream(init) { - if (typeof ReadableStream === "function" && (0, stream_type_check_1.isReadableStream)(init.source)) { - return (0, createChecksumStream_browser_1.createChecksumStream)(init); + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } - return new ChecksumStream_1.ChecksumStream(init); + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + if ($nonEmptySchema) { + out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + } + if (it.opts.allErrors) { + out += ' } '; + } + return out; } -exports.createChecksumStream = createChecksumStream; /***/ }), -/***/ 33259: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 5912: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createBufferedReadable = void 0; -const node_stream_1 = __nccwpck_require__(84492); -const ByteArrayCollector_1 = __nccwpck_require__(39361); -const createBufferedReadableStream_1 = __nccwpck_require__(92558); -const stream_type_check_1 = __nccwpck_require__(57578); -function createBufferedReadable(upstream, size, logger) { - if ((0, stream_type_check_1.isReadableStream)(upstream)) { - return (0, createBufferedReadableStream_1.createBufferedReadableStream)(upstream, size, logger); +module.exports = function generate_custom(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $rule = this, + $definition = 'definition' + $lvl, + $rDef = $rule.definition, + $closingBraces = ''; + var $compile, $inline, $macro, $ruleValidate, $validateCode; + if ($isData && $rDef.$data) { + $validateCode = 'keywordValidate' + $lvl; + var $validateSchema = $rDef.validateSchema; + out += ' var ' + ($definition) + ' = RULES.custom[\'' + ($keyword) + '\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;'; + } else { + $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it); + if (!$ruleValidate) return; + $schemaValue = 'validate.schema' + $schemaPath; + $validateCode = $ruleValidate.code; + $compile = $rDef.compile; + $inline = $rDef.inline; + $macro = $rDef.macro; + } + var $ruleErrs = $validateCode + '.errors', + $i = 'i' + $lvl, + $ruleErr = 'ruleErr' + $lvl, + $asyncKeyword = $rDef.async; + if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema'); + if (!($inline || $macro)) { + out += '' + ($ruleErrs) + ' = null;'; + } + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if ($isData && $rDef.$data) { + $closingBraces += '}'; + out += ' if (' + ($schemaValue) + ' === undefined) { ' + ($valid) + ' = true; } else { '; + if ($validateSchema) { + $closingBraces += '}'; + out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') { '; } - const downstream = new node_stream_1.Readable({ read() { } }); - let streamBufferingLoggedWarning = false; - let bytesSeen = 0; - const buffers = [ - "", - new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size)), - new ByteArrayCollector_1.ByteArrayCollector((size) => Buffer.from(new Uint8Array(size))), - ]; - let mode = -1; - upstream.on("data", (chunk) => { - const chunkMode = (0, createBufferedReadableStream_1.modeOf)(chunk, true); - if (mode !== chunkMode) { - if (mode >= 0) { - downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); - } - mode = chunkMode; + } + if ($inline) { + if ($rDef.statements) { + out += ' ' + ($ruleValidate.validate) + ' '; + } else { + out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; '; + } + } else if ($macro) { + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + $it.schema = $ruleValidate.validate; + $it.schemaPath = ''; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var $code = it.validate($it).replace(/validate\.schema/g, $validateCode); + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($code); + } else { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + out += ' ' + ($validateCode) + '.call( '; + if (it.opts.passContext) { + out += 'this'; + } else { + out += 'self'; + } + if ($compile || $rDef.schema === false) { + out += ' , ' + ($data) + ' '; + } else { + out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' '; + } + out += ' , (dataPath || \'\')'; + if (it.errorPath != '""') { + out += ' + ' + (it.errorPath); + } + var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData ) '; + var def_callRuleValidate = out; + out = $$outStack.pop(); + if ($rDef.errors === false) { + out += ' ' + ($valid) + ' = '; + if ($asyncKeyword) { + out += 'await '; + } + out += '' + (def_callRuleValidate) + '; '; + } else { + if ($asyncKeyword) { + $ruleErrs = 'customErrors' + $lvl; + out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = await ' + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } '; + } else { + out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; '; + } + } + } + if ($rDef.modifying) { + out += ' if (' + ($parentData) + ') ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];'; + } + out += '' + ($closingBraces); + if ($rDef.valid) { + if ($breakOnError) { + out += ' if (true) { '; + } + } else { + out += ' if ( '; + if ($rDef.valid === undefined) { + out += ' !'; + if ($macro) { + out += '' + ($nextValid); + } else { + out += '' + ($valid); + } + } else { + out += ' ' + (!$rDef.valid) + ' '; + } + out += ') { '; + $errorKeyword = $rule.keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + var def_customError = out; + out = $$outStack.pop(); + if ($inline) { + if ($rDef.errors) { + if ($rDef.errors != 'full') { + out += ' for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '= size && bufferSize === 0) { - downstream.push(chunk); + } + } else if ($macro) { + out += ' var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' '; } - else { - const newSize = (0, createBufferedReadableStream_1.merge)(buffers, mode, chunk); - if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { - streamBufferingLoggedWarning = true; - logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); - } - if (newSize >= size) { - downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); - } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } - }); - upstream.on("end", () => { - if (mode !== -1) { - const remainder = (0, createBufferedReadableStream_1.flush)(buffers, mode); - if ((0, createBufferedReadableStream_1.sizeOf)(remainder) > 0) { - downstream.push(remainder); - } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; } - downstream.push(null); - }); - return downstream; + } + } else { + if ($rDef.errors === false) { + out += ' ' + (def_customError) + ' '; + } else { + out += ' if (Array.isArray(' + ($ruleErrs) + ')) { if (vErrors === null) vErrors = ' + ($ruleErrs) + '; else vErrors = vErrors.concat(' + ($ruleErrs) + '); errors = vErrors.length; for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + ' { +/***/ 2591: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.modeOf = exports.sizeOf = exports.flush = exports.merge = exports.createBufferedReadable = exports.createBufferedReadableStream = void 0; -const ByteArrayCollector_1 = __nccwpck_require__(39361); -function createBufferedReadableStream(upstream, size, logger) { - const reader = upstream.getReader(); - let streamBufferingLoggedWarning = false; - let bytesSeen = 0; - const buffers = ["", new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size))]; - let mode = -1; - const pull = async (controller) => { - const { value, done } = await reader.read(); - const chunk = value; - if (done) { - if (mode !== -1) { - const remainder = flush(buffers, mode); - if (sizeOf(remainder) > 0) { - controller.enqueue(remainder); - } +module.exports = function generate_dependencies(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $schemaDeps = {}, + $propertyDeps = {}, + $ownProperties = it.opts.ownProperties; + for ($property in $schema) { + if ($property == '__proto__') continue; + var $sch = $schema[$property]; + var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps; + $deps[$property] = $sch; + } + out += 'var ' + ($errs) + ' = errors;'; + var $currentErrorPath = it.errorPath; + out += 'var missing' + ($lvl) + ';'; + for (var $property in $propertyDeps) { + $deps = $propertyDeps[$property]; + if ($deps.length) { + out += ' if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') '; + } + if ($breakOnError) { + out += ' && ( '; + var arr1 = $deps; + if (arr1) { + var $propertyKey, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $propertyKey = arr1[$i += 1]; + if ($i) { + out += ' || '; } - controller.close(); + var $prop = it.util.getProperty($propertyKey), + $useData = $data + $prop; + out += ' ( ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) '; + } } - else { - const chunkMode = modeOf(chunk, false); - if (mode !== chunkMode) { - if (mode >= 0) { - controller.enqueue(flush(buffers, mode)); - } - mode = chunkMode; + out += ')) { '; + var $propertyPath = 'missing' + $lvl, + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should have '; + if ($deps.length == 1) { + out += 'property ' + (it.util.escapeQuotes($deps[0])); + } else { + out += 'properties ' + (it.util.escapeQuotes($deps.join(", "))); } - if (mode === -1) { - controller.enqueue(chunk); - return; + out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } else { + out += ' ) { '; + var arr2 = $deps; + if (arr2) { + var $propertyKey, i2 = -1, + l2 = arr2.length - 1; + while (i2 < l2) { + $propertyKey = arr2[i2 += 1]; + var $prop = it.util.getProperty($propertyKey), + $missingProperty = it.util.escapeQuotes($propertyKey), + $useData = $data + $prop; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); } - const chunkSize = sizeOf(chunk); - bytesSeen += chunkSize; - const bufferSize = sizeOf(buffers[mode]); - if (chunkSize >= size && bufferSize === 0) { - controller.enqueue(chunk); + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; } - else { - const newSize = merge(buffers, mode, chunk); - if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { - streamBufferingLoggedWarning = true; - logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); - } - if (newSize >= size) { - controller.enqueue(flush(buffers, mode)); - } - else { - await pull(controller); + out += ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should have '; + if ($deps.length == 1) { + out += 'property ' + (it.util.escapeQuotes($deps[0])); + } else { + out += 'properties ' + (it.util.escapeQuotes($deps.join(", "))); } + out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; + } } - }; - return new ReadableStream({ - pull, - }); -} -exports.createBufferedReadableStream = createBufferedReadableStream; -exports.createBufferedReadable = createBufferedReadableStream; -function merge(buffers, mode, chunk) { - switch (mode) { - case 0: - buffers[0] += chunk; - return sizeOf(buffers[0]); - case 1: - case 2: - buffers[mode].push(chunk); - return sizeOf(buffers[mode]); - } -} -exports.merge = merge; -function flush(buffers, mode) { - switch (mode) { - case 0: - const s = buffers[0]; - buffers[0] = ""; - return s; - case 1: - case 2: - return buffers[mode].flush(); - } - throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`); -} -exports.flush = flush; -function sizeOf(chunk) { - var _a, _b; - return (_b = (_a = chunk === null || chunk === void 0 ? void 0 : chunk.byteLength) !== null && _a !== void 0 ? _a : chunk === null || chunk === void 0 ? void 0 : chunk.length) !== null && _b !== void 0 ? _b : 0; -} -exports.sizeOf = sizeOf; -function modeOf(chunk, allowBuffer = true) { - if (allowBuffer && typeof Buffer !== "undefined" && chunk instanceof Buffer) { - return 2; - } - if (chunk instanceof Uint8Array) { - return 1; + } + out += ' } '; + if ($breakOnError) { + $closingBraces += '}'; + out += ' else { '; + } } - if (typeof chunk === "string") { - return 0; + } + it.errorPath = $currentErrorPath; + var $currentBaseId = $it.baseId; + for (var $property in $schemaDeps) { + var $sch = $schemaDeps[$property]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + out += ' ' + ($nextValid) + ' = true; if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') '; + } + out += ') { '; + $it.schema = $sch; + $it.schemaPath = $schemaPath + it.util.getProperty($property); + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property); + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } } - return -1; + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + return out; } -exports.modeOf = modeOf; /***/ }), -/***/ 23636: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 10163: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getAwsChunkedEncodingStream = void 0; -const stream_1 = __nccwpck_require__(12781); -const getAwsChunkedEncodingStream = (readableStream, options) => { - const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options; - const checksumRequired = base64Encoder !== undefined && - checksumAlgorithmFn !== undefined && - checksumLocationName !== undefined && - streamHasher !== undefined; - const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readableStream) : undefined; - const awsChunkedEncodingStream = new stream_1.Readable({ read: () => { } }); - readableStream.on("data", (data) => { - const length = bodyLengthChecker(data) || 0; - awsChunkedEncodingStream.push(`${length.toString(16)}\r\n`); - awsChunkedEncodingStream.push(data); - awsChunkedEncodingStream.push("\r\n"); - }); - readableStream.on("end", async () => { - awsChunkedEncodingStream.push(`0\r\n`); - if (checksumRequired) { - const checksum = base64Encoder(await digest); - awsChunkedEncodingStream.push(`${checksumLocationName}:${checksum}\r\n`); - awsChunkedEncodingStream.push(`\r\n`); - } - awsChunkedEncodingStream.push(null); - }); - return awsChunkedEncodingStream; -}; -exports.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream; +module.exports = function generate_enum(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $i = 'i' + $lvl, + $vSchema = 'schema' + $lvl; + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + ';'; + } + out += 'var ' + ($valid) + ';'; + if ($isData) { + out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; + } + out += '' + ($valid) + ' = false;for (var ' + ($i) + '=0; ' + ($i) + '<' + ($vSchema) + '.length; ' + ($i) + '++) if (equal(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + '])) { ' + ($valid) + ' = true; break; }'; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('enum') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValues: schema' + ($lvl) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be equal to one of the allowed values\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' }'; + if ($breakOnError) { + out += ' else { '; + } + return out; +} /***/ }), -/***/ 56711: -/***/ ((__unused_webpack_module, exports) => { +/***/ 63847: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.headStream = void 0; -async function headStream(stream, bytes) { - var _a; - let byteLengthCounter = 0; - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - byteLengthCounter += (_a = value === null || value === void 0 ? void 0 : value.byteLength) !== null && _a !== void 0 ? _a : 0; - } - if (byteLengthCounter >= bytes) { - break; - } - isDone = done; +module.exports = function generate_format(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + if (it.opts.format === false) { + if ($breakOnError) { + out += ' if (true) { '; } - reader.releaseLock(); - const collected = new Uint8Array(Math.min(bytes, byteLengthCounter)); - let offset = 0; - for (const chunk of chunks) { - if (chunk.byteLength > collected.byteLength - offset) { - collected.set(chunk.subarray(0, collected.byteLength - offset), offset); - break; + return out; + } + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $unknownFormats = it.opts.unknownFormats, + $allowUnknown = Array.isArray($unknownFormats); + if ($isData) { + var $format = 'format' + $lvl, + $isObject = 'isObject' + $lvl, + $formatType = 'formatType' + $lvl; + out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var ' + ($isObject) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; var ' + ($formatType) + ' = ' + ($isObject) + ' && ' + ($format) + '.type || \'string\'; if (' + ($isObject) + ') { '; + if (it.async) { + out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; '; + } + out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; + } + out += ' ('; + if ($unknownFormats != 'ignore') { + out += ' (' + ($schemaValue) + ' && !' + ($format) + ' '; + if ($allowUnknown) { + out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 '; + } + out += ') || '; + } + out += ' (' + ($format) + ' && ' + ($formatType) + ' == \'' + ($ruleType) + '\' && !(typeof ' + ($format) + ' == \'function\' ? '; + if (it.async) { + out += ' (async' + ($lvl) + ' ? await ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) '; + } else { + out += ' ' + ($format) + '(' + ($data) + ') '; + } + out += ' : ' + ($format) + '.test(' + ($data) + '))))) {'; + } else { + var $format = it.formats[$schema]; + if (!$format) { + if ($unknownFormats == 'ignore') { + it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"'); + if ($breakOnError) { + out += ' if (true) { '; } - else { - collected.set(chunk, offset); + return out; + } else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) { + if ($breakOnError) { + out += ' if (true) { '; } - offset += chunk.length; + return out; + } else { + throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"'); + } } - return collected; + var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate; + var $formatType = $isObject && $format.type || 'string'; + if ($isObject) { + var $async = $format.async === true; + $format = $format.validate; + } + if ($formatType != $ruleType) { + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } + if ($async) { + if (!it.async) throw new Error('async format in sync schema'); + var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate'; + out += ' if (!(await ' + ($formatRef) + '(' + ($data) + '))) { '; + } else { + out += ' if (! '; + var $formatRef = 'formats' + it.util.getProperty($schema); + if ($isObject) $formatRef += '.validate'; + if (typeof $format == 'function') { + out += ' ' + ($formatRef) + '(' + ($data) + ') '; + } else { + out += ' ' + ($formatRef) + '.test(' + ($data) + ') '; + } + out += ') { '; + } + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format: '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match format "'; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + (it.util.escapeQuotes($schema)); + } + out += '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + return out; } -exports.headStream = headStream; /***/ }), -/***/ 6708: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 80862: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.headStream = void 0; -const stream_1 = __nccwpck_require__(12781); -const headStream_browser_1 = __nccwpck_require__(56711); -const stream_type_check_1 = __nccwpck_require__(57578); -const headStream = (stream, bytes) => { - if ((0, stream_type_check_1.isReadableStream)(stream)) { - return (0, headStream_browser_1.headStream)(stream, bytes); +module.exports = function generate_if(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + var $thenSch = it.schema['then'], + $elseSch = it.schema['else'], + $thenPresent = $thenSch !== undefined && (it.opts.strictKeywords ? (typeof $thenSch == 'object' && Object.keys($thenSch).length > 0) || $thenSch === false : it.util.schemaHasRules($thenSch, it.RULES.all)), + $elsePresent = $elseSch !== undefined && (it.opts.strictKeywords ? (typeof $elseSch == 'object' && Object.keys($elseSch).length > 0) || $elseSch === false : it.util.schemaHasRules($elseSch, it.RULES.all)), + $currentBaseId = $it.baseId; + if ($thenPresent || $elsePresent) { + var $ifClause; + $it.createErrors = false; + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = true; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + $it.createErrors = true; + out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + if ($thenPresent) { + out += ' if (' + ($nextValid) + ') { '; + $it.schema = it.schema['then']; + $it.schemaPath = it.schemaPath + '.then'; + $it.errSchemaPath = it.errSchemaPath + '/then'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + ($valid) + ' = ' + ($nextValid) + '; '; + if ($thenPresent && $elsePresent) { + $ifClause = 'ifClause' + $lvl; + out += ' var ' + ($ifClause) + ' = \'then\'; '; + } else { + $ifClause = '\'then\''; + } + out += ' } '; + if ($elsePresent) { + out += ' else { '; + } + } else { + out += ' if (!' + ($nextValid) + ') { '; } - return new Promise((resolve, reject) => { - const collector = new Collector(); - collector.limit = bytes; - stream.pipe(collector); - stream.on("error", (err) => { - collector.end(); - reject(err); - }); - collector.on("error", reject); - collector.on("finish", function () { - const bytes = new Uint8Array(Buffer.concat(this.buffers)); - resolve(bytes); - }); - }); -}; -exports.headStream = headStream; -class Collector extends stream_1.Writable { - constructor() { - super(...arguments); - this.buffers = []; - this.limit = Infinity; - this.bytesBuffered = 0; + if ($elsePresent) { + $it.schema = it.schema['else']; + $it.schemaPath = it.schemaPath + '.else'; + $it.errSchemaPath = it.errSchemaPath + '/else'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + ($valid) + ' = ' + ($nextValid) + '; '; + if ($thenPresent && $elsePresent) { + $ifClause = 'ifClause' + $lvl; + out += ' var ' + ($ifClause) + ' = \'else\'; '; + } else { + $ifClause = '\'else\''; + } + out += ' } '; } - _write(chunk, encoding, callback) { - var _a; - this.buffers.push(chunk); - this.bytesBuffered += (_a = chunk.byteLength) !== null && _a !== void 0 ? _a : 0; - if (this.bytesBuffered >= this.limit) { - const excess = this.bytesBuffered - this.limit; - const tailBuffer = this.buffers[this.buffers.length - 1]; - this.buffers[this.buffers.length - 1] = tailBuffer.subarray(0, tailBuffer.byteLength - excess); - this.emit("finish"); - } - callback(); + out += ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('if') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { failingKeyword: ' + ($ifClause) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match "\' + ' + ($ifClause) + ' + \'" schema\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; } -} - - -/***/ }), - -/***/ 96607: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -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 __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - Uint8ArrayBlobAdapter: () => Uint8ArrayBlobAdapter -}); -module.exports = __toCommonJS(src_exports); - -// src/blob/transforms.ts -var import_util_base64 = __nccwpck_require__(75600); -var import_util_utf8 = __nccwpck_require__(41895); -function transformToString(payload, encoding = "utf-8") { - if (encoding === "base64") { - return (0, import_util_base64.toBase64)(payload); - } - return (0, import_util_utf8.toUtf8)(payload); -} -__name(transformToString, "transformToString"); -function transformFromString(str, encoding) { - if (encoding === "base64") { - return Uint8ArrayBlobAdapter.mutate((0, import_util_base64.fromBase64)(str)); - } - return Uint8ArrayBlobAdapter.mutate((0, import_util_utf8.fromUtf8)(str)); -} -__name(transformFromString, "transformFromString"); - -// src/blob/Uint8ArrayBlobAdapter.ts -var Uint8ArrayBlobAdapter = class _Uint8ArrayBlobAdapter extends Uint8Array { - static { - __name(this, "Uint8ArrayBlobAdapter"); - } - /** - * @param source - such as a string or Stream. - * @returns a new Uint8ArrayBlobAdapter extending Uint8Array. - */ - static fromString(source, encoding = "utf-8") { - switch (typeof source) { - case "string": - return transformFromString(source, encoding); - default: - throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`); + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + } else { + if ($breakOnError) { + out += ' if (true) { '; } } - /** - * @param source - Uint8Array to be mutated. - * @returns the same Uint8Array but with prototype switched to Uint8ArrayBlobAdapter. - */ - static mutate(source) { - Object.setPrototypeOf(source, _Uint8ArrayBlobAdapter.prototype); - return source; - } - /** - * @param encoding - default 'utf-8'. - * @returns the blob as string. - */ - transformToString(encoding = "utf-8") { - return transformToString(this, encoding); - } -}; - -// src/index.ts -__reExport(src_exports, __nccwpck_require__(6982), module.exports); -__reExport(src_exports, __nccwpck_require__(21927), module.exports); -__reExport(src_exports, __nccwpck_require__(33259), module.exports); -__reExport(src_exports, __nccwpck_require__(23636), module.exports); -__reExport(src_exports, __nccwpck_require__(6708), module.exports); -__reExport(src_exports, __nccwpck_require__(4515), module.exports); -__reExport(src_exports, __nccwpck_require__(88321), module.exports); -__reExport(src_exports, __nccwpck_require__(57578), module.exports); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - + return out; +} /***/ }), -/***/ 12942: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 85810: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.sdkStreamMixin = void 0; -const fetch_http_handler_1 = __nccwpck_require__(82687); -const util_base64_1 = __nccwpck_require__(75600); -const util_hex_encoding_1 = __nccwpck_require__(45364); -const util_utf8_1 = __nccwpck_require__(41895); -const stream_type_check_1 = __nccwpck_require__(57578); -const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; -const sdkStreamMixin = (stream) => { - var _a, _b; - if (!isBlobInstance(stream) && !(0, stream_type_check_1.isReadableStream)(stream)) { - const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; - throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`); - } - let transformed = false; - const transformToByteArray = async () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - transformed = true; - return await (0, fetch_http_handler_1.streamCollector)(stream); - }; - const blobToWebStream = (blob) => { - if (typeof blob.stream !== "function") { - throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\n" + - "If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body"); - } - return blob.stream(); - }; - return Object.assign(stream, { - transformToByteArray: transformToByteArray, - transformToString: async (encoding) => { - const buf = await transformToByteArray(); - if (encoding === "base64") { - return (0, util_base64_1.toBase64)(buf); - } - else if (encoding === "hex") { - return (0, util_hex_encoding_1.toHex)(buf); - } - else if (encoding === undefined || encoding === "utf8" || encoding === "utf-8") { - return (0, util_utf8_1.toUtf8)(buf); - } - else if (typeof TextDecoder === "function") { - return new TextDecoder(encoding).decode(buf); - } - else { - throw new Error("TextDecoder is not available, please make sure polyfill is provided."); - } - }, - transformToWebStream: () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - transformed = true; - if (isBlobInstance(stream)) { - return blobToWebStream(stream); - } - else if ((0, stream_type_check_1.isReadableStream)(stream)) { - return stream; - } - else { - throw new Error(`Cannot transform payload to web stream, got ${stream}`); - } - }, - }); + +//all requires must be explicit because browserify won't work with dynamic requires +module.exports = { + '$ref': __nccwpck_require__(42393), + allOf: __nccwpck_require__(89443), + anyOf: __nccwpck_require__(63093), + '$comment': __nccwpck_require__(30134), + const: __nccwpck_require__(1661), + contains: __nccwpck_require__(55964), + dependencies: __nccwpck_require__(2591), + 'enum': __nccwpck_require__(10163), + format: __nccwpck_require__(63847), + 'if': __nccwpck_require__(80862), + items: __nccwpck_require__(54408), + maximum: __nccwpck_require__(7404), + minimum: __nccwpck_require__(7404), + maxItems: __nccwpck_require__(64683), + minItems: __nccwpck_require__(64683), + maxLength: __nccwpck_require__(52114), + minLength: __nccwpck_require__(52114), + maxProperties: __nccwpck_require__(71142), + minProperties: __nccwpck_require__(71142), + multipleOf: __nccwpck_require__(39772), + not: __nccwpck_require__(60750), + oneOf: __nccwpck_require__(6106), + pattern: __nccwpck_require__(13912), + properties: __nccwpck_require__(52924), + propertyNames: __nccwpck_require__(19195), + required: __nccwpck_require__(8420), + uniqueItems: __nccwpck_require__(24995), + validate: __nccwpck_require__(49585) }; -exports.sdkStreamMixin = sdkStreamMixin; -const isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob; /***/ }), -/***/ 4515: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 54408: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.sdkStreamMixin = void 0; -const node_http_handler_1 = __nccwpck_require__(20258); -const util_buffer_from_1 = __nccwpck_require__(31381); -const stream_1 = __nccwpck_require__(12781); -const sdk_stream_mixin_browser_1 = __nccwpck_require__(12942); -const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; -const sdkStreamMixin = (stream) => { - var _a, _b; - if (!(stream instanceof stream_1.Readable)) { - try { - return (0, sdk_stream_mixin_browser_1.sdkStreamMixin)(stream); +module.exports = function generate_items(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $idx = 'i' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $currentBaseId = it.baseId; + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if (Array.isArray($schema)) { + var $additionalItems = it.schema.additionalItems; + if ($additionalItems === false) { + out += ' ' + ($valid) + ' = ' + ($data) + '.length <= ' + ($schema.length) + '; '; + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalItems'; + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('additionalItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have more than ' + ($schema.length) + ' items\' '; } - catch (e) { - const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; - throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`); + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + $errSchemaPath = $currErrSchemaPath; + if ($breakOnError) { + $closingBraces += '}'; + out += ' else { '; + } } - let transformed = false; - const transformToByteArray = async () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($i) + ') { '; + var $passData = $data + '[' + $i + ']'; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true); + $it.dataPathArr[$dataNxt] = $i; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } } - transformed = true; - return await (0, node_http_handler_1.streamCollector)(stream); - }; - return Object.assign(stream, { - transformToByteArray, - transformToString: async (encoding) => { - const buf = await transformToByteArray(); - if (encoding === undefined || Buffer.isEncoding(encoding)) { - return (0, util_buffer_from_1.fromArrayBuffer)(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding); - } - else { - const decoder = new TextDecoder(encoding); - return decoder.decode(buf); - } - }, - transformToWebStream: () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - if (stream.readableFlowing !== null) { - throw new Error("The stream has been consumed by other callbacks."); - } - if (typeof stream_1.Readable.toWeb !== "function") { - throw new Error("Readable.toWeb() is not supported. Please ensure a polyfill is available."); - } - transformed = true; - return stream_1.Readable.toWeb(stream); - }, - }); -}; -exports.sdkStreamMixin = sdkStreamMixin; + } + } + if (typeof $additionalItems == 'object' && (it.opts.strictKeywords ? (typeof $additionalItems == 'object' && Object.keys($additionalItems).length > 0) || $additionalItems === false : it.util.schemaHasRules($additionalItems, it.RULES.all))) { + $it.schema = $additionalItems; + $it.schemaPath = it.schemaPath + '.additionalItems'; + $it.errSchemaPath = it.errSchemaPath + '/additionalItems'; + out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') { for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' } } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } else if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' }'; + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + return out; +} /***/ }), -/***/ 64693: -/***/ ((__unused_webpack_module, exports) => { +/***/ 39772: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.splitStream = void 0; -async function splitStream(stream) { - if (typeof stream.stream === "function") { - stream = stream.stream(); +module.exports = function generate_multipleOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!($isData || typeof $schema == 'number')) { + throw new Error($keyword + ' must be number'); + } + out += 'var division' + ($lvl) + ';if ('; + if ($isData) { + out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || '; + } + out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', '; + if (it.opts.multipleOfPrecision) { + out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' '; + } else { + out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') '; + } + out += ' ) '; + if ($isData) { + out += ' ) '; + } + out += ' ) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be multiple of '; + if ($isData) { + out += '\' + ' + ($schemaValue); + } else { + out += '' + ($schemaValue) + '\''; + } } - const readableStream = stream; - return readableStream.tee(); + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; } -exports.splitStream = splitStream; /***/ }), -/***/ 88321: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 60750: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.splitStream = void 0; -const stream_1 = __nccwpck_require__(12781); -const splitStream_browser_1 = __nccwpck_require__(64693); -const stream_type_check_1 = __nccwpck_require__(57578); -async function splitStream(stream) { - if ((0, stream_type_check_1.isReadableStream)(stream) || (0, stream_type_check_1.isBlob)(stream)) { - return (0, splitStream_browser_1.splitStream)(stream); +module.exports = function generate_not(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + ($errs) + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.createErrors = false; + var $allErrorsOption; + if ($it.opts.allErrors) { + $allErrorsOption = $it.opts.allErrors; + $it.opts.allErrors = false; } - const stream1 = new stream_1.PassThrough(); - const stream2 = new stream_1.PassThrough(); - stream.pipe(stream1); - stream.pipe(stream2); - return [stream1, stream2]; + out += ' ' + (it.validate($it)) + ' '; + $it.createErrors = true; + if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' if (' + ($nextValid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be valid\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + if (it.opts.allErrors) { + out += ' } '; + } + } else { + out += ' var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be valid\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if ($breakOnError) { + out += ' if (false) { '; + } + } + return out; } -exports.splitStream = splitStream; /***/ }), -/***/ 57578: -/***/ ((__unused_webpack_module, exports) => { +/***/ 6106: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isBlob = exports.isReadableStream = void 0; -const isReadableStream = (stream) => { - var _a; - return typeof ReadableStream === "function" && - (((_a = stream === null || stream === void 0 ? void 0 : stream.constructor) === null || _a === void 0 ? void 0 : _a.name) === ReadableStream.name || stream instanceof ReadableStream); -}; -exports.isReadableStream = isReadableStream; -const isBlob = (blob) => { - var _a; - return typeof Blob === "function" && (((_a = blob === null || blob === void 0 ? void 0 : blob.constructor) === null || _a === void 0 ? void 0 : _a.name) === Blob.name || blob instanceof Blob); -}; -exports.isBlob = isBlob; +module.exports = function generate_oneOf(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $currentBaseId = $it.baseId, + $prevValid = 'prevValid' + $lvl, + $passingSchemas = 'passingSchemas' + $lvl; + out += 'var ' + ($errs) + ' = errors , ' + ($prevValid) + ' = false , ' + ($valid) + ' = false , ' + ($passingSchemas) + ' = null; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + } else { + out += ' var ' + ($nextValid) + ' = true; '; + } + if ($i) { + out += ' if (' + ($nextValid) + ' && ' + ($prevValid) + ') { ' + ($valid) + ' = false; ' + ($passingSchemas) + ' = [' + ($passingSchemas) + ', ' + ($i) + ']; } else { '; + $closingBraces += '}'; + } + out += ' if (' + ($nextValid) + ') { ' + ($valid) + ' = ' + ($prevValid) + ' = true; ' + ($passingSchemas) + ' = ' + ($i) + '; }'; + } + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { passingSchemas: ' + ($passingSchemas) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match exactly one schema in oneOf\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } + out += '} else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }'; + if (it.opts.allErrors) { + out += ' } '; + } + return out; +} /***/ }), -/***/ 54197: +/***/ 13912: /***/ ((module) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -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); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - escapeUri: () => escapeUri, - escapeUriPath: () => escapeUriPath -}); -module.exports = __toCommonJS(src_exports); - -// src/escape-uri.ts -var escapeUri = /* @__PURE__ */ __name((uri) => ( - // AWS percent-encodes some extra non-standard characters in a URI - encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode) -), "escapeUri"); -var hexEncode = /* @__PURE__ */ __name((c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, "hexEncode"); - -// src/escape-uri-path.ts -var escapeUriPath = /* @__PURE__ */ __name((uri) => uri.split("/").map(escapeUri).join("/"), "escapeUriPath"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); +"use strict"; +module.exports = function generate_pattern(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $regExpCode = it.opts.regExp ? 'regExp' : 'new RegExp'; + if ($isData) { + out += ' var ' + ($valid) + ' = true; try { ' + ($valid) + ' = ' + ($regExpCode) + '(' + ($schemaValue) + ').test(' + ($data) + '); } catch(e) { ' + ($valid) + ' = false; } if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; + } + out += ' !' + ($valid) + ') {'; + } else { + var $regexp = it.usePattern($schema); + out += ' if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; + } + out += ' !' + ($regexp) + '.test(' + ($data) + ') ) {'; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern: '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match pattern "'; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + (it.util.escapeQuotes($schema)); + } + out += '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} /***/ }), -/***/ 41895: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -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); +/***/ 52924: +/***/ ((module) => { -// src/index.ts -var src_exports = {}; -__export(src_exports, { - fromUtf8: () => fromUtf8, - toUint8Array: () => toUint8Array, - toUtf8: () => toUtf8 -}); -module.exports = __toCommonJS(src_exports); +"use strict"; -// src/fromUtf8.ts -var import_util_buffer_from = __nccwpck_require__(31381); -var fromUtf8 = /* @__PURE__ */ __name((input) => { - const buf = (0, import_util_buffer_from.fromString)(input, "utf8"); - return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); -}, "fromUtf8"); +module.exports = function generate_properties(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $key = 'key' + $lvl, + $idx = 'idx' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $dataProperties = 'dataProperties' + $lvl; + var $schemaKeys = Object.keys($schema || {}).filter(notProto), + $pProperties = it.schema.patternProperties || {}, + $pPropertyKeys = Object.keys($pProperties).filter(notProto), + $aProperties = it.schema.additionalProperties, + $someProperties = $schemaKeys.length || $pPropertyKeys.length, + $noAdditional = $aProperties === false, + $additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length, + $removeAdditional = it.opts.removeAdditional, + $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional, + $ownProperties = it.opts.ownProperties, + $currentBaseId = it.baseId; + var $required = it.schema.required; + if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) { + var $requiredHash = it.util.toHash($required); + } -// src/toUint8Array.ts -var toUint8Array = /* @__PURE__ */ __name((data) => { - if (typeof data === "string") { - return fromUtf8(data); + function notProto(p) { + return p !== '__proto__'; } - if (ArrayBuffer.isView(data)) { - return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); + out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;'; + if ($ownProperties) { + out += ' var ' + ($dataProperties) + ' = undefined;'; + } + if ($checkAdditional) { + if ($ownProperties) { + out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; + } else { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + } + if ($someProperties) { + out += ' var isAdditional' + ($lvl) + ' = !(false '; + if ($schemaKeys.length) { + if ($schemaKeys.length > 8) { + out += ' || validate.schema' + ($schemaPath) + '.hasOwnProperty(' + ($key) + ') '; + } else { + var arr1 = $schemaKeys; + if (arr1) { + var $propertyKey, i1 = -1, + l1 = arr1.length - 1; + while (i1 < l1) { + $propertyKey = arr1[i1 += 1]; + out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' '; + } + } + } + } + if ($pPropertyKeys.length) { + var arr2 = $pPropertyKeys; + if (arr2) { + var $pProperty, $i = -1, + l2 = arr2.length - 1; + while ($i < l2) { + $pProperty = arr2[$i += 1]; + out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') '; + } + } + } + out += ' ); if (isAdditional' + ($lvl) + ') { '; + } + if ($removeAdditional == 'all') { + out += ' delete ' + ($data) + '[' + ($key) + ']; '; + } else { + var $currentErrorPath = it.errorPath; + var $additionalProperty = '\' + ' + $key + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + } + if ($noAdditional) { + if ($removeAdditional) { + out += ' delete ' + ($data) + '[' + ($key) + ']; '; + } else { + out += ' ' + ($nextValid) + ' = false; '; + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalProperties'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is an invalid additional property'; + } else { + out += 'should NOT have additional properties'; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + $errSchemaPath = $currErrSchemaPath; + if ($breakOnError) { + out += ' break; '; + } + } + } else if ($additionalIsSchema) { + if ($removeAdditional == 'failing') { + out += ' var ' + ($errs) + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + } else { + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + } + } + it.errorPath = $currentErrorPath; + } + if ($someProperties) { + out += ' } '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + var $useDefaults = it.opts.useDefaults && !it.compositeRule; + if ($schemaKeys.length) { + var arr3 = $schemaKeys; + if (arr3) { + var $propertyKey, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $sch = $schema[$propertyKey]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + var $prop = it.util.getProperty($propertyKey), + $passData = $data + $prop, + $hasDefault = $useDefaults && $sch.default !== undefined; + $it.schema = $sch; + $it.schemaPath = $schemaPath + $prop; + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey); + $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers); + $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey); + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + $code = it.util.varReplace($code, $nextData, $passData); + var $useData = $passData; + } else { + var $useData = $nextData; + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; '; + } + if ($hasDefault) { + out += ' ' + ($code) + ' '; + } else { + if ($requiredHash && $requiredHash[$propertyKey]) { + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') { ' + ($nextValid) + ' = false; '; + var $currentErrorPath = it.errorPath, + $currErrSchemaPath = $errSchemaPath, + $missingProperty = it.util.escapeQuotes($propertyKey); + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + $errSchemaPath = it.errSchemaPath + '/required'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + $errSchemaPath = $currErrSchemaPath; + it.errorPath = $currentErrorPath; + out += ' } else { '; + } else { + if ($breakOnError) { + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') { ' + ($nextValid) + ' = true; } else { '; + } else { + out += ' if (' + ($useData) + ' !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ' ) { '; + } + } + out += ' ' + ($code) + ' } '; + } + } + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } } - return new Uint8Array(data); -}, "toUint8Array"); - -// src/toUtf8.ts - -var toUtf8 = /* @__PURE__ */ __name((input) => { - if (typeof input === "string") { - return input; + if ($pPropertyKeys.length) { + var arr4 = $pPropertyKeys; + if (arr4) { + var $pProperty, i4 = -1, + l4 = arr4.length - 1; + while (i4 < l4) { + $pProperty = arr4[i4 += 1]; + var $sch = $pProperties[$pProperty]; + if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { + $it.schema = $sch; + $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty); + $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty); + if ($ownProperties) { + out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; + } else { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + } + out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else ' + ($nextValid) + ' = true; '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } } - if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { - throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; } - return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); -}, "toUtf8"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - + return out; +} /***/ }), -/***/ 78011: +/***/ 19195: /***/ ((module) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -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); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - WaiterState: () => WaiterState, - checkExceptions: () => checkExceptions, - createWaiter: () => createWaiter, - waiterServiceDefaults: () => waiterServiceDefaults -}); -module.exports = __toCommonJS(src_exports); - -// src/utils/sleep.ts -var sleep = /* @__PURE__ */ __name((seconds) => { - return new Promise((resolve) => setTimeout(resolve, seconds * 1e3)); -}, "sleep"); - -// src/waiter.ts -var waiterServiceDefaults = { - minDelay: 2, - maxDelay: 120 -}; -var WaiterState = /* @__PURE__ */ ((WaiterState2) => { - WaiterState2["ABORTED"] = "ABORTED"; - WaiterState2["FAILURE"] = "FAILURE"; - WaiterState2["SUCCESS"] = "SUCCESS"; - WaiterState2["RETRY"] = "RETRY"; - WaiterState2["TIMEOUT"] = "TIMEOUT"; - return WaiterState2; -})(WaiterState || {}); -var checkExceptions = /* @__PURE__ */ __name((result) => { - if (result.state === "ABORTED" /* ABORTED */) { - const abortError = new Error( - `${JSON.stringify({ - ...result, - reason: "Request was aborted" - })}` - ); - abortError.name = "AbortError"; - throw abortError; - } else if (result.state === "TIMEOUT" /* TIMEOUT */) { - const timeoutError = new Error( - `${JSON.stringify({ - ...result, - reason: "Waiter has timed out" - })}` - ); - timeoutError.name = "TimeoutError"; - throw timeoutError; - } else if (result.state !== "SUCCESS" /* SUCCESS */) { - throw new Error(`${JSON.stringify(result)}`); - } - return result; -}, "checkExceptions"); +"use strict"; -// src/poller.ts -var exponentialBackoffWithJitter = /* @__PURE__ */ __name((minDelay, maxDelay, attemptCeiling, attempt) => { - if (attempt > attemptCeiling) - return maxDelay; - const delay = minDelay * 2 ** (attempt - 1); - return randomInRange(minDelay, delay); -}, "exponentialBackoffWithJitter"); -var randomInRange = /* @__PURE__ */ __name((min, max) => min + Math.random() * (max - min), "randomInRange"); -var runPolling = /* @__PURE__ */ __name(async ({ minDelay, maxDelay, maxWaitTime, abortController, client, abortSignal }, input, acceptorChecks) => { - const observedResponses = {}; - const { state, reason } = await acceptorChecks(client, input); - if (reason) { - const message = createMessageFromResponse(reason); - observedResponses[message] |= 0; - observedResponses[message] += 1; - } - if (state !== "RETRY" /* RETRY */) { - return { state, reason, observedResponses }; - } - let currentAttempt = 1; - const waitUntil = Date.now() + maxWaitTime * 1e3; - const attemptCeiling = Math.log(maxDelay / minDelay) / Math.log(2) + 1; - while (true) { - if (abortController?.signal?.aborted || abortSignal?.aborted) { - const message = "AbortController signal aborted."; - observedResponses[message] |= 0; - observedResponses[message] += 1; - return { state: "ABORTED" /* ABORTED */, observedResponses }; +module.exports = function generate_propertyNames(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + out += 'var ' + ($errs) + ' = errors;'; + if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + var $key = 'key' + $lvl, + $idx = 'idx' + $lvl, + $i = 'i' + $lvl, + $invalidName = '\' + ' + $key + ' + \'', + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $dataProperties = 'dataProperties' + $lvl, + $ownProperties = it.opts.ownProperties, + $currentBaseId = it.baseId; + if ($ownProperties) { + out += ' var ' + ($dataProperties) + ' = undefined; '; } - const delay = exponentialBackoffWithJitter(minDelay, maxDelay, attemptCeiling, currentAttempt); - if (Date.now() + delay * 1e3 > waitUntil) { - return { state: "TIMEOUT" /* TIMEOUT */, observedResponses }; + if ($ownProperties) { + out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; + } else { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; } - await sleep(delay); - const { state: state2, reason: reason2 } = await acceptorChecks(client, input); - if (reason2) { - const message = createMessageFromResponse(reason2); - observedResponses[message] |= 0; - observedResponses[message] += 1; + out += ' var startErrs' + ($lvl) + ' = errors; '; + var $passData = $key; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; } - if (state2 !== "RETRY" /* RETRY */) { - return { state: state2, reason: reason2, observedResponses }; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' if (!' + ($nextValid) + ') { for (var ' + ($i) + '=startErrs' + ($lvl) + '; ' + ($i) + ' { - if (reason?.$responseBodyText) { - return `Deserialization error for body: ${reason.$responseBodyText}`; - } - if (reason?.$metadata?.httpStatusCode) { - if (reason.$response || reason.message) { - return `${reason.$response.statusCode ?? reason.$metadata.httpStatusCode ?? "Unknown"}: ${reason.message}`; + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } } - return `${reason.$metadata.httpStatusCode}: OK`; - } - return String(reason?.message ?? JSON.stringify(reason) ?? "Unknown"); -}, "createMessageFromResponse"); - -// src/utils/validate.ts -var validateWaiterOptions = /* @__PURE__ */ __name((options) => { - if (options.maxWaitTime <= 0) { - throw new Error(`WaiterConfiguration.maxWaitTime must be greater than 0`); - } else if (options.minDelay <= 0) { - throw new Error(`WaiterConfiguration.minDelay must be greater than 0`); - } else if (options.maxDelay <= 0) { - throw new Error(`WaiterConfiguration.maxDelay must be greater than 0`); - } else if (options.maxWaitTime <= options.minDelay) { - throw new Error( - `WaiterConfiguration.maxWaitTime [${options.maxWaitTime}] must be greater than WaiterConfiguration.minDelay [${options.minDelay}] for this waiter` - ); - } else if (options.maxDelay < options.minDelay) { - throw new Error( - `WaiterConfiguration.maxDelay [${options.maxDelay}] must be greater than WaiterConfiguration.minDelay [${options.minDelay}] for this waiter` - ); - } -}, "validateWaiterOptions"); - -// src/createWaiter.ts -var abortTimeout = /* @__PURE__ */ __name(async (abortSignal) => { - return new Promise((resolve) => { - const onAbort = /* @__PURE__ */ __name(() => resolve({ state: "ABORTED" /* ABORTED */ }), "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - abortSignal.addEventListener("abort", onAbort); - } else { - abortSignal.onabort = onAbort; + if ($breakOnError) { + out += ' break; '; } - }); -}, "abortTimeout"); -var createWaiter = /* @__PURE__ */ __name(async (options, input, acceptorChecks) => { - const params = { - ...waiterServiceDefaults, - ...options - }; - validateWaiterOptions(params); - const exitConditions = [runPolling(params, input, acceptorChecks)]; - if (options.abortController) { - exitConditions.push(abortTimeout(options.abortController.signal)); + out += ' } }'; } - if (options.abortSignal) { - exitConditions.push(abortTimeout(options.abortSignal)); + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; } - return Promise.race(exitConditions); -}, "createWaiter"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (0); - - - -/***/ }), - -/***/ 61231: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const indentString = __nccwpck_require__(98043); -const cleanStack = __nccwpck_require__(27972); - -const cleanInternalStack = stack => stack.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, ''); - -class AggregateError extends Error { - constructor(errors) { - if (!Array.isArray(errors)) { - throw new TypeError(`Expected input to be an Array, got ${typeof errors}`); - } - - errors = [...errors].map(error => { - if (error instanceof Error) { - return error; - } - - if (error !== null && typeof error === 'object') { - // Handle plain error objects with message property and/or possibly other metadata - return Object.assign(new Error(error.message), error); - } - - return new Error(error); - }); - - let message = errors - .map(error => { - // The `stack` property is not standardized, so we can't assume it exists - return typeof error.stack === 'string' ? cleanInternalStack(cleanStack(error.stack)) : String(error); - }) - .join('\n'); - message = '\n' + indentString(message, 4); - super(message); - - this.name = 'AggregateError'; - - Object.defineProperty(this, '_errors', {value: errors}); - } - - * [Symbol.iterator]() { - for (const error of this._errors) { - yield error; - } - } + return out; } -module.exports = AggregateError; - /***/ }), -/***/ 64941: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 42393: +/***/ ((module) => { "use strict"; - -var compileSchema = __nccwpck_require__(875) - , resolve = __nccwpck_require__(63896) - , Cache = __nccwpck_require__(93679) - , SchemaObject = __nccwpck_require__(37605) - , stableStringify = __nccwpck_require__(30969) - , formats = __nccwpck_require__(66627) - , rules = __nccwpck_require__(68561) - , $dataMetaSchema = __nccwpck_require__(21412) - , util = __nccwpck_require__(76578); - -module.exports = Ajv; - -Ajv.prototype.validate = validate; -Ajv.prototype.compile = compile; -Ajv.prototype.addSchema = addSchema; -Ajv.prototype.addMetaSchema = addMetaSchema; -Ajv.prototype.validateSchema = validateSchema; -Ajv.prototype.getSchema = getSchema; -Ajv.prototype.removeSchema = removeSchema; -Ajv.prototype.addFormat = addFormat; -Ajv.prototype.errorsText = errorsText; - -Ajv.prototype._addSchema = _addSchema; -Ajv.prototype._compile = _compile; - -Ajv.prototype.compileAsync = __nccwpck_require__(80890); -var customKeyword = __nccwpck_require__(53297); -Ajv.prototype.addKeyword = customKeyword.add; -Ajv.prototype.getKeyword = customKeyword.get; -Ajv.prototype.removeKeyword = customKeyword.remove; -Ajv.prototype.validateKeyword = customKeyword.validate; - -var errorClasses = __nccwpck_require__(25726); -Ajv.ValidationError = errorClasses.Validation; -Ajv.MissingRefError = errorClasses.MissingRef; -Ajv.$dataMetaSchema = $dataMetaSchema; - -var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema'; - -var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ]; -var META_SUPPORT_DATA = ['/properties']; - -/** - * Creates validator instance. - * Usage: `Ajv(opts)` - * @param {Object} opts optional options - * @return {Object} ajv instance - */ -function Ajv(opts) { - if (!(this instanceof Ajv)) return new Ajv(opts); - opts = this._opts = util.copy(opts) || {}; - setLogger(this); - this._schemas = {}; - this._refs = {}; - this._fragments = {}; - this._formats = formats(opts.format); - - this._cache = opts.cache || new Cache; - this._loadingSchemas = {}; - this._compilations = []; - this.RULES = rules(); - this._getId = chooseGetId(opts); - - opts.loopRequired = opts.loopRequired || Infinity; - if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true; - if (opts.serialize === undefined) opts.serialize = stableStringify; - this._metaOpts = getMetaSchemaOptions(this); - - if (opts.formats) addInitialFormats(this); - if (opts.keywords) addInitialKeywords(this); - addDefaultMetaSchema(this); - if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta); - if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}}); - addInitialSchemas(this); -} - - - -/** - * Validate data using schema - * Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize. - * @this Ajv - * @param {String|Object} schemaKeyRef key, ref or schema object - * @param {Any} data to be validated - * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`). - */ -function validate(schemaKeyRef, data) { - var v; - if (typeof schemaKeyRef == 'string') { - v = this.getSchema(schemaKeyRef); - if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"'); +module.exports = function generate_ref(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $async, $refCode; + if ($schema == '#' || $schema == '#/') { + if (it.isRoot) { + $async = it.async; + $refCode = 'validate'; + } else { + $async = it.root.schema.$async === true; + $refCode = 'root.refVal[0]'; + } } else { - var schemaObj = this._addSchema(schemaKeyRef); - v = schemaObj.validate || this._compile(schemaObj); - } - - var valid = v(data); - if (v.$async !== true) this.errors = v.errors; - return valid; -} - - -/** - * Create validating function for passed schema. - * @this Ajv - * @param {Object} schema schema object - * @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords. - * @return {Function} validating function - */ -function compile(schema, _meta) { - var schemaObj = this._addSchema(schema, undefined, _meta); - return schemaObj.validate || this._compile(schemaObj); -} - - -/** - * Adds schema to the instance. - * @this Ajv - * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored. - * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. - * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead. - * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. - * @return {Ajv} this for method chaining - */ -function addSchema(schema, key, _skipValidation, _meta) { - if (Array.isArray(schema)){ - for (var i=0; i { +"use strict"; -function _getSchemaFragment(self, ref) { - var res = resolve.schema.call(self, { schema: {} }, ref); - if (res) { - var schema = res.schema - , root = res.root - , baseId = res.baseId; - var v = compileSchema.call(self, schema, root, undefined, baseId); - self._fragments[ref] = new SchemaObject({ - ref: ref, - fragment: true, - schema: schema, - root: root, - baseId: baseId, - validate: v - }); - return v; +module.exports = function generate_required(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; } -} - - -function _getSchemaObj(self, keyRef) { - keyRef = resolve.normalizeId(keyRef); - return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef]; -} - - -/** - * Remove cached schema(s). - * If no parameter is passed all schemas but meta-schemas are removed. - * If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. - * Even if schema is referenced by other schemas it still can be removed as other schemas have local references. - * @this Ajv - * @param {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object - * @return {Ajv} this for method chaining - */ -function removeSchema(schemaKeyRef) { - if (schemaKeyRef instanceof RegExp) { - _removeAllSchemas(this, this._schemas, schemaKeyRef); - _removeAllSchemas(this, this._refs, schemaKeyRef); - return this; + var $vSchema = 'schema' + $lvl; + if (!$isData) { + if ($schema.length < it.opts.loopRequired && it.schema.properties && Object.keys(it.schema.properties).length) { + var $required = []; + var arr1 = $schema; + if (arr1) { + var $property, i1 = -1, + l1 = arr1.length - 1; + while (i1 < l1) { + $property = arr1[i1 += 1]; + var $propertySch = it.schema.properties[$property]; + if (!($propertySch && (it.opts.strictKeywords ? (typeof $propertySch == 'object' && Object.keys($propertySch).length > 0) || $propertySch === false : it.util.schemaHasRules($propertySch, it.RULES.all)))) { + $required[$required.length] = $property; + } + } + } + } else { + var $required = $schema; + } } - switch (typeof schemaKeyRef) { - case 'undefined': - _removeAllSchemas(this, this._schemas); - _removeAllSchemas(this, this._refs); - this._cache.clear(); - return this; - case 'string': - var schemaObj = _getSchemaObj(this, schemaKeyRef); - if (schemaObj) this._cache.del(schemaObj.cacheKey); - delete this._schemas[schemaKeyRef]; - delete this._refs[schemaKeyRef]; - return this; - case 'object': - var serialize = this._opts.serialize; - var cacheKey = serialize ? serialize(schemaKeyRef) : schemaKeyRef; - this._cache.del(cacheKey); - var id = this._getId(schemaKeyRef); - if (id) { - id = resolve.normalizeId(id); - delete this._schemas[id]; - delete this._refs[id]; + if ($isData || $required.length) { + var $currentErrorPath = it.errorPath, + $loopRequired = $isData || $required.length >= it.opts.loopRequired, + $ownProperties = it.opts.ownProperties; + if ($breakOnError) { + out += ' var missing' + ($lvl) + '; '; + if ($loopRequired) { + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; + } + var $i = 'i' + $lvl, + $propertyPath = 'schema' + $lvl + '[' + $i + ']', + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); + } + out += ' var ' + ($valid) + ' = true; '; + if ($isData) { + out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; + } + out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined '; + if ($ownProperties) { + out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) '; + } + out += '; if (!' + ($valid) + ') break; } '; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + } else { + out += ' if ( '; + var arr2 = $required; + if (arr2) { + var $propertyKey, $i = -1, + l2 = arr2.length - 1; + while ($i < l2) { + $propertyKey = arr2[$i += 1]; + if ($i) { + out += ' || '; + } + var $prop = it.util.getProperty($propertyKey), + $useData = $data + $prop; + out += ' ( ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) '; + } + } + out += ') { '; + var $propertyPath = 'missing' + $lvl, + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + } + } else { + if ($loopRequired) { + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; + } + var $i = 'i' + $lvl, + $propertyPath = 'schema' + $lvl + '[' + $i + ']', + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); + } + if ($isData) { + out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { '; + } + out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) '; + } + out += ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } '; + if ($isData) { + out += ' } '; + } + } else { + var arr3 = $required; + if (arr3) { + var $propertyKey, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $prop = it.util.getProperty($propertyKey), + $missingProperty = it.util.escapeQuotes($propertyKey), + $useData = $data + $prop; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + out += ' if ( ' + ($useData) + ' === undefined '; + if ($ownProperties) { + out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; + } + out += ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; + } + } } - } - return this; -} - - -function _removeAllSchemas(self, schemas, regex) { - for (var keyRef in schemas) { - var schemaObj = schemas[keyRef]; - if (!schemaObj.meta && (!regex || regex.test(keyRef))) { - self._cache.del(schemaObj.cacheKey); - delete schemas[keyRef]; } + it.errorPath = $currentErrorPath; + } else if ($breakOnError) { + out += ' if (true) {'; } + return out; } -/* @this Ajv */ -function _addSchema(schema, skipValidation, meta, shouldAddSchema) { - if (typeof schema != 'object' && typeof schema != 'boolean') - throw new Error('schema should be object or boolean'); - var serialize = this._opts.serialize; - var cacheKey = serialize ? serialize(schema) : schema; - var cached = this._cache.get(cacheKey); - if (cached) return cached; - - shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false; - - var id = resolve.normalizeId(this._getId(schema)); - if (id && shouldAddSchema) checkUnique(this, id); +/***/ }), - var willValidate = this._opts.validateSchema !== false && !skipValidation; - var recursiveMeta; - if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema))) - this.validateSchema(schema, true); +/***/ 24995: +/***/ ((module) => { - var localRefs = resolve.ids.call(this, schema); +"use strict"; - var schemaObj = new SchemaObject({ - id: id, - schema: schema, - localRefs: localRefs, - cacheKey: cacheKey, - meta: meta - }); +module.exports = function generate_uniqueItems(it, $keyword, $ruleType) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.$data && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (($schema || $isData) && it.opts.uniqueItems !== false) { + if ($isData) { + out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { '; + } + out += ' var i = ' + ($data) + '.length , ' + ($valid) + ' = true , j; if (i > 1) { '; + var $itemType = it.schema.items && it.schema.items.type, + $typeIsArray = Array.isArray($itemType); + if (!$itemType || $itemType == 'object' || $itemType == 'array' || ($typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0))) { + out += ' outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } '; + } else { + out += ' var itemIndices = {}, item; for (;i--;) { var item = ' + ($data) + '[i]; '; + var $method = 'checkDataType' + ($typeIsArray ? 's' : ''); + out += ' if (' + (it.util[$method]($itemType, 'item', it.opts.strictNumbers, true)) + ') continue; '; + if ($typeIsArray) { + out += ' if (typeof item == \'string\') item = \'"\' + item; '; + } + out += ' if (typeof itemIndices[item] == \'number\') { ' + ($valid) + ' = false; j = itemIndices[item]; break; } itemIndices[item] = i; } '; + } + out += ' } '; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} - if (id[0] != '#' && shouldAddSchema) this._refs[id] = schemaObj; - this._cache.put(cacheKey, schemaObj); - if (willValidate && recursiveMeta) this.validateSchema(schema, true); +/***/ }), - return schemaObj; -} +/***/ 49585: +/***/ ((module) => { +"use strict"; -/* @this Ajv */ -function _compile(schemaObj, root) { - if (schemaObj.compiling) { - schemaObj.validate = callValidate; - callValidate.schema = schemaObj.schema; - callValidate.errors = null; - callValidate.root = root ? root : callValidate; - if (schemaObj.schema.$async === true) - callValidate.$async = true; - return callValidate; +module.exports = function generate_validate(it, $keyword, $ruleType) { + var out = ''; + var $async = it.schema.$async === true, + $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'), + $id = it.self._getId(it.schema); + if (it.opts.strictKeywords) { + var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords); + if ($unknownKwd) { + var $keywordsMsg = 'unknown keyword: ' + $unknownKwd; + if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg); + else throw new Error($keywordsMsg); + } } - schemaObj.compiling = true; - - var currentOpts; - if (schemaObj.meta) { - currentOpts = this._opts; - this._opts = this._metaOpts; + if (it.isTop) { + out += ' var validate = '; + if ($async) { + it.async = true; + out += 'async '; + } + out += 'function(data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; '; + if ($id && (it.opts.sourceCode || it.opts.processCode)) { + out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' '; + } } - - var v; - try { v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs); } - catch(e) { - delete schemaObj.validate; - throw e; + if (typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref)) { + var $keyword = 'false schema'; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + if (it.schema === false) { + if (it.isTop) { + $breakOnError = true; + } else { + out += ' var ' + ($valid) + ' = false; '; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'boolean schema is false\' '; + } + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { + /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } else { + if (it.isTop) { + if ($async) { + out += ' return data; '; + } else { + out += ' validate.errors = null; return true; '; + } + } else { + out += ' var ' + ($valid) + ' = true; '; + } + } + if (it.isTop) { + out += ' }; return validate; '; + } + return out; } - finally { - schemaObj.compiling = false; - if (schemaObj.meta) this._opts = currentOpts; + if (it.isTop) { + var $top = it.isTop, + $lvl = it.level = 0, + $dataLvl = it.dataLevel = 0, + $data = 'data'; + it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema)); + it.baseId = it.baseId || it.rootId; + delete it.isTop; + it.dataPathArr = [""]; + if (it.schema.default !== undefined && it.opts.useDefaults && it.opts.strictDefaults) { + var $defaultMsg = 'default is ignored in the schema root'; + if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); + else throw new Error($defaultMsg); + } + out += ' var vErrors = null; '; + out += ' var errors = 0; '; + out += ' if (rootData === undefined) rootData = data; '; + } else { + var $lvl = it.level, + $dataLvl = it.dataLevel, + $data = 'data' + ($dataLvl || ''); + if ($id) it.baseId = it.resolve.url(it.baseId, $id); + if ($async && !it.async) throw new Error('async schema in sync schema'); + out += ' var errs_' + ($lvl) + ' = errors;'; } - - schemaObj.validate = v; - schemaObj.refs = v.refs; - schemaObj.refVal = v.refVal; - schemaObj.root = v.root; - return v; - - - /* @this {*} - custom context, see passContext option */ - function callValidate() { - /* jshint validthis: true */ - var _validate = schemaObj.validate; - var result = _validate.apply(this, arguments); - callValidate.errors = _validate.errors; - return result; + var $valid = 'valid' + $lvl, + $breakOnError = !it.opts.allErrors, + $closingBraces1 = '', + $closingBraces2 = ''; + var $errorKeyword; + var $typeSchema = it.schema.type, + $typeIsArray = Array.isArray($typeSchema); + if ($typeSchema && it.opts.nullable && it.schema.nullable === true) { + if ($typeIsArray) { + if ($typeSchema.indexOf('null') == -1) $typeSchema = $typeSchema.concat('null'); + } else if ($typeSchema != 'null') { + $typeSchema = [$typeSchema, 'null']; + $typeIsArray = true; + } } -} - - -function chooseGetId(opts) { - switch (opts.schemaId) { - case 'auto': return _get$IdOrId; - case 'id': return _getId; - default: return _get$Id; + if ($typeIsArray && $typeSchema.length == 1) { + $typeSchema = $typeSchema[0]; + $typeIsArray = false; } -} - -/* @this Ajv */ -function _getId(schema) { - if (schema.$id) this.logger.warn('schema $id ignored', schema.$id); - return schema.id; -} - -/* @this Ajv */ -function _get$Id(schema) { - if (schema.id) this.logger.warn('schema id ignored', schema.id); - return schema.$id; -} - - -function _get$IdOrId(schema) { - if (schema.$id && schema.id && schema.$id != schema.id) - throw new Error('schema $id is different from id'); - return schema.$id || schema.id; -} - - -/** - * Convert array of error message objects to string - * @this Ajv - * @param {Array} errors optional array of validation errors, if not passed errors from the instance are used. - * @param {Object} options optional options with properties `separator` and `dataVar`. - * @return {String} human readable string with all errors descriptions - */ -function errorsText(errors, options) { - errors = errors || this.errors; - if (!errors) return 'No errors'; - options = options || {}; - var separator = options.separator === undefined ? ', ' : options.separator; - var dataVar = options.dataVar === undefined ? 'data' : options.dataVar; - - var text = ''; - for (var i=0; i { - -"use strict"; - - - -var Cache = module.exports = function Cache() { - this._cache = {}; -}; - - -Cache.prototype.put = function Cache_put(key, value) { - this._cache[key] = value; -}; - -Cache.prototype.get = function Cache_get(key) { - return this._cache[key]; -}; - - -Cache.prototype.del = function Cache_del(key) { - delete this._cache[key]; -}; + function $shouldUseGroup($rulesGroup) { + var rules = $rulesGroup.rules; + for (var i = 0; i < rules.length; i++) + if ($shouldUseRule(rules[i])) return true; + } + function $shouldUseRule($rule) { + return it.schema[$rule.keyword] !== undefined || ($rule.implements && $ruleImplementsSomeKeyword($rule)); + } -Cache.prototype.clear = function Cache_clear() { - this._cache = {}; -}; + function $ruleImplementsSomeKeyword($rule) { + var impl = $rule.implements; + for (var i = 0; i < impl.length; i++) + if (it.schema[impl[i]] !== undefined) return true; + } + return out; +} /***/ }), -/***/ 80890: +/***/ 53297: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var MissingRefError = (__nccwpck_require__(25726).MissingRef); +var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i; +var customRuleCode = __nccwpck_require__(5912); +var definitionSchema = __nccwpck_require__(10458); -module.exports = compileAsync; +module.exports = { + add: addKeyword, + get: getKeyword, + remove: removeKeyword, + validate: validateKeyword +}; /** - * Creates validating function for passed schema with asynchronous loading of missing schemas. - * `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema. + * Define custom keyword * @this Ajv - * @param {Object} schema schema object - * @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped - * @param {Function} callback an optional node-style callback, it is called with 2 parameters: error (or null) and validating function. - * @return {Promise} promise that resolves with a validating function. + * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords). + * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`. + * @return {Ajv} this for method chaining */ -function compileAsync(schema, meta, callback) { - /* eslint no-shadow: 0 */ - /* global Promise */ +function addKeyword(keyword, definition) { /* jshint validthis: true */ - var self = this; - if (typeof this._opts.loadSchema != 'function') - throw new Error('options.loadSchema should be a function'); + /* eslint no-shadow: 0 */ + var RULES = this.RULES; + if (RULES.keywords[keyword]) + throw new Error('Keyword ' + keyword + ' is already defined'); - if (typeof meta == 'function') { - callback = meta; - meta = undefined; - } + if (!IDENTIFIER.test(keyword)) + throw new Error('Keyword ' + keyword + ' is not a valid identifier'); - var p = loadMetaSchemaOf(schema).then(function () { - var schemaObj = self._addSchema(schema, undefined, meta); - return schemaObj.validate || _compileAsync(schemaObj); - }); + if (definition) { + this.validateKeyword(definition, true); - if (callback) { - p.then( - function(v) { callback(null, v); }, - callback - ); - } + var dataType = definition.type; + if (Array.isArray(dataType)) { + for (var i=0; i { - -"use strict"; - - -var resolve = __nccwpck_require__(63896); +/** + * Validate keyword definition + * @this Ajv + * @param {Object} definition keyword definition object. + * @param {Boolean} throwError true to throw exception if definition is invalid + * @return {boolean} validation result + */ +function validateKeyword(definition, throwError) { + validateKeyword.errors = null; + var v = this._validateKeyword = this._validateKeyword + || this.compile(definitionSchema, true); -module.exports = { - Validation: errorSubclass(ValidationError), - MissingRef: errorSubclass(MissingRefError) -}; + if (v(definition)) return true; + validateKeyword.errors = v.errors; + if (throwError) + throw new Error('custom keyword definition is invalid: ' + this.errorsText(v.errors)); + else + return false; +} -function ValidationError(errors) { - this.message = 'validation failed'; - this.errors = errors; - this.ajv = this.validation = true; -} +/***/ }), +/***/ 99348: +/***/ ((module) => { -MissingRefError.message = function (baseId, ref) { - return 'can\'t resolve reference ' + ref + ' from id ' + baseId; -}; +// Copyright 2011 Mark Cavage All rights reserved. -function MissingRefError(baseId, ref, message) { - this.message = message || MissingRefError.message(baseId, ref); - this.missingRef = resolve.url(baseId, ref); - this.missingSchema = resolve.normalizeId(resolve.fullPath(this.missingRef)); -} +module.exports = { + newInvalidAsn1Error: function (msg) { + var e = new Error(); + e.name = 'InvalidAsn1Error'; + e.message = msg || ''; + return e; + } -function errorSubclass(Subclass) { - Subclass.prototype = Object.create(Error.prototype); - Subclass.prototype.constructor = Subclass; - return Subclass; -} +}; /***/ }), -/***/ 66627: +/***/ 194: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - - -var util = __nccwpck_require__(76578); +// Copyright 2011 Mark Cavage All rights reserved. -var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; -var DAYS = [0,31,28,31,30,31,30,31,31,30,31,30,31]; -var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i; -var HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i; -var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; -var URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; -// uri-template: https://tools.ietf.org/html/rfc6570 -var URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; -// For the source: https://gist.github.com/dperini/729294 -// For test cases: https://mathiasbynens.be/demo/url-regex -// @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983. -// var URL = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; -var URL = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i; -var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; -var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; -var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; -var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; +var errors = __nccwpck_require__(99348); +var types = __nccwpck_require__(42473); +var Reader = __nccwpck_require__(20290); +var Writer = __nccwpck_require__(43200); -module.exports = formats; -function formats(mode) { - mode = mode == 'full' ? 'full' : 'fast'; - return util.copy(formats[mode]); -} +// --- Exports +module.exports = { -formats.fast = { - // date: http://tools.ietf.org/html/rfc3339#section-5.6 - date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/, - // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 - time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, - 'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, - // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js - uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, - 'uri-reference': /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, - 'uri-template': URITEMPLATE, - url: URL, - // email (sources from jsen validator): - // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 - // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation') - email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i, - hostname: HOSTNAME, - // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html - ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, - // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses - ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, - regex: regex, - // uuid: http://tools.ietf.org/html/rfc4122 - uuid: UUID, - // JSON-pointer: https://tools.ietf.org/html/rfc6901 - // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A - 'json-pointer': JSON_POINTER, - 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT, - // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 - 'relative-json-pointer': RELATIVE_JSON_POINTER -}; + Reader: Reader, + Writer: Writer -formats.full = { - date: date, - time: time, - 'date-time': date_time, - uri: uri, - 'uri-reference': URIREF, - 'uri-template': URITEMPLATE, - url: URL, - email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, - hostname: HOSTNAME, - ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, - ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, - regex: regex, - uuid: UUID, - 'json-pointer': JSON_POINTER, - 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT, - 'relative-json-pointer': RELATIVE_JSON_POINTER }; - -function isLeapYear(year) { - // https://tools.ietf.org/html/rfc3339#appendix-C - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +for (var t in types) { + if (types.hasOwnProperty(t)) + module.exports[t] = types[t]; +} +for (var e in errors) { + if (errors.hasOwnProperty(e)) + module.exports[e] = errors[e]; } -function date(str) { - // full-date from http://tools.ietf.org/html/rfc3339#section-5.6 - var matches = str.match(DATE); - if (!matches) return false; +/***/ }), - var year = +matches[1]; - var month = +matches[2]; - var day = +matches[3]; +/***/ 20290: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return month >= 1 && month <= 12 && day >= 1 && - day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]); -} +// Copyright 2011 Mark Cavage All rights reserved. +var assert = __nccwpck_require__(39491); +var Buffer = (__nccwpck_require__(15118).Buffer); -function time(str, full) { - var matches = str.match(TIME); - if (!matches) return false; +var ASN1 = __nccwpck_require__(42473); +var errors = __nccwpck_require__(99348); - var hour = matches[1]; - var minute = matches[2]; - var second = matches[3]; - var timeZone = matches[5]; - return ((hour <= 23 && minute <= 59 && second <= 59) || - (hour == 23 && minute == 59 && second == 60)) && - (!full || timeZone); -} +// --- Globals -var DATE_TIME_SEPARATOR = /t|\s/i; -function date_time(str) { - // http://tools.ietf.org/html/rfc3339#section-5.6 - var dateTime = str.split(DATE_TIME_SEPARATOR); - return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true); -} +var newInvalidAsn1Error = errors.newInvalidAsn1Error; -var NOT_URI_FRAGMENT = /\/|:/; -function uri(str) { - // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "." - return NOT_URI_FRAGMENT.test(str) && URI.test(str); -} +// --- API -var Z_ANCHOR = /[^\\]\\Z/; -function regex(str) { - if (Z_ANCHOR.test(str)) return false; - try { - new RegExp(str); - return true; - } catch(e) { - return false; - } -} +function Reader(data) { + if (!data || !Buffer.isBuffer(data)) + throw new TypeError('data must be a node Buffer'); + this._buf = data; + this._size = data.length; -/***/ }), + // These hold the "current" state + this._len = 0; + this._offset = 0; +} -/***/ 875: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +Object.defineProperty(Reader.prototype, 'length', { + enumerable: true, + get: function () { return (this._len); } +}); -"use strict"; +Object.defineProperty(Reader.prototype, 'offset', { + enumerable: true, + get: function () { return (this._offset); } +}); +Object.defineProperty(Reader.prototype, 'remain', { + get: function () { return (this._size - this._offset); } +}); -var resolve = __nccwpck_require__(63896) - , util = __nccwpck_require__(76578) - , errorClasses = __nccwpck_require__(25726) - , stableStringify = __nccwpck_require__(30969); +Object.defineProperty(Reader.prototype, 'buffer', { + get: function () { return (this._buf.slice(this._offset)); } +}); -var validateGenerator = __nccwpck_require__(49585); /** - * Functions below are used inside compiled validations function + * Reads a single byte and advances offset; you can pass in `true` to make this + * a "peek" operation (i.e., get the byte, but don't advance the offset). + * + * @param {Boolean} peek true means don't move offset. + * @return {Number} the next byte, null if not enough data. */ +Reader.prototype.readByte = function (peek) { + if (this._size - this._offset < 1) + return null; -var ucs2length = util.ucs2length; -var equal = __nccwpck_require__(28206); + var b = this._buf[this._offset] & 0xff; -// this error is thrown by async schemas to return validation errors via exception -var ValidationError = errorClasses.Validation; + if (!peek) + this._offset += 1; + + return b; +}; -module.exports = compile; + +Reader.prototype.peek = function () { + return this.readByte(true); +}; /** - * Compiles schema to validation function - * @this Ajv - * @param {Object} schema schema object - * @param {Object} root object with information about the root schema for this schema - * @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution - * @param {String} baseId base ID for IDs in the schema - * @return {Function} validation function + * Reads a (potentially) variable length off the BER buffer. This call is + * not really meant to be called directly, as callers have to manipulate + * the internal buffer afterwards. + * + * As a result of this call, you can call `Reader.length`, until the + * next thing called that does a readLength. + * + * @return {Number} the amount of offset to advance the buffer. + * @throws {InvalidAsn1Error} on bad ASN.1 */ -function compile(schema, root, localRefs, baseId) { - /* jshint validthis: true, evil: true */ - /* eslint no-shadow: 0 */ - var self = this - , opts = this._opts - , refVal = [ undefined ] - , refs = {} - , patterns = [] - , patternsHash = {} - , defaults = [] - , defaultsHash = {} - , customRules = []; - - root = root || { schema: schema, refVal: refVal, refs: refs }; +Reader.prototype.readLength = function (offset) { + if (offset === undefined) + offset = this._offset; - var c = checkCompiling.call(this, schema, root, baseId); - var compilation = this._compilations[c.index]; - if (c.compiling) return (compilation.callValidate = callValidate); + if (offset >= this._size) + return null; - var formats = this._formats; - var RULES = this.RULES; + var lenB = this._buf[offset++] & 0xff; + if (lenB === null) + return null; - try { - var v = localCompile(schema, root, localRefs, baseId); - compilation.validate = v; - var cv = compilation.callValidate; - if (cv) { - cv.schema = v.schema; - cv.errors = null; - cv.refs = v.refs; - cv.refVal = v.refVal; - cv.root = v.root; - cv.$async = v.$async; - if (opts.sourceCode) cv.source = v.source; - } - return v; - } finally { - endCompiling.call(this, schema, root, baseId); - } + if ((lenB & 0x80) === 0x80) { + lenB &= 0x7f; - /* @this {*} - custom context, see passContext option */ - function callValidate() { - /* jshint validthis: true */ - var validate = compilation.validate; - var result = validate.apply(this, arguments); - callValidate.errors = validate.errors; - return result; - } + if (lenB === 0) + throw newInvalidAsn1Error('Indefinite length not supported'); - function localCompile(_schema, _root, localRefs, baseId) { - var isRoot = !_root || (_root && _root.schema == _schema); - if (_root.schema != root.schema) - return compile.call(self, _schema, _root, localRefs, baseId); + if (lenB > 4) + throw newInvalidAsn1Error('encoding too long'); - var $async = _schema.$async === true; + if (this._size - offset < lenB) + return null; - var sourceCode = validateGenerator({ - isTop: true, - schema: _schema, - isRoot: isRoot, - baseId: baseId, - root: _root, - schemaPath: '', - errSchemaPath: '#', - errorPath: '""', - MissingRefError: errorClasses.MissingRef, - RULES: RULES, - validate: validateGenerator, - util: util, - resolve: resolve, - resolveRef: resolveRef, - usePattern: usePattern, - useDefault: useDefault, - useCustomRule: useCustomRule, - opts: opts, - formats: formats, - logger: self.logger, - self: self - }); + this._len = 0; + for (var i = 0; i < lenB; i++) + this._len = (this._len << 8) + (this._buf[offset++] & 0xff); - sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) - + vars(defaults, defaultCode) + vars(customRules, customRuleCode) - + sourceCode; + } else { + // Wasn't a variable length + this._len = lenB; + } - if (opts.processCode) sourceCode = opts.processCode(sourceCode, _schema); - // console.log('\n\n\n *** \n', JSON.stringify(sourceCode)); - var validate; - try { - var makeValidate = new Function( - 'self', - 'RULES', - 'formats', - 'root', - 'refVal', - 'defaults', - 'customRules', - 'equal', - 'ucs2length', - 'ValidationError', - sourceCode - ); + return offset; +}; - validate = makeValidate( - self, - RULES, - formats, - root, - refVal, - defaults, - customRules, - equal, - ucs2length, - ValidationError - ); - refVal[0] = validate; - } catch(e) { - self.logger.error('Error compiling schema, function code:', sourceCode); - throw e; - } +/** + * Parses the next sequence in this BER buffer. + * + * To get the length of the sequence, call `Reader.length`. + * + * @return {Number} the sequence's tag. + */ +Reader.prototype.readSequence = function (tag) { + var seq = this.peek(); + if (seq === null) + return null; + if (tag !== undefined && tag !== seq) + throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + + ': got 0x' + seq.toString(16)); - validate.schema = _schema; - validate.errors = null; - validate.refs = refs; - validate.refVal = refVal; - validate.root = isRoot ? validate : _root; - if ($async) validate.$async = true; - if (opts.sourceCode === true) { - validate.source = { - code: sourceCode, - patterns: patterns, - defaults: defaults - }; - } + var o = this.readLength(this._offset + 1); // stored in `length` + if (o === null) + return null; - return validate; - } + this._offset = o; + return seq; +}; - function resolveRef(baseId, ref, isRoot) { - ref = resolve.url(baseId, ref); - var refIndex = refs[ref]; - var _refVal, refCode; - if (refIndex !== undefined) { - _refVal = refVal[refIndex]; - refCode = 'refVal[' + refIndex + ']'; - return resolvedRef(_refVal, refCode); - } - if (!isRoot && root.refs) { - var rootRefId = root.refs[ref]; - if (rootRefId !== undefined) { - _refVal = root.refVal[rootRefId]; - refCode = addLocalRef(ref, _refVal); - return resolvedRef(_refVal, refCode); - } - } - refCode = addLocalRef(ref); - var v = resolve.call(self, localCompile, root, ref); - if (v === undefined) { - var localSchema = localRefs && localRefs[ref]; - if (localSchema) { - v = resolve.inlineRef(localSchema, opts.inlineRefs) - ? localSchema - : compile.call(self, localSchema, root, localRefs, baseId); - } - } +Reader.prototype.readInt = function () { + return this._readTag(ASN1.Integer); +}; - if (v === undefined) { - removeLocalRef(ref); - } else { - replaceLocalRef(ref, v); - return resolvedRef(v, refCode); - } - } - function addLocalRef(ref, v) { - var refId = refVal.length; - refVal[refId] = v; - refs[ref] = refId; - return 'refVal' + refId; - } +Reader.prototype.readBoolean = function () { + return (this._readTag(ASN1.Boolean) === 0 ? false : true); +}; - function removeLocalRef(ref) { - delete refs[ref]; - } - function replaceLocalRef(ref, v) { - var refId = refs[ref]; - refVal[refId] = v; - } +Reader.prototype.readEnumeration = function () { + return this._readTag(ASN1.Enumeration); +}; - function resolvedRef(refVal, code) { - return typeof refVal == 'object' || typeof refVal == 'boolean' - ? { code: code, schema: refVal, inline: true } - : { code: code, $async: refVal && !!refVal.$async }; - } - function usePattern(regexStr) { - var index = patternsHash[regexStr]; - if (index === undefined) { - index = patternsHash[regexStr] = patterns.length; - patterns[index] = regexStr; - } - return 'pattern' + index; - } +Reader.prototype.readString = function (tag, retbuf) { + if (!tag) + tag = ASN1.OctetString; - function useDefault(value) { - switch (typeof value) { - case 'boolean': - case 'number': - return '' + value; - case 'string': - return util.toQuotedString(value); - case 'object': - if (value === null) return 'null'; - var valueStr = stableStringify(value); - var index = defaultsHash[valueStr]; - if (index === undefined) { - index = defaultsHash[valueStr] = defaults.length; - defaults[index] = value; - } - return 'default' + index; - } - } + var b = this.peek(); + if (b === null) + return null; - function useCustomRule(rule, schema, parentSchema, it) { - if (self._opts.validateSchema !== false) { - var deps = rule.definition.dependencies; - if (deps && !deps.every(function(keyword) { - return Object.prototype.hasOwnProperty.call(parentSchema, keyword); - })) - throw new Error('parent schema must have all required keywords: ' + deps.join(',')); + if (b !== tag) + throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + + ': got 0x' + b.toString(16)); - var validateSchema = rule.definition.validateSchema; - if (validateSchema) { - var valid = validateSchema(schema); - if (!valid) { - var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors); - if (self._opts.validateSchema == 'log') self.logger.error(message); - else throw new Error(message); - } - } - } + var o = this.readLength(this._offset + 1); // stored in `length` - var compile = rule.definition.compile - , inline = rule.definition.inline - , macro = rule.definition.macro; + if (o === null) + return null; - var validate; - if (compile) { - validate = compile.call(self, schema, parentSchema, it); - } else if (macro) { - validate = macro.call(self, schema, parentSchema, it); - if (opts.validateSchema !== false) self.validateSchema(validate, true); - } else if (inline) { - validate = inline.call(self, it, rule.keyword, schema, parentSchema); - } else { - validate = rule.definition.validate; - if (!validate) return; - } + if (this.length > this._size - o) + return null; - if (validate === undefined) - throw new Error('custom keyword "' + rule.keyword + '"failed to compile'); + this._offset = o; - var index = customRules.length; - customRules[index] = validate; + if (this.length === 0) + return retbuf ? Buffer.alloc(0) : ''; - return { - code: 'customRule' + index, - validate: validate - }; - } -} + var str = this._buf.slice(this._offset, this._offset + this.length); + this._offset += this.length; + return retbuf ? str : str.toString('utf8'); +}; -/** - * Checks if the schema is currently compiled - * @this Ajv - * @param {Object} schema schema to compile - * @param {Object} root root object - * @param {String} baseId base schema ID - * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean) - */ -function checkCompiling(schema, root, baseId) { - /* jshint validthis: true */ - var index = compIndex.call(this, schema, root, baseId); - if (index >= 0) return { index: index, compiling: true }; - index = this._compilations.length; - this._compilations[index] = { - schema: schema, - root: root, - baseId: baseId - }; - return { index: index, compiling: false }; -} +Reader.prototype.readOID = function (tag) { + if (!tag) + tag = ASN1.OID; + var b = this.readString(tag, true); + if (b === null) + return null; -/** - * Removes the schema from the currently compiled list - * @this Ajv - * @param {Object} schema schema to compile - * @param {Object} root root object - * @param {String} baseId base schema ID - */ -function endCompiling(schema, root, baseId) { - /* jshint validthis: true */ - var i = compIndex.call(this, schema, root, baseId); - if (i >= 0) this._compilations.splice(i, 1); -} + var values = []; + var value = 0; + for (var i = 0; i < b.length; i++) { + var byte = b[i] & 0xff; -/** - * Index of schema compilation in the currently compiled list - * @this Ajv - * @param {Object} schema schema to compile - * @param {Object} root root object - * @param {String} baseId base schema ID - * @return {Integer} compilation index - */ -function compIndex(schema, root, baseId) { - /* jshint validthis: true */ - for (var i=0; i> 0); + return values.join('.'); +}; -function defaultCode(i) { - return 'var default' + i + ' = defaults[' + i + '];'; -} +Reader.prototype._readTag = function (tag) { + assert.ok(tag !== undefined); -function refValCode(i, refVal) { - return refVal[i] === undefined ? '' : 'var refVal' + i + ' = refVal[' + i + '];'; -} + var b = this.peek(); + if (b === null) + return null; -function customRuleCode(i) { - return 'var customRule' + i + ' = customRules[' + i + '];'; -} + if (b !== tag) + throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + + ': got 0x' + b.toString(16)); + var o = this.readLength(this._offset + 1); // stored in `length` + if (o === null) + return null; -function vars(arr, statement) { - if (!arr.length) return ''; - var code = ''; - for (var i=0; i 4) + throw newInvalidAsn1Error('Integer too long: ' + this.length); + if (this.length > this._size - o) + return null; + this._offset = o; -/***/ }), + var fb = this._buf[this._offset]; + var value = 0; -/***/ 63896: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + for (var i = 0; i < this.length; i++) { + value <<= 8; + value |= (this._buf[this._offset++] & 0xff); + } -"use strict"; + if ((fb & 0x80) === 0x80 && i !== 4) + value -= (1 << (i * 8)); + return value >> 0; +}; -var URI = __nccwpck_require__(70020) - , equal = __nccwpck_require__(28206) - , util = __nccwpck_require__(76578) - , SchemaObject = __nccwpck_require__(37605) - , traverse = __nccwpck_require__(52533); -module.exports = resolve; -resolve.normalizeId = normalizeId; -resolve.fullPath = getFullPath; -resolve.url = resolveUrl; -resolve.ids = resolveIds; -resolve.inlineRef = inlineRef; -resolve.schema = resolveSchema; +// --- Exported API -/** - * [resolve and compile the references ($ref)] - * @this Ajv - * @param {Function} compile reference to schema compilation funciton (localCompile) - * @param {Object} root object with information about the root schema for the current schema - * @param {String} ref reference to resolve - * @return {Object|Function} schema object (if the schema can be inlined) or validation function - */ -function resolve(compile, root, ref) { - /* jshint validthis: true */ - var refVal = this._refs[ref]; - if (typeof refVal == 'string') { - if (this._refs[refVal]) refVal = this._refs[refVal]; - else return resolve.call(this, compile, root, refVal); - } +module.exports = Reader; - refVal = refVal || this._schemas[ref]; - if (refVal instanceof SchemaObject) { - return inlineRef(refVal.schema, this._opts.inlineRefs) - ? refVal.schema - : refVal.validate || this._compile(refVal); - } - var res = resolveSchema.call(this, root, ref); - var schema, v, baseId; - if (res) { - schema = res.schema; - root = res.root; - baseId = res.baseId; - } +/***/ }), - if (schema instanceof SchemaObject) { - v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId); - } else if (schema !== undefined) { - v = inlineRef(schema, this._opts.inlineRefs) - ? schema - : compile.call(this, schema, root, undefined, baseId); - } +/***/ 42473: +/***/ ((module) => { - return v; -} +// Copyright 2011 Mark Cavage All rights reserved. -/** - * Resolve schema, its root and baseId - * @this Ajv - * @param {Object} root root object with properties schema, refVal, refs - * @param {String} ref reference to resolve - * @return {Object} object with properties schema, root, baseId - */ -function resolveSchema(root, ref) { - /* jshint validthis: true */ - var p = URI.parse(ref) - , refPath = _getFullPath(p) - , baseId = getFullPath(this._getId(root.schema)); - if (Object.keys(root.schema).length === 0 || refPath !== baseId) { - var id = normalizeId(refPath); - var refVal = this._refs[id]; - if (typeof refVal == 'string') { - return resolveRecursive.call(this, root, refVal, p); - } else if (refVal instanceof SchemaObject) { - if (!refVal.validate) this._compile(refVal); - root = refVal; - } else { - refVal = this._schemas[id]; - if (refVal instanceof SchemaObject) { - if (!refVal.validate) this._compile(refVal); - if (id == normalizeId(ref)) - return { schema: refVal, root: root, baseId: baseId }; - root = refVal; - } else { - return; - } - } - if (!root.schema) return; - baseId = getFullPath(this._getId(root.schema)); - } - return getJsonPointer.call(this, p, baseId, root.schema, root); -} +module.exports = { + EOC: 0, + Boolean: 1, + Integer: 2, + BitString: 3, + OctetString: 4, + Null: 5, + OID: 6, + ObjectDescriptor: 7, + External: 8, + Real: 9, // float + Enumeration: 10, + PDV: 11, + Utf8String: 12, + RelativeOID: 13, + Sequence: 16, + Set: 17, + NumericString: 18, + PrintableString: 19, + T61String: 20, + VideotexString: 21, + IA5String: 22, + UTCTime: 23, + GeneralizedTime: 24, + GraphicString: 25, + VisibleString: 26, + GeneralString: 28, + UniversalString: 29, + CharacterString: 30, + BMPString: 31, + Constructor: 32, + Context: 128 +}; -/* @this Ajv */ -function resolveRecursive(root, ref, parsedRef) { - /* jshint validthis: true */ - var res = resolveSchema.call(this, root, ref); - if (res) { - var schema = res.schema; - var baseId = res.baseId; - root = res.root; - var id = this._getId(schema); - if (id) baseId = resolveUrl(baseId, id); - return getJsonPointer.call(this, parsedRef, baseId, schema, root); - } -} +/***/ }), +/***/ 43200: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var PREVENT_SCOPE_CHANGE = util.toHash(['properties', 'patternProperties', 'enum', 'dependencies', 'definitions']); -/* @this Ajv */ -function getJsonPointer(parsedRef, baseId, schema, root) { - /* jshint validthis: true */ - parsedRef.fragment = parsedRef.fragment || ''; - if (parsedRef.fragment.slice(0,1) != '/') return; - var parts = parsedRef.fragment.split('/'); +// Copyright 2011 Mark Cavage All rights reserved. - for (var i = 1; i < parts.length; i++) { - var part = parts[i]; - if (part) { - part = util.unescapeFragment(part); - schema = schema[part]; - if (schema === undefined) break; - var id; - if (!PREVENT_SCOPE_CHANGE[part]) { - id = this._getId(schema); - if (id) baseId = resolveUrl(baseId, id); - if (schema.$ref) { - var $ref = resolveUrl(baseId, schema.$ref); - var res = resolveSchema.call(this, root, $ref); - if (res) { - schema = res.schema; - root = res.root; - baseId = res.baseId; - } - } - } - } - } - if (schema !== undefined && schema !== root.schema) - return { schema: schema, root: root, baseId: baseId }; -} +var assert = __nccwpck_require__(39491); +var Buffer = (__nccwpck_require__(15118).Buffer); +var ASN1 = __nccwpck_require__(42473); +var errors = __nccwpck_require__(99348); -var SIMPLE_INLINED = util.toHash([ - 'type', 'format', 'pattern', - 'maxLength', 'minLength', - 'maxProperties', 'minProperties', - 'maxItems', 'minItems', - 'maximum', 'minimum', - 'uniqueItems', 'multipleOf', - 'required', 'enum' -]); -function inlineRef(schema, limit) { - if (limit === false) return false; - if (limit === undefined || limit === true) return checkNoRef(schema); - else if (limit) return countKeys(schema) <= limit; -} +// --- Globals +var newInvalidAsn1Error = errors.newInvalidAsn1Error; -function checkNoRef(schema) { - var item; - if (Array.isArray(schema)) { - for (var i=0; i { + var sz = 4; -"use strict"; + while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) && + (sz > 1)) { + sz--; + i <<= 8; + } + if (sz > 4) + throw newInvalidAsn1Error('BER ints cannot be > 0xffffffff'); -var ruleModules = __nccwpck_require__(85810) - , toHash = (__nccwpck_require__(76578).toHash); + this._ensure(2 + sz); + this._buf[this._offset++] = tag; + this._buf[this._offset++] = sz; -module.exports = function rules() { - var RULES = [ - { type: 'number', - rules: [ { 'maximum': ['exclusiveMaximum'] }, - { 'minimum': ['exclusiveMinimum'] }, 'multipleOf', 'format'] }, - { type: 'string', - rules: [ 'maxLength', 'minLength', 'pattern', 'format' ] }, - { type: 'array', - rules: [ 'maxItems', 'minItems', 'items', 'contains', 'uniqueItems' ] }, - { type: 'object', - rules: [ 'maxProperties', 'minProperties', 'required', 'dependencies', 'propertyNames', - { 'properties': ['additionalProperties', 'patternProperties'] } ] }, - { rules: [ '$ref', 'const', 'enum', 'not', 'anyOf', 'oneOf', 'allOf', 'if' ] } - ]; + while (sz-- > 0) { + this._buf[this._offset++] = ((i & 0xff000000) >>> 24); + i <<= 8; + } - var ALL = [ 'type', '$comment' ]; - var KEYWORDS = [ - '$schema', '$id', 'id', '$data', '$async', 'title', - 'description', 'default', 'definitions', - 'examples', 'readOnly', 'writeOnly', - 'contentMediaType', 'contentEncoding', - 'additionalItems', 'then', 'else' - ]; - var TYPES = [ 'number', 'integer', 'string', 'array', 'object', 'boolean', 'null' ]; - RULES.all = toHash(ALL); - RULES.types = toHash(TYPES); +}; - RULES.forEach(function (group) { - group.rules = group.rules.map(function (keyword) { - var implKeywords; - if (typeof keyword == 'object') { - var key = Object.keys(keyword)[0]; - implKeywords = keyword[key]; - keyword = key; - implKeywords.forEach(function (k) { - ALL.push(k); - RULES.all[k] = true; - }); - } - ALL.push(keyword); - var rule = RULES.all[keyword] = { - keyword: keyword, - code: ruleModules[keyword], - implements: implKeywords - }; - return rule; - }); - RULES.all.$comment = { - keyword: '$comment', - code: ruleModules.$comment - }; +Writer.prototype.writeNull = function () { + this.writeByte(ASN1.Null); + this.writeByte(0x00); +}; - if (group.type) RULES.types[group.type] = group; - }); - RULES.keywords = toHash(ALL.concat(KEYWORDS)); - RULES.custom = {}; +Writer.prototype.writeEnumeration = function (i, tag) { + if (typeof (i) !== 'number') + throw new TypeError('argument must be a Number'); + if (typeof (tag) !== 'number') + tag = ASN1.Enumeration; - return RULES; + return this.writeInt(i, tag); }; -/***/ }), +Writer.prototype.writeBoolean = function (b, tag) { + if (typeof (b) !== 'boolean') + throw new TypeError('argument must be a Boolean'); + if (typeof (tag) !== 'number') + tag = ASN1.Boolean; -/***/ 37605: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this._ensure(3); + this._buf[this._offset++] = tag; + this._buf[this._offset++] = 0x01; + this._buf[this._offset++] = b ? 0xff : 0x00; +}; -"use strict"; +Writer.prototype.writeString = function (s, tag) { + if (typeof (s) !== 'string') + throw new TypeError('argument must be a string (was: ' + typeof (s) + ')'); + if (typeof (tag) !== 'number') + tag = ASN1.OctetString; -var util = __nccwpck_require__(76578); + var len = Buffer.byteLength(s); + this.writeByte(tag); + this.writeLength(len); + if (len) { + this._ensure(len); + this._buf.write(s, this._offset); + this._offset += len; + } +}; -module.exports = SchemaObject; -function SchemaObject(obj) { - util.copy(obj, this); -} +Writer.prototype.writeBuffer = function (buf, tag) { + if (typeof (tag) !== 'number') + throw new TypeError('tag must be a number'); + if (!Buffer.isBuffer(buf)) + throw new TypeError('argument must be a buffer'); + this.writeByte(tag); + this.writeLength(buf.length); + this._ensure(buf.length); + buf.copy(this._buf, this._offset, 0, buf.length); + this._offset += buf.length; +}; -/***/ }), -/***/ 64580: -/***/ ((module) => { +Writer.prototype.writeStringArray = function (strings) { + if ((!strings instanceof Array)) + throw new TypeError('argument must be an Array[String]'); -"use strict"; + var self = this; + strings.forEach(function (s) { + self.writeString(s); + }); +}; +// This is really to solve DER cases, but whatever for now +Writer.prototype.writeOID = function (s, tag) { + if (typeof (s) !== 'string') + throw new TypeError('argument must be a string'); + if (typeof (tag) !== 'number') + tag = ASN1.OID; -// https://mathiasbynens.be/notes/javascript-encoding -// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode -module.exports = function ucs2length(str) { - var length = 0 - , len = str.length - , pos = 0 - , value; - while (pos < len) { - length++; - value = str.charCodeAt(pos++); - if (value >= 0xD800 && value <= 0xDBFF && pos < len) { - // high surrogate, and there is a next character - value = str.charCodeAt(pos); - if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate + if (!/^([0-9]+\.){3,}[0-9]+$/.test(s)) + throw new Error('argument is not a valid OID string'); + + function encodeOctet(bytes, octet) { + if (octet < 128) { + bytes.push(octet); + } else if (octet < 16384) { + bytes.push((octet >>> 7) | 0x80); + bytes.push(octet & 0x7F); + } else if (octet < 2097152) { + bytes.push((octet >>> 14) | 0x80); + bytes.push(((octet >>> 7) | 0x80) & 0xFF); + bytes.push(octet & 0x7F); + } else if (octet < 268435456) { + bytes.push((octet >>> 21) | 0x80); + bytes.push(((octet >>> 14) | 0x80) & 0xFF); + bytes.push(((octet >>> 7) | 0x80) & 0xFF); + bytes.push(octet & 0x7F); + } else { + bytes.push(((octet >>> 28) | 0x80) & 0xFF); + bytes.push(((octet >>> 21) | 0x80) & 0xFF); + bytes.push(((octet >>> 14) | 0x80) & 0xFF); + bytes.push(((octet >>> 7) | 0x80) & 0xFF); + bytes.push(octet & 0x7F); } } - return length; -}; - -/***/ }), + var tmp = s.split('.'); + var bytes = []; + bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10)); + tmp.slice(2).forEach(function (b) { + encodeOctet(bytes, parseInt(b, 10)); + }); -/***/ 76578: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var self = this; + this._ensure(2 + bytes.length); + this.writeByte(tag); + this.writeLength(bytes.length); + bytes.forEach(function (b) { + self.writeByte(b); + }); +}; -"use strict"; +Writer.prototype.writeLength = function (len) { + if (typeof (len) !== 'number') + throw new TypeError('argument must be a Number'); + this._ensure(4); -module.exports = { - copy: copy, - checkDataType: checkDataType, - checkDataTypes: checkDataTypes, - coerceToTypes: coerceToTypes, - toHash: toHash, - getProperty: getProperty, - escapeQuotes: escapeQuotes, - equal: __nccwpck_require__(28206), - ucs2length: __nccwpck_require__(64580), - varOccurences: varOccurences, - varReplace: varReplace, - schemaHasRules: schemaHasRules, - schemaHasRulesExcept: schemaHasRulesExcept, - schemaUnknownRules: schemaUnknownRules, - toQuotedString: toQuotedString, - getPathExpr: getPathExpr, - getPath: getPath, - getData: getData, - unescapeFragment: unescapeFragment, - unescapeJsonPointer: unescapeJsonPointer, - escapeFragment: escapeFragment, - escapeJsonPointer: escapeJsonPointer + if (len <= 0x7f) { + this._buf[this._offset++] = len; + } else if (len <= 0xff) { + this._buf[this._offset++] = 0x81; + this._buf[this._offset++] = len; + } else if (len <= 0xffff) { + this._buf[this._offset++] = 0x82; + this._buf[this._offset++] = len >> 8; + this._buf[this._offset++] = len; + } else if (len <= 0xffffff) { + this._buf[this._offset++] = 0x83; + this._buf[this._offset++] = len >> 16; + this._buf[this._offset++] = len >> 8; + this._buf[this._offset++] = len; + } else { + throw newInvalidAsn1Error('Length too long (> 4 bytes)'); + } }; +Writer.prototype.startSequence = function (tag) { + if (typeof (tag) !== 'number') + tag = ASN1.Sequence | ASN1.Constructor; -function copy(o, to) { - to = to || {}; - for (var key in o) to[key] = o[key]; - return to; -} + this.writeByte(tag); + this._seq.push(this._offset); + this._ensure(3); + this._offset += 3; +}; -function checkDataType(dataType, data, strictNumbers, negate) { - var EQUAL = negate ? ' !== ' : ' === ' - , AND = negate ? ' || ' : ' && ' - , OK = negate ? '!' : '' - , NOT = negate ? '' : '!'; - switch (dataType) { - case 'null': return data + EQUAL + 'null'; - case 'array': return OK + 'Array.isArray(' + data + ')'; - case 'object': return '(' + OK + data + AND + - 'typeof ' + data + EQUAL + '"object"' + AND + - NOT + 'Array.isArray(' + data + '))'; - case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND + - NOT + '(' + data + ' % 1)' + - AND + data + EQUAL + data + - (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')'; - case 'number': return '(typeof ' + data + EQUAL + '"' + dataType + '"' + - (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')'; - default: return 'typeof ' + data + EQUAL + '"' + dataType + '"'; +Writer.prototype.endSequence = function () { + var seq = this._seq.pop(); + var start = seq + 3; + var len = this._offset - start; + + if (len <= 0x7f) { + this._shift(start, len, -2); + this._buf[seq] = len; + } else if (len <= 0xff) { + this._shift(start, len, -1); + this._buf[seq] = 0x81; + this._buf[seq + 1] = len; + } else if (len <= 0xffff) { + this._buf[seq] = 0x82; + this._buf[seq + 1] = len >> 8; + this._buf[seq + 2] = len; + } else if (len <= 0xffffff) { + this._shift(start, len, 1); + this._buf[seq] = 0x83; + this._buf[seq + 1] = len >> 16; + this._buf[seq + 2] = len >> 8; + this._buf[seq + 3] = len; + } else { + throw newInvalidAsn1Error('Sequence too long'); } -} +}; -function checkDataTypes(dataTypes, data, strictNumbers) { - switch (dataTypes.length) { - case 1: return checkDataType(dataTypes[0], data, strictNumbers, true); - default: - var code = ''; - var types = toHash(dataTypes); - if (types.array && types.object) { - code = types.null ? '(': '(!' + data + ' || '; - code += 'typeof ' + data + ' !== "object")'; - delete types.null; - delete types.array; - delete types.object; - } - if (types.number) delete types.integer; - for (var t in types) - code += (code ? ' && ' : '' ) + checkDataType(t, data, strictNumbers, true); +Writer.prototype._shift = function (start, len, shift) { + assert.ok(start !== undefined); + assert.ok(len !== undefined); + assert.ok(shift); - return code; - } -} + this._buf.copy(this._buf, start + shift, start, start + len); + this._offset += shift; +}; +Writer.prototype._ensure = function (len) { + assert.ok(len); -var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]); -function coerceToTypes(optionCoerceTypes, dataTypes) { - if (Array.isArray(dataTypes)) { - var types = []; - for (var i=0; i { -function varOccurences(str, dataVar) { - dataVar += '[^0-9]'; - var matches = str.match(new RegExp(dataVar, 'g')); - return matches ? matches.length : 0; -} +// Copyright 2011 Mark Cavage All rights reserved. +// If you have no idea what ASN.1 or BER is, see this: +// ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc -function varReplace(str, dataVar, expr) { - dataVar += '([^0-9])'; - expr = expr.replace(/\$/g, '$$$$'); - return str.replace(new RegExp(dataVar, 'g'), expr + '$1'); -} +var Ber = __nccwpck_require__(194); -function schemaHasRules(schema, rules) { - if (typeof schema == 'boolean') return !schema; - for (var key in schema) if (rules[key]) return true; -} +// --- Exported API -function schemaHasRulesExcept(schema, rules, exceptKeyword) { - if (typeof schema == 'boolean') return !schema && exceptKeyword != 'not'; - for (var key in schema) if (key != exceptKeyword && rules[key]) return true; -} +module.exports = { + Ber: Ber, -function schemaUnknownRules(schema, rules) { - if (typeof schema == 'boolean') return; - for (var key in schema) if (!rules[key]) return key; -} + BerReader: Ber.Reader, + BerWriter: Ber.Writer -function toQuotedString(str) { - return '\'' + escapeQuotes(str) + '\''; -} +}; -function getPathExpr(currentPath, expr, jsonPointers, isNumber) { - var path = jsonPointers // false by default - ? '\'/\' + ' + expr + (isNumber ? '' : '.replace(/~/g, \'~0\').replace(/\\//g, \'~1\')') - : (isNumber ? '\'[\' + ' + expr + ' + \']\'' : '\'[\\\'\' + ' + expr + ' + \'\\\']\''); - return joinPaths(currentPath, path); -} +/***/ }), +/***/ 66631: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function getPath(currentPath, prop, jsonPointers) { - var path = jsonPointers // false by default - ? toQuotedString('/' + escapeJsonPointer(prop)) - : toQuotedString(getProperty(prop)); - return joinPaths(currentPath, path); -} +// Copyright (c) 2012, Mark Cavage. All rights reserved. +// Copyright 2015 Joyent, Inc. +var assert = __nccwpck_require__(39491); +var Stream = (__nccwpck_require__(12781).Stream); +var util = __nccwpck_require__(73837); -var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; -var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; -function getData($data, lvl, paths) { - var up, jsonPointer, data, matches; - if ($data === '') return 'rootData'; - if ($data[0] == '/') { - if (!JSON_POINTER.test($data)) throw new Error('Invalid JSON-pointer: ' + $data); - jsonPointer = $data; - data = 'rootData'; - } else { - matches = $data.match(RELATIVE_JSON_POINTER); - if (!matches) throw new Error('Invalid JSON-pointer: ' + $data); - up = +matches[1]; - jsonPointer = matches[2]; - if (jsonPointer == '#') { - if (up >= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl); - return paths[lvl - up]; - } - if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl); - data = 'data' + ((lvl - up) || ''); - if (!jsonPointer) return data; - } +///--- Globals - var expr = data; - var segments = jsonPointer.split('/'); - for (var i=0; i { + /* optional checks */ + keys.forEach(function (k) { + var name = 'optional' + _capitalize(k); + if (ndebug) { + out[name] = noop; + return; + } + var type = types[k]; + out[name] = function (arg, msg) { + if (arg === undefined || arg === null) { + return; + } + if (!type.check(arg)) { + _toss(msg, k, type.operator, arg, type.actual); + } + }; + }); -"use strict"; + /* arrayOf checks */ + keys.forEach(function (k) { + var name = 'arrayOf' + _capitalize(k); + if (ndebug) { + out[name] = noop; + return; + } + var type = types[k]; + var expected = '[' + k + ']'; + out[name] = function (arg, msg) { + if (!Array.isArray(arg)) { + _toss(msg, expected, type.operator, arg, type.actual); + } + var i; + for (i = 0; i < arg.length; i++) { + if (!type.check(arg[i])) { + _toss(msg, expected, type.operator, arg, type.actual); + } + } + }; + }); + /* optionalArrayOf checks */ + keys.forEach(function (k) { + var name = 'optionalArrayOf' + _capitalize(k); + if (ndebug) { + out[name] = noop; + return; + } + var type = types[k]; + var expected = '[' + k + ']'; + out[name] = function (arg, msg) { + if (arg === undefined || arg === null) { + return; + } + if (!Array.isArray(arg)) { + _toss(msg, expected, type.operator, arg, type.actual); + } + var i; + for (i = 0; i < arg.length; i++) { + if (!type.check(arg[i])) { + _toss(msg, expected, type.operator, arg, type.actual); + } + } + }; + }); -var KEYWORDS = [ - 'multipleOf', - 'maximum', - 'exclusiveMaximum', - 'minimum', - 'exclusiveMinimum', - 'maxLength', - 'minLength', - 'pattern', - 'additionalItems', - 'maxItems', - 'minItems', - 'uniqueItems', - 'maxProperties', - 'minProperties', - 'required', - 'additionalProperties', - 'enum', - 'format', - 'const' -]; + /* re-export built-in assertions */ + Object.keys(assert).forEach(function (k) { + if (k === 'AssertionError') { + out[k] = assert[k]; + return; + } + if (ndebug) { + out[k] = noop; + return; + } + out[k] = assert[k]; + }); -module.exports = function (metaSchema, keywordsJsonPointers) { - for (var i=0; i { +/***/ 41299: +/***/ (function(__unused_webpack_module, exports) { -"use strict"; +!function(e,t){ true?t(exports):0}(this,(function(e){"use strict";class t extends Error{constructor(e){super(null!=e?`Timed out after waiting for ${e} ms`:"Timed out"),Object.setPrototypeOf(this,t.prototype)}}const o=(e,t)=>new Promise(((o,n)=>{try{e.schedule(o,t)}catch(e){n(e)}})),n={schedule:(e,t)=>{let o;const n=e=>{null!=e&&clearTimeout(e),o=void 0};return o=setTimeout((()=>{n(o),e()}),t),{cancel:()=>n(o)}}},i=Number.POSITIVE_INFINITY,r=(e,r,l)=>{var u,s;const c=null!==(u="number"==typeof r?r:null==r?void 0:r.timeout)&&void 0!==u?u:5e3,d=null!==(s="number"==typeof r?l:null==r?void 0:r.intervalBetweenAttempts)&&void 0!==s?s:50;let a=!1;const f=()=>new Promise(((t,i)=>{const r=()=>{a||new Promise(((t,o)=>{try{t(e())}catch(e){o(e)}})).then((e=>{e?t(e):o(n,d).then(r).catch(i)})).catch(i)};r()})),T=c!==i?()=>o(n,c).then((()=>{throw a=!0,new t(c)})):void 0;return null!=T?Promise.race([f(),T()]):f()};e.DEFAULT_INTERVAL_BETWEEN_ATTEMPTS_IN_MS=50,e.DEFAULT_TIMEOUT_IN_MS=5e3,e.TimeoutError=t,e.WAIT_FOREVER=i,e.default=r,e.waitUntil=r,Object.defineProperty(e,"__esModule",{value:!0})}));//# sourceMappingURL=index.js.map -var metaSchema = __nccwpck_require__(6680); +/***/ }), -module.exports = { - $id: 'https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js', - definitions: { - simpleTypes: metaSchema.definitions.simpleTypes - }, - type: 'object', - dependencies: { - schema: ['validate'], - $data: ['validate'], - statements: ['inline'], - valid: {not: {required: ['macro']}} - }, - properties: { - type: metaSchema.properties.type, - schema: {type: 'boolean'}, - statements: {type: 'boolean'}, - dependencies: { - type: 'array', - items: {type: 'string'} - }, - metaSchema: {type: 'object'}, - modifying: {type: 'boolean'}, - valid: {type: 'boolean'}, - $data: {type: 'boolean'}, - async: {type: 'boolean'}, - errors: { - anyOf: [ - {type: 'boolean'}, - {const: 'full'} - ] - } - } +/***/ 14812: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +module.exports = +{ + parallel : __nccwpck_require__(8210), + serial : __nccwpck_require__(50445), + serialOrdered : __nccwpck_require__(3578) }; /***/ }), -/***/ 7404: +/***/ 1700: /***/ ((module) => { -"use strict"; +// API +module.exports = abort; -module.exports = function generate__limit(it, $keyword, $ruleType) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $errorKeyword; - var $data = 'data' + ($dataLvl || ''); - var $isData = it.opts.$data && $schema && $schema.$data, - $schemaValue; - if ($isData) { - out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; - $schemaValue = 'schema' + $lvl; - } else { - $schemaValue = $schema; - } - var $isMax = $keyword == 'maximum', - $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum', - $schemaExcl = it.schema[$exclusiveKeyword], - $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data, - $op = $isMax ? '<' : '>', - $notOp = $isMax ? '>' : '<', - $errorKeyword = undefined; - if (!($isData || typeof $schema == 'number' || $schema === undefined)) { - throw new Error($keyword + ' must be number'); - } - if (!($isDataExcl || $schemaExcl === undefined || typeof $schemaExcl == 'number' || typeof $schemaExcl == 'boolean')) { - throw new Error($exclusiveKeyword + ' must be number or boolean'); - } - if ($isDataExcl) { - var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), - $exclusive = 'exclusive' + $lvl, - $exclType = 'exclType' + $lvl, - $exclIsNumber = 'exclIsNumber' + $lvl, - $opExpr = 'op' + $lvl, - $opStr = '\' + ' + $opExpr + ' + \''; - out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; '; - $schemaValueExcl = 'schemaExcl' + $lvl; - out += ' var ' + ($exclusive) + '; var ' + ($exclType) + ' = typeof ' + ($schemaValueExcl) + '; if (' + ($exclType) + ' != \'boolean\' && ' + ($exclType) + ' != \'undefined\' && ' + ($exclType) + ' != \'number\') { '; - var $errorKeyword = $exclusiveKeyword; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; - if (it.opts.messages !== false) { - out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += ' } else if ( '; - if ($isData) { - out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; - } - out += ' ' + ($exclType) + ' == \'number\' ? ( (' + ($exclusive) + ' = ' + ($schemaValue) + ' === undefined || ' + ($schemaValueExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ') ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValueExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) : ( (' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\'; '; - if ($schema === undefined) { - $errorKeyword = $exclusiveKeyword; - $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; - $schemaValue = $schemaValueExcl; - $isData = $isDataExcl; - } - } else { - var $exclIsNumber = typeof $schemaExcl == 'number', - $opStr = $op; - if ($exclIsNumber && $isData) { - var $opExpr = '\'' + $opStr + '\''; - out += ' if ( '; - if ($isData) { - out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; - } - out += ' ( ' + ($schemaValue) + ' === undefined || ' + ($schemaExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ' ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { '; - } else { - if ($exclIsNumber && $schema === undefined) { - $exclusive = true; - $errorKeyword = $exclusiveKeyword; - $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; - $schemaValue = $schemaExcl; - $notOp += '='; - } else { - if ($exclIsNumber) $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema); - if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) { - $exclusive = true; - $errorKeyword = $exclusiveKeyword; - $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; - $notOp += '='; - } else { - $exclusive = false; - $opStr += '='; - } - } - var $opExpr = '\'' + $opStr + '\''; - out += ' if ( '; - if ($isData) { - out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; - } - out += ' ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') { '; - } - } - $errorKeyword = $errorKeyword || $keyword; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should be ' + ($opStr) + ' '; - if ($isData) { - out += '\' + ' + ($schemaValue); - } else { - out += '' + ($schemaValue) + '\''; - } - } - if (it.opts.verbose) { - out += ' , schema: '; - if ($isData) { - out += 'validate.schema' + ($schemaPath); - } else { - out += '' + ($schema); - } - out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += ' } '; - if ($breakOnError) { - out += ' else { '; +/** + * Aborts leftover active jobs + * + * @param {object} state - current state object + */ +function abort(state) +{ + Object.keys(state.jobs).forEach(clean.bind(state)); + + // reset leftover jobs + state.jobs = {}; +} + +/** + * Cleans up leftover job by invoking abort function for the provided job id + * + * @this state + * @param {string|number} key - job id to abort + */ +function clean(key) +{ + if (typeof this.jobs[key] == 'function') + { + this.jobs[key](); } - return out; } /***/ }), -/***/ 64683: -/***/ ((module) => { +/***/ 72794: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +var defer = __nccwpck_require__(15295); -module.exports = function generate__limitItems(it, $keyword, $ruleType) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $errorKeyword; - var $data = 'data' + ($dataLvl || ''); - var $isData = it.opts.$data && $schema && $schema.$data, - $schemaValue; - if ($isData) { - out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; - $schemaValue = 'schema' + $lvl; - } else { - $schemaValue = $schema; - } - if (!($isData || typeof $schema == 'number')) { - throw new Error($keyword + ' must be number'); - } - var $op = $keyword == 'maxItems' ? '>' : '<'; - out += 'if ( '; - if ($isData) { - out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; - } - out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { '; - var $errorKeyword = $keyword; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should NOT have '; - if ($keyword == 'maxItems') { - out += 'more'; - } else { - out += 'fewer'; - } - out += ' than '; - if ($isData) { - out += '\' + ' + ($schemaValue) + ' + \''; - } else { - out += '' + ($schema); - } - out += ' items\' '; - } - if (it.opts.verbose) { - out += ' , schema: '; - if ($isData) { - out += 'validate.schema' + ($schemaPath); - } else { - out += '' + ($schema); - } - out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; +// API +module.exports = async; + +/** + * Runs provided callback asynchronously + * even if callback itself is not + * + * @param {function} callback - callback to invoke + * @returns {function} - augmented callback + */ +function async(callback) +{ + var isAsync = false; + + // check if async happened + defer(function() { isAsync = true; }); + + return function async_callback(err, result) + { + if (isAsync) + { + callback(err, result); } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; + else + { + defer(function nextTick_callback() + { + callback(err, result); + }); } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += '} '; - if ($breakOnError) { - out += ' else { '; - } - return out; + }; } /***/ }), -/***/ 52114: +/***/ 15295: /***/ ((module) => { -"use strict"; +module.exports = defer; -module.exports = function generate__limitLength(it, $keyword, $ruleType) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $errorKeyword; - var $data = 'data' + ($dataLvl || ''); - var $isData = it.opts.$data && $schema && $schema.$data, - $schemaValue; - if ($isData) { - out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; - $schemaValue = 'schema' + $lvl; - } else { - $schemaValue = $schema; - } - if (!($isData || typeof $schema == 'number')) { - throw new Error($keyword + ' must be number'); - } - var $op = $keyword == 'maxLength' ? '>' : '<'; - out += 'if ( '; - if ($isData) { - out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; - } - if (it.opts.unicode === false) { - out += ' ' + ($data) + '.length '; - } else { - out += ' ucs2length(' + ($data) + ') '; - } - out += ' ' + ($op) + ' ' + ($schemaValue) + ') { '; - var $errorKeyword = $keyword; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should NOT be '; - if ($keyword == 'maxLength') { - out += 'longer'; - } else { - out += 'shorter'; - } - out += ' than '; - if ($isData) { - out += '\' + ' + ($schemaValue) + ' + \''; - } else { - out += '' + ($schema); - } - out += ' characters\' '; - } - if (it.opts.verbose) { - out += ' , schema: '; - if ($isData) { - out += 'validate.schema' + ($schemaPath); - } else { - out += '' + ($schema); - } - out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; +/** + * Runs provided function on next iteration of the event loop + * + * @param {function} fn - function to run + */ +function defer(fn) +{ + var nextTick = typeof setImmediate == 'function' + ? setImmediate + : ( + typeof process == 'object' && typeof process.nextTick == 'function' + ? process.nextTick + : null + ); + + if (nextTick) + { + nextTick(fn); } - out += '} '; - if ($breakOnError) { - out += ' else { '; + else + { + setTimeout(fn, 0); } - return out; } /***/ }), -/***/ 71142: -/***/ ((module) => { +/***/ 9023: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +var async = __nccwpck_require__(72794) + , abort = __nccwpck_require__(1700) + ; -module.exports = function generate__limitProperties(it, $keyword, $ruleType) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $errorKeyword; - var $data = 'data' + ($dataLvl || ''); - var $isData = it.opts.$data && $schema && $schema.$data, - $schemaValue; - if ($isData) { - out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; - $schemaValue = 'schema' + $lvl; - } else { - $schemaValue = $schema; - } - if (!($isData || typeof $schema == 'number')) { - throw new Error($keyword + ' must be number'); - } - var $op = $keyword == 'maxProperties' ? '>' : '<'; - out += 'if ( '; - if ($isData) { - out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; - } - out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { '; - var $errorKeyword = $keyword; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should NOT have '; - if ($keyword == 'maxProperties') { - out += 'more'; - } else { - out += 'fewer'; - } - out += ' than '; - if ($isData) { - out += '\' + ' + ($schemaValue) + ' + \''; - } else { - out += '' + ($schema); - } - out += ' properties\' '; +// API +module.exports = iterate; + +/** + * Iterates over each job object + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {object} state - current job status + * @param {function} callback - invoked when all elements processed + */ +function iterate(list, iterator, state, callback) +{ + // store current index + var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; + + state.jobs[key] = runJob(iterator, key, list[key], function(error, output) + { + // don't repeat yourself + // skip secondary callbacks + if (!(key in state.jobs)) + { + return; } - if (it.opts.verbose) { - out += ' , schema: '; - if ($isData) { - out += 'validate.schema' + ($schemaPath); - } else { - out += '' + ($schema); - } - out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + + // clean up jobs + delete state.jobs[key]; + + if (error) + { + // don't process rest of the results + // stop still active jobs + // and reset the list + abort(state); } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; + else + { + state.results[key] = output; } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + + // return salvaged results + callback(error, state.results); + }); +} + +/** + * Runs iterator over provided job element + * + * @param {function} iterator - iterator to invoke + * @param {string|number} key - key/index of the element in the list of jobs + * @param {mixed} item - job description + * @param {function} callback - invoked after iterator is done with the job + * @returns {function|mixed} - job abort function or something else + */ +function runJob(iterator, key, item, callback) +{ + var aborter; + + // allow shortcut if iterator expects only two arguments + if (iterator.length == 2) + { + aborter = iterator(item, async(callback)); } - out += '} '; - if ($breakOnError) { - out += ' else { '; + // otherwise go with full three arguments + else + { + aborter = iterator(item, key, async(callback)); } - return out; + + return aborter; } /***/ }), -/***/ 89443: +/***/ 42474: /***/ ((module) => { -"use strict"; +// API +module.exports = state; -module.exports = function generate_allOf(it, $keyword, $ruleType) { - var out = ' '; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $it = it.util.copy(it); - var $closingBraces = ''; - $it.level++; - var $nextValid = 'valid' + $it.level; - var $currentBaseId = $it.baseId, - $allSchemasEmpty = true; - var arr1 = $schema; - if (arr1) { - var $sch, $i = -1, - l1 = arr1.length - 1; - while ($i < l1) { - $sch = arr1[$i += 1]; - if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { - $allSchemasEmpty = false; - $it.schema = $sch; - $it.schemaPath = $schemaPath + '[' + $i + ']'; - $it.errSchemaPath = $errSchemaPath + '/' + $i; - out += ' ' + (it.validate($it)) + ' '; - $it.baseId = $currentBaseId; - if ($breakOnError) { - out += ' if (' + ($nextValid) + ') { '; - $closingBraces += '}'; - } - } - } - } - if ($breakOnError) { - if ($allSchemasEmpty) { - out += ' if (true) { '; - } else { - out += ' ' + ($closingBraces.slice(0, -1)) + ' '; +/** + * Creates initial state object + * for iteration over list + * + * @param {array|object} list - list to iterate over + * @param {function|null} sortMethod - function to use for keys sort, + * or `null` to keep them as is + * @returns {object} - initial state object + */ +function state(list, sortMethod) +{ + var isNamedList = !Array.isArray(list) + , initState = + { + index : 0, + keyedList: isNamedList || sortMethod ? Object.keys(list) : null, + jobs : {}, + results : isNamedList ? {} : [], + size : isNamedList ? Object.keys(list).length : list.length } + ; + + if (sortMethod) + { + // sort array keys based on it's values + // sort object's keys just on own merit + initState.keyedList.sort(isNamedList ? sortMethod : function(a, b) + { + return sortMethod(list[a], list[b]); + }); } - return out; + + return initState; } /***/ }), -/***/ 63093: -/***/ ((module) => { +/***/ 37942: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +var abort = __nccwpck_require__(1700) + , async = __nccwpck_require__(72794) + ; -module.exports = function generate_anyOf(it, $keyword, $ruleType) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $valid = 'valid' + $lvl; - var $errs = 'errs__' + $lvl; - var $it = it.util.copy(it); - var $closingBraces = ''; - $it.level++; - var $nextValid = 'valid' + $it.level; - var $noEmptySchema = $schema.every(function($sch) { - return (it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)); - }); - if ($noEmptySchema) { - var $currentBaseId = $it.baseId; - out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false; '; - var $wasComposite = it.compositeRule; - it.compositeRule = $it.compositeRule = true; - var arr1 = $schema; - if (arr1) { - var $sch, $i = -1, - l1 = arr1.length - 1; - while ($i < l1) { - $sch = arr1[$i += 1]; - $it.schema = $sch; - $it.schemaPath = $schemaPath + '[' + $i + ']'; - $it.errSchemaPath = $errSchemaPath + '/' + $i; - out += ' ' + (it.validate($it)) + ' '; - $it.baseId = $currentBaseId; - out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { '; - $closingBraces += '}'; - } - } - it.compositeRule = $it.compositeRule = $wasComposite; - out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; - if (it.opts.messages !== false) { - out += ' , message: \'should match some schema in anyOf\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError(vErrors); '; - } else { - out += ' validate.errors = vErrors; return false; '; - } - } - out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; - if (it.opts.allErrors) { - out += ' } '; - } - } else { - if ($breakOnError) { - out += ' if (true) { '; - } +// API +module.exports = terminator; + +/** + * Terminates jobs in the attached state context + * + * @this AsyncKitState# + * @param {function} callback - final callback to invoke after termination + */ +function terminator(callback) +{ + if (!Object.keys(this.jobs).length) + { + return; } - return out; + + // fast forward iteration index + this.index = this.size; + + // abort jobs + abort(this); + + // send back results we have so far + async(callback)(null, this.results); } /***/ }), -/***/ 30134: -/***/ ((module) => { +/***/ 8210: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +var iterate = __nccwpck_require__(9023) + , initState = __nccwpck_require__(42474) + , terminator = __nccwpck_require__(37942) + ; -module.exports = function generate_comment(it, $keyword, $ruleType) { - var out = ' '; - var $schema = it.schema[$keyword]; - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $comment = it.util.toQuotedString($schema); - if (it.opts.$comment === true) { - out += ' console.log(' + ($comment) + ');'; - } else if (typeof it.opts.$comment == 'function') { - out += ' self._opts.$comment(' + ($comment) + ', ' + (it.util.toQuotedString($errSchemaPath)) + ', validate.root.schema);'; +// Public API +module.exports = parallel; + +/** + * Runs iterator over provided array elements in parallel + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function parallel(list, iterator, callback) +{ + var state = initState(list); + + while (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, function(error, result) + { + if (error) + { + callback(error, result); + return; + } + + // looks like it's the last one + if (Object.keys(state.jobs).length === 0) + { + callback(null, state.results); + return; + } + }); + + state.index++; } - return out; + + return terminator.bind(state, callback); } /***/ }), -/***/ 1661: -/***/ ((module) => { +/***/ 50445: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +var serialOrdered = __nccwpck_require__(3578); -module.exports = function generate_const(it, $keyword, $ruleType) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $valid = 'valid' + $lvl; - var $isData = it.opts.$data && $schema && $schema.$data, - $schemaValue; - if ($isData) { - out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; - $schemaValue = 'schema' + $lvl; - } else { - $schemaValue = $schema; - } - if (!$isData) { - out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';'; - } - out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') { '; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('const') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValue: schema' + ($lvl) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should be equal to constant\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += ' }'; - if ($breakOnError) { - out += ' else { '; - } - return out; +// Public API +module.exports = serial; + +/** + * Runs iterator over provided array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function serial(list, iterator, callback) +{ + return serialOrdered(list, iterator, null, callback); } /***/ }), -/***/ 55964: -/***/ ((module) => { +/***/ 3578: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +var iterate = __nccwpck_require__(9023) + , initState = __nccwpck_require__(42474) + , terminator = __nccwpck_require__(37942) + ; -module.exports = function generate_contains(it, $keyword, $ruleType) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $valid = 'valid' + $lvl; - var $errs = 'errs__' + $lvl; - var $it = it.util.copy(it); - var $closingBraces = ''; - $it.level++; - var $nextValid = 'valid' + $it.level; - var $idx = 'i' + $lvl, - $dataNxt = $it.dataLevel = it.dataLevel + 1, - $nextData = 'data' + $dataNxt, - $currentBaseId = it.baseId, - $nonEmptySchema = (it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all)); - out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; - if ($nonEmptySchema) { - var $wasComposite = it.compositeRule; - it.compositeRule = $it.compositeRule = true; - $it.schema = $schema; - $it.schemaPath = $schemaPath; - $it.errSchemaPath = $errSchemaPath; - out += ' var ' + ($nextValid) + ' = false; for (var ' + ($idx) + ' = 0; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; - $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); - var $passData = $data + '[' + $idx + ']'; - $it.dataPathArr[$dataNxt] = $idx; - var $code = it.validate($it); - $it.baseId = $currentBaseId; - if (it.util.varOccurences($code, $nextData) < 2) { - out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; - } else { - out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; - } - out += ' if (' + ($nextValid) + ') break; } '; - it.compositeRule = $it.compositeRule = $wasComposite; - out += ' ' + ($closingBraces) + ' if (!' + ($nextValid) + ') {'; - } else { - out += ' if (' + ($data) + '.length == 0) {'; - } - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('contains') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; - if (it.opts.messages !== false) { - out += ' , message: \'should contain a valid item\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; +// Public API +module.exports = serialOrdered; +// sorting helpers +module.exports.ascending = ascending; +module.exports.descending = descending; + +/** + * Runs iterator over provided sorted array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} sortMethod - custom sort function + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function serialOrdered(list, iterator, sortMethod, callback) +{ + var state = initState(list, sortMethod); + + iterate(list, iterator, state, function iteratorHandler(error, result) + { + if (error) + { + callback(error, result); + return; } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; + + state.index++; + + // are we there yet? + if (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, iteratorHandler); + return; } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += ' } else { '; - if ($nonEmptySchema) { - out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; - } - if (it.opts.allErrors) { - out += ' } '; - } - return out; + + // done here + callback(null, state.results); + }); + + return terminator.bind(state, callback); +} + +/* + * -- Sort methods + */ + +/** + * sort helper to sort array elements in ascending order + * + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result + */ +function ascending(a, b) +{ + return a < b ? -1 : a > b ? 1 : 0; +} + +/** + * sort helper to sort array elements in descending order + * + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result + */ +function descending(a, b) +{ + return -1 * ascending(a, b); } /***/ }), -/***/ 5912: -/***/ ((module) => { +/***/ 96342: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; -module.exports = function generate_custom(it, $keyword, $ruleType) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $errorKeyword; - var $data = 'data' + ($dataLvl || ''); - var $valid = 'valid' + $lvl; - var $errs = 'errs__' + $lvl; - var $isData = it.opts.$data && $schema && $schema.$data, - $schemaValue; - if ($isData) { - out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; - $schemaValue = 'schema' + $lvl; - } else { - $schemaValue = $schema; - } - var $rule = this, - $definition = 'definition' + $lvl, - $rDef = $rule.definition, - $closingBraces = ''; - var $compile, $inline, $macro, $ruleValidate, $validateCode; - if ($isData && $rDef.$data) { - $validateCode = 'keywordValidate' + $lvl; - var $validateSchema = $rDef.validateSchema; - out += ' var ' + ($definition) + ' = RULES.custom[\'' + ($keyword) + '\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;'; - } else { - $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it); - if (!$ruleValidate) return; - $schemaValue = 'validate.schema' + $schemaPath; - $validateCode = $ruleValidate.code; - $compile = $rDef.compile; - $inline = $rDef.inline; - $macro = $rDef.macro; - } - var $ruleErrs = $validateCode + '.errors', - $i = 'i' + $lvl, - $ruleErr = 'ruleErr' + $lvl, - $asyncKeyword = $rDef.async; - if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema'); - if (!($inline || $macro)) { - out += '' + ($ruleErrs) + ' = null;'; - } - out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; - if ($isData && $rDef.$data) { - $closingBraces += '}'; - out += ' if (' + ($schemaValue) + ' === undefined) { ' + ($valid) + ' = true; } else { '; - if ($validateSchema) { - $closingBraces += '}'; - out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') { '; - } - } - if ($inline) { - if ($rDef.statements) { - out += ' ' + ($ruleValidate.validate) + ' '; - } else { - out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; '; - } - } else if ($macro) { - var $it = it.util.copy(it); - var $closingBraces = ''; - $it.level++; - var $nextValid = 'valid' + $it.level; - $it.schema = $ruleValidate.validate; - $it.schemaPath = ''; - var $wasComposite = it.compositeRule; - it.compositeRule = $it.compositeRule = true; - var $code = it.validate($it).replace(/validate\.schema/g, $validateCode); - it.compositeRule = $it.compositeRule = $wasComposite; - out += ' ' + ($code); - } else { - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; - out += ' ' + ($validateCode) + '.call( '; - if (it.opts.passContext) { - out += 'this'; - } else { - out += 'self'; - } - if ($compile || $rDef.schema === false) { - out += ' , ' + ($data) + ' '; - } else { - out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' '; - } - out += ' , (dataPath || \'\')'; - if (it.errorPath != '""') { - out += ' + ' + (it.errorPath); - } - var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', - $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; - out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData ) '; - var def_callRuleValidate = out; - out = $$outStack.pop(); - if ($rDef.errors === false) { - out += ' ' + ($valid) + ' = '; - if ($asyncKeyword) { - out += 'await '; - } - out += '' + (def_callRuleValidate) + '; '; - } else { - if ($asyncKeyword) { - $ruleErrs = 'customErrors' + $lvl; - out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = await ' + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } '; - } else { - out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; '; - } - } - } - if ($rDef.modifying) { - out += ' if (' + ($parentData) + ') ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];'; - } - out += '' + ($closingBraces); - if ($rDef.valid) { - if ($breakOnError) { - out += ' if (true) { '; - } - } else { - out += ' if ( '; - if ($rDef.valid === undefined) { - out += ' !'; - if ($macro) { - out += '' + ($nextValid); - } else { - out += '' + ($valid); - } - } else { - out += ' ' + (!$rDef.valid) + ' '; - } - out += ') { '; - $errorKeyword = $rule.keyword; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - var def_customError = out; - out = $$outStack.pop(); - if ($inline) { - if ($rDef.errors) { - if ($rDef.errors != 'full') { - out += ' for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + ' + * + * 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. + */ + +/** + * Module dependencies. + */ + +var crypto = __nccwpck_require__(6113) + , parse = (__nccwpck_require__(57310).parse) + ; + +/** + * Valid keys. + */ + +var keys = + [ 'acl' + , 'location' + , 'logging' + , 'notification' + , 'partNumber' + , 'policy' + , 'requestPayment' + , 'torrent' + , 'uploadId' + , 'uploads' + , 'versionId' + , 'versioning' + , 'versions' + , 'website' + ] + +/** + * Return an "Authorization" header value with the given `options` + * in the form of "AWS :" + * + * @param {Object} options + * @return {String} + * @api private + */ + +function authorization (options) { + return 'AWS ' + options.key + ':' + sign(options) +} + +module.exports = authorization +module.exports.authorization = authorization + +/** + * Simple HMAC-SHA1 Wrapper + * + * @param {Object} options + * @return {String} + * @api private + */ + +function hmacSha1 (options) { + return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64') +} + +module.exports.hmacSha1 = hmacSha1 + +/** + * Create a base64 sha1 HMAC for `options`. + * + * @param {Object} options + * @return {String} + * @api private + */ + +function sign (options) { + options.message = stringToSign(options) + return hmacSha1(options) } +module.exports.sign = sign +/** + * Create a base64 sha1 HMAC for `options`. + * + * Specifically to be used with S3 presigned URLs + * + * @param {Object} options + * @return {String} + * @api private + */ -/***/ }), +function signQuery (options) { + options.message = queryStringToSign(options) + return hmacSha1(options) +} +module.exports.signQuery= signQuery -/***/ 2591: -/***/ ((module) => { +/** + * Return a string for sign() with the given `options`. + * + * Spec: + * + * \n + * \n + * \n + * \n + * [headers\n] + * + * + * @param {Object} options + * @return {String} + * @api private + */ -"use strict"; +function stringToSign (options) { + var headers = options.amazonHeaders || '' + if (headers) headers += '\n' + var r = + [ options.verb + , options.md5 + , options.contentType + , options.date ? options.date.toUTCString() : '' + , headers + options.resource + ] + return r.join('\n') +} +module.exports.stringToSign = stringToSign -module.exports = function generate_dependencies(it, $keyword, $ruleType) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $errs = 'errs__' + $lvl; - var $it = it.util.copy(it); - var $closingBraces = ''; - $it.level++; - var $nextValid = 'valid' + $it.level; - var $schemaDeps = {}, - $propertyDeps = {}, - $ownProperties = it.opts.ownProperties; - for ($property in $schema) { - if ($property == '__proto__') continue; - var $sch = $schema[$property]; - var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps; - $deps[$property] = $sch; - } - out += 'var ' + ($errs) + ' = errors;'; - var $currentErrorPath = it.errorPath; - out += 'var missing' + ($lvl) + ';'; - for (var $property in $propertyDeps) { - $deps = $propertyDeps[$property]; - if ($deps.length) { - out += ' if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined '; - if ($ownProperties) { - out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') '; - } - if ($breakOnError) { - out += ' && ( '; - var arr1 = $deps; - if (arr1) { - var $propertyKey, $i = -1, - l1 = arr1.length - 1; - while ($i < l1) { - $propertyKey = arr1[$i += 1]; - if ($i) { - out += ' || '; - } - var $prop = it.util.getProperty($propertyKey), - $useData = $data + $prop; - out += ' ( ( ' + ($useData) + ' === undefined '; - if ($ownProperties) { - out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; - } - out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) '; - } - } - out += ')) { '; - var $propertyPath = 'missing' + $lvl, - $missingProperty = '\' + ' + $propertyPath + ' + \''; - if (it.opts._errorDataPathProperty) { - it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; - } - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should have '; - if ($deps.length == 1) { - out += 'property ' + (it.util.escapeQuotes($deps[0])); - } else { - out += 'properties ' + (it.util.escapeQuotes($deps.join(", "))); - } - out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - } else { - out += ' ) { '; - var arr2 = $deps; - if (arr2) { - var $propertyKey, i2 = -1, - l2 = arr2.length - 1; - while (i2 < l2) { - $propertyKey = arr2[i2 += 1]; - var $prop = it.util.getProperty($propertyKey), - $missingProperty = it.util.escapeQuotes($propertyKey), - $useData = $data + $prop; - if (it.opts._errorDataPathProperty) { - it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); - } - out += ' if ( ' + ($useData) + ' === undefined '; - if ($ownProperties) { - out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; - } - out += ') { var err = '; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should have '; - if ($deps.length == 1) { - out += 'property ' + (it.util.escapeQuotes($deps[0])); - } else { - out += 'properties ' + (it.util.escapeQuotes($deps.join(", "))); - } - out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; - } - } - } - out += ' } '; - if ($breakOnError) { - $closingBraces += '}'; - out += ' else { '; - } - } - } - it.errorPath = $currentErrorPath; - var $currentBaseId = $it.baseId; - for (var $property in $schemaDeps) { - var $sch = $schemaDeps[$property]; - if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { - out += ' ' + ($nextValid) + ' = true; if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined '; - if ($ownProperties) { - out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') '; - } - out += ') { '; - $it.schema = $sch; - $it.schemaPath = $schemaPath + it.util.getProperty($property); - $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property); - out += ' ' + (it.validate($it)) + ' '; - $it.baseId = $currentBaseId; - out += ' } '; - if ($breakOnError) { - out += ' if (' + ($nextValid) + ') { '; - $closingBraces += '}'; - } - } - } - if ($breakOnError) { - out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; +/** + * Return a string for sign() with the given `options`, but is meant exclusively + * for S3 presigned URLs + * + * Spec: + * + * \n + * + * + * @param {Object} options + * @return {String} + * @api private + */ + +function queryStringToSign (options){ + return 'GET\n\n\n' + options.date + '\n' + options.resource +} +module.exports.queryStringToSign = queryStringToSign + +/** + * Perform the following: + * + * - ignore non-amazon headers + * - lowercase fields + * - sort lexicographically + * - trim whitespace between ":" + * - join with newline + * + * @param {Object} headers + * @return {String} + * @api private + */ + +function canonicalizeHeaders (headers) { + var buf = [] + , fields = Object.keys(headers) + ; + for (var i = 0, len = fields.length; i < len; ++i) { + var field = fields[i] + , val = headers[field] + , field = field.toLowerCase() + ; + if (0 !== field.indexOf('x-amz')) continue + buf.push(field + ':' + val) } - return out; + return buf.sort().join('\n') +} +module.exports.canonicalizeHeaders = canonicalizeHeaders + +/** + * Perform the following: + * + * - ignore non sub-resources + * - sort lexicographically + * + * @param {String} resource + * @return {String} + * @api private + */ + +function canonicalizeResource (resource) { + var url = parse(resource, true) + , path = url.pathname + , buf = [] + ; + + Object.keys(url.query).forEach(function(key){ + if (!~keys.indexOf(key)) return + var val = '' == url.query[key] ? '' : '=' + encodeURIComponent(url.query[key]) + buf.push(key + val) + }) + + return path + (buf.length ? '?' + buf.sort().join('&') : '') } +module.exports.canonicalizeResource = canonicalizeResource /***/ }), -/***/ 10163: -/***/ ((module) => { +/***/ 16071: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +var aws4 = exports, + url = __nccwpck_require__(57310), + querystring = __nccwpck_require__(63477), + crypto = __nccwpck_require__(6113), + lru = __nccwpck_require__(74225), + credentialsCache = lru(1000) -module.exports = function generate_enum(it, $keyword, $ruleType) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $valid = 'valid' + $lvl; - var $isData = it.opts.$data && $schema && $schema.$data, - $schemaValue; - if ($isData) { - out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; - $schemaValue = 'schema' + $lvl; - } else { - $schemaValue = $schema; - } - var $i = 'i' + $lvl, - $vSchema = 'schema' + $lvl; - if (!$isData) { - out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + ';'; - } - out += 'var ' + ($valid) + ';'; - if ($isData) { - out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; - } - out += '' + ($valid) + ' = false;for (var ' + ($i) + '=0; ' + ($i) + '<' + ($vSchema) + '.length; ' + ($i) + '++) if (equal(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + '])) { ' + ($valid) + ' = true; break; }'; - if ($isData) { - out += ' } '; - } - out += ' if (!' + ($valid) + ') { '; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('enum') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValues: schema' + ($lvl) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should be equal to one of the allowed values\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += ' }'; - if ($breakOnError) { - out += ' else { '; - } - return out; +// http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html + +function hmac(key, string, encoding) { + return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding) } +function hash(string, encoding) { + return crypto.createHash('sha256').update(string, 'utf8').digest(encoding) +} -/***/ }), +// This function assumes the string has already been percent encoded +function encodeRfc3986(urlEncodedString) { + return urlEncodedString.replace(/[!'()*]/g, function(c) { + return '%' + c.charCodeAt(0).toString(16).toUpperCase() + }) +} -/***/ 63847: -/***/ ((module) => { +function encodeRfc3986Full(str) { + return encodeRfc3986(encodeURIComponent(str)) +} -"use strict"; +// A bit of a combination of: +// https://github.com/aws/aws-sdk-java-v2/blob/dc695de6ab49ad03934e1b02e7263abbd2354be0/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/AbstractAws4Signer.java#L59 +// https://github.com/aws/aws-sdk-js/blob/18cb7e5b463b46239f9fdd4a65e2ff8c81831e8f/lib/signers/v4.js#L191-L199 +// https://github.com/mhart/aws4fetch/blob/b3aed16b6f17384cf36ea33bcba3c1e9f3bdfefd/src/main.js#L25-L34 +var HEADERS_TO_IGNORE = { + 'authorization': true, + 'connection': true, + 'x-amzn-trace-id': true, + 'user-agent': true, + 'expect': true, + 'presigned-expires': true, + 'range': true, +} -module.exports = function generate_format(it, $keyword, $ruleType) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - if (it.opts.format === false) { - if ($breakOnError) { - out += ' if (true) { '; - } - return out; - } - var $isData = it.opts.$data && $schema && $schema.$data, - $schemaValue; - if ($isData) { - out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; - $schemaValue = 'schema' + $lvl; - } else { - $schemaValue = $schema; +// request: { path | body, [host], [method], [headers], [service], [region] } +// credentials: { accessKeyId, secretAccessKey, [sessionToken] } +function RequestSigner(request, credentials) { + + if (typeof request === 'string') request = url.parse(request) + + var headers = request.headers = (request.headers || {}), + hostParts = (!this.service || !this.region) && this.matchHost(request.hostname || request.host || headers.Host || headers.host) + + this.request = request + this.credentials = credentials || this.defaultCredentials() + + this.service = request.service || hostParts[0] || '' + this.region = request.region || hostParts[1] || 'us-east-1' + + // SES uses a different domain from the service name + if (this.service === 'email') this.service = 'ses' + + if (!request.method && request.body) + request.method = 'POST' + + if (!headers.Host && !headers.host) { + headers.Host = request.hostname || request.host || this.createHost() + + // If a port is specified explicitly, use it as is + if (request.port) + headers.Host += ':' + request.port } - var $unknownFormats = it.opts.unknownFormats, - $allowUnknown = Array.isArray($unknownFormats); - if ($isData) { - var $format = 'format' + $lvl, - $isObject = 'isObject' + $lvl, - $formatType = 'formatType' + $lvl; - out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var ' + ($isObject) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; var ' + ($formatType) + ' = ' + ($isObject) + ' && ' + ($format) + '.type || \'string\'; if (' + ($isObject) + ') { '; - if (it.async) { - out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; '; - } - out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if ( '; - if ($isData) { - out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; - } - out += ' ('; - if ($unknownFormats != 'ignore') { - out += ' (' + ($schemaValue) + ' && !' + ($format) + ' '; - if ($allowUnknown) { - out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 '; - } - out += ') || '; - } - out += ' (' + ($format) + ' && ' + ($formatType) + ' == \'' + ($ruleType) + '\' && !(typeof ' + ($format) + ' == \'function\' ? '; - if (it.async) { - out += ' (async' + ($lvl) + ' ? await ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) '; - } else { - out += ' ' + ($format) + '(' + ($data) + ') '; - } - out += ' : ' + ($format) + '.test(' + ($data) + '))))) {'; + if (!request.hostname && !request.host) + request.hostname = headers.Host || headers.host + + this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT' + + this.extraHeadersToIgnore = request.extraHeadersToIgnore || Object.create(null) + this.extraHeadersToInclude = request.extraHeadersToInclude || Object.create(null) +} + +RequestSigner.prototype.matchHost = function(host) { + var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/) + var hostParts = (match || []).slice(1, 3) + + // ES's hostParts are sometimes the other way round, if the value that is expected + // to be region equals ‘es’ switch them back + // e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com + if (hostParts[1] === 'es' || hostParts[1] === 'aoss') + hostParts = hostParts.reverse() + + if (hostParts[1] == 's3') { + hostParts[0] = 's3' + hostParts[1] = 'us-east-1' } else { - var $format = it.formats[$schema]; - if (!$format) { - if ($unknownFormats == 'ignore') { - it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"'); - if ($breakOnError) { - out += ' if (true) { '; - } - return out; - } else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) { - if ($breakOnError) { - out += ' if (true) { '; - } - return out; - } else { - throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"'); - } - } - var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate; - var $formatType = $isObject && $format.type || 'string'; - if ($isObject) { - var $async = $format.async === true; - $format = $format.validate; - } - if ($formatType != $ruleType) { - if ($breakOnError) { - out += ' if (true) { '; - } - return out; - } - if ($async) { - if (!it.async) throw new Error('async format in sync schema'); - var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate'; - out += ' if (!(await ' + ($formatRef) + '(' + ($data) + '))) { '; - } else { - out += ' if (! '; - var $formatRef = 'formats' + it.util.getProperty($schema); - if ($isObject) $formatRef += '.validate'; - if (typeof $format == 'function') { - out += ' ' + ($formatRef) + '(' + ($data) + ') '; - } else { - out += ' ' + ($formatRef) + '.test(' + ($data) + ') '; - } - out += ') { '; - } - } - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format: '; - if ($isData) { - out += '' + ($schemaValue); - } else { - out += '' + (it.util.toQuotedString($schema)); - } - out += ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should match format "'; - if ($isData) { - out += '\' + ' + ($schemaValue) + ' + \''; - } else { - out += '' + (it.util.escapeQuotes($schema)); - } - out += '"\' '; - } - if (it.opts.verbose) { - out += ' , schema: '; - if ($isData) { - out += 'validate.schema' + ($schemaPath); - } else { - out += '' + (it.util.toQuotedString($schema)); + for (var i = 0; i < 2; i++) { + if (/^s3-/.test(hostParts[i])) { + hostParts[1] = hostParts[i].slice(3) + hostParts[0] = 's3' + break } - out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += ' } '; - if ($breakOnError) { - out += ' else { '; } - return out; + + return hostParts } +// http://docs.aws.amazon.com/general/latest/gr/rande.html +RequestSigner.prototype.isSingleRegion = function() { + // Special case for S3 and SimpleDB in us-east-1 + if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1') return true -/***/ }), + return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts'] + .indexOf(this.service) >= 0 +} -/***/ 80862: -/***/ ((module) => { +RequestSigner.prototype.createHost = function() { + var region = this.isSingleRegion() ? '' : '.' + this.region, + subdomain = this.service === 'ses' ? 'email' : this.service + return subdomain + region + '.amazonaws.com' +} -"use strict"; +RequestSigner.prototype.prepareRequest = function() { + this.parsePath() + + var request = this.request, headers = request.headers, query + + if (request.signQuery) { + + this.parsedPath.query = query = this.parsedPath.query || {} + + if (this.credentials.sessionToken) + query['X-Amz-Security-Token'] = this.credentials.sessionToken + + if (this.service === 's3' && !query['X-Amz-Expires']) + query['X-Amz-Expires'] = 86400 + + if (query['X-Amz-Date']) + this.datetime = query['X-Amz-Date'] + else + query['X-Amz-Date'] = this.getDateTime() + + query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256' + query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString() + query['X-Amz-SignedHeaders'] = this.signedHeaders() -module.exports = function generate_if(it, $keyword, $ruleType) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $valid = 'valid' + $lvl; - var $errs = 'errs__' + $lvl; - var $it = it.util.copy(it); - $it.level++; - var $nextValid = 'valid' + $it.level; - var $thenSch = it.schema['then'], - $elseSch = it.schema['else'], - $thenPresent = $thenSch !== undefined && (it.opts.strictKeywords ? (typeof $thenSch == 'object' && Object.keys($thenSch).length > 0) || $thenSch === false : it.util.schemaHasRules($thenSch, it.RULES.all)), - $elsePresent = $elseSch !== undefined && (it.opts.strictKeywords ? (typeof $elseSch == 'object' && Object.keys($elseSch).length > 0) || $elseSch === false : it.util.schemaHasRules($elseSch, it.RULES.all)), - $currentBaseId = $it.baseId; - if ($thenPresent || $elsePresent) { - var $ifClause; - $it.createErrors = false; - $it.schema = $schema; - $it.schemaPath = $schemaPath; - $it.errSchemaPath = $errSchemaPath; - out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = true; '; - var $wasComposite = it.compositeRule; - it.compositeRule = $it.compositeRule = true; - out += ' ' + (it.validate($it)) + ' '; - $it.baseId = $currentBaseId; - $it.createErrors = true; - out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; - it.compositeRule = $it.compositeRule = $wasComposite; - if ($thenPresent) { - out += ' if (' + ($nextValid) + ') { '; - $it.schema = it.schema['then']; - $it.schemaPath = it.schemaPath + '.then'; - $it.errSchemaPath = it.errSchemaPath + '/then'; - out += ' ' + (it.validate($it)) + ' '; - $it.baseId = $currentBaseId; - out += ' ' + ($valid) + ' = ' + ($nextValid) + '; '; - if ($thenPresent && $elsePresent) { - $ifClause = 'ifClause' + $lvl; - out += ' var ' + ($ifClause) + ' = \'then\'; '; - } else { - $ifClause = '\'then\''; - } - out += ' } '; - if ($elsePresent) { - out += ' else { '; - } - } else { - out += ' if (!' + ($nextValid) + ') { '; - } - if ($elsePresent) { - $it.schema = it.schema['else']; - $it.schemaPath = it.schemaPath + '.else'; - $it.errSchemaPath = it.errSchemaPath + '/else'; - out += ' ' + (it.validate($it)) + ' '; - $it.baseId = $currentBaseId; - out += ' ' + ($valid) + ' = ' + ($nextValid) + '; '; - if ($thenPresent && $elsePresent) { - $ifClause = 'ifClause' + $lvl; - out += ' var ' + ($ifClause) + ' = \'else\'; '; - } else { - $ifClause = '\'else\''; - } - out += ' } '; - } - out += ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('if') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { failingKeyword: ' + ($ifClause) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should match "\' + ' + ($ifClause) + ' + \'" schema\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError(vErrors); '; - } else { - out += ' validate.errors = vErrors; return false; '; - } - } - out += ' } '; - if ($breakOnError) { - out += ' else { '; - } } else { - if ($breakOnError) { - out += ' if (true) { '; + + if (!request.doNotModifyHeaders && !this.isCodeCommitGit) { + if (request.body && !headers['Content-Type'] && !headers['content-type']) + headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8' + + if (request.body && !headers['Content-Length'] && !headers['content-length']) + headers['Content-Length'] = Buffer.byteLength(request.body) + + if (this.credentials.sessionToken && !headers['X-Amz-Security-Token'] && !headers['x-amz-security-token']) + headers['X-Amz-Security-Token'] = this.credentials.sessionToken + + if (this.service === 's3' && !headers['X-Amz-Content-Sha256'] && !headers['x-amz-content-sha256']) + headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex') + + if (headers['X-Amz-Date'] || headers['x-amz-date']) + this.datetime = headers['X-Amz-Date'] || headers['x-amz-date'] + else + headers['X-Amz-Date'] = this.getDateTime() } + + delete headers.Authorization + delete headers.authorization } - return out; } +RequestSigner.prototype.sign = function() { + if (!this.parsedPath) this.prepareRequest() -/***/ }), + if (this.request.signQuery) { + this.parsedPath.query['X-Amz-Signature'] = this.signature() + } else { + this.request.headers.Authorization = this.authHeader() + } -/***/ 85810: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this.request.path = this.formatPath() -"use strict"; + return this.request +} +RequestSigner.prototype.getDateTime = function() { + if (!this.datetime) { + var headers = this.request.headers, + date = new Date(headers.Date || headers.date || new Date) -//all requires must be explicit because browserify won't work with dynamic requires -module.exports = { - '$ref': __nccwpck_require__(42393), - allOf: __nccwpck_require__(89443), - anyOf: __nccwpck_require__(63093), - '$comment': __nccwpck_require__(30134), - const: __nccwpck_require__(1661), - contains: __nccwpck_require__(55964), - dependencies: __nccwpck_require__(2591), - 'enum': __nccwpck_require__(10163), - format: __nccwpck_require__(63847), - 'if': __nccwpck_require__(80862), - items: __nccwpck_require__(54408), - maximum: __nccwpck_require__(7404), - minimum: __nccwpck_require__(7404), - maxItems: __nccwpck_require__(64683), - minItems: __nccwpck_require__(64683), - maxLength: __nccwpck_require__(52114), - minLength: __nccwpck_require__(52114), - maxProperties: __nccwpck_require__(71142), - minProperties: __nccwpck_require__(71142), - multipleOf: __nccwpck_require__(39772), - not: __nccwpck_require__(60750), - oneOf: __nccwpck_require__(6106), - pattern: __nccwpck_require__(13912), - properties: __nccwpck_require__(52924), - propertyNames: __nccwpck_require__(19195), - required: __nccwpck_require__(8420), - uniqueItems: __nccwpck_require__(24995), - validate: __nccwpck_require__(49585) -}; + this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, '') + // Remove the trailing 'Z' on the timestamp string for CodeCommit git access + if (this.isCodeCommitGit) this.datetime = this.datetime.slice(0, -1) + } + return this.datetime +} -/***/ }), +RequestSigner.prototype.getDate = function() { + return this.getDateTime().substr(0, 8) +} -/***/ 54408: -/***/ ((module) => { +RequestSigner.prototype.authHeader = function() { + return [ + 'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(), + 'SignedHeaders=' + this.signedHeaders(), + 'Signature=' + this.signature(), + ].join(', ') +} -"use strict"; +RequestSigner.prototype.signature = function() { + var date = this.getDate(), + cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(), + kDate, kRegion, kService, kCredentials = credentialsCache.get(cacheKey) + if (!kCredentials) { + kDate = hmac('AWS4' + this.credentials.secretAccessKey, date) + kRegion = hmac(kDate, this.region) + kService = hmac(kRegion, this.service) + kCredentials = hmac(kService, 'aws4_request') + credentialsCache.set(cacheKey, kCredentials) + } + return hmac(kCredentials, this.stringToSign(), 'hex') +} -module.exports = function generate_items(it, $keyword, $ruleType) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $valid = 'valid' + $lvl; - var $errs = 'errs__' + $lvl; - var $it = it.util.copy(it); - var $closingBraces = ''; - $it.level++; - var $nextValid = 'valid' + $it.level; - var $idx = 'i' + $lvl, - $dataNxt = $it.dataLevel = it.dataLevel + 1, - $nextData = 'data' + $dataNxt, - $currentBaseId = it.baseId; - out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; - if (Array.isArray($schema)) { - var $additionalItems = it.schema.additionalItems; - if ($additionalItems === false) { - out += ' ' + ($valid) + ' = ' + ($data) + '.length <= ' + ($schema.length) + '; '; - var $currErrSchemaPath = $errSchemaPath; - $errSchemaPath = it.errSchemaPath + '/additionalItems'; - out += ' if (!' + ($valid) + ') { '; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('additionalItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should NOT have more than ' + ($schema.length) + ' items\' '; - } - if (it.opts.verbose) { - out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += ' } '; - $errSchemaPath = $currErrSchemaPath; - if ($breakOnError) { - $closingBraces += '}'; - out += ' else { '; - } - } - var arr1 = $schema; - if (arr1) { - var $sch, $i = -1, - l1 = arr1.length - 1; - while ($i < l1) { - $sch = arr1[$i += 1]; - if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { - out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($i) + ') { '; - var $passData = $data + '[' + $i + ']'; - $it.schema = $sch; - $it.schemaPath = $schemaPath + '[' + $i + ']'; - $it.errSchemaPath = $errSchemaPath + '/' + $i; - $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true); - $it.dataPathArr[$dataNxt] = $i; - var $code = it.validate($it); - $it.baseId = $currentBaseId; - if (it.util.varOccurences($code, $nextData) < 2) { - out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; - } else { - out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; - } - out += ' } '; - if ($breakOnError) { - out += ' if (' + ($nextValid) + ') { '; - $closingBraces += '}'; - } - } - } - } - if (typeof $additionalItems == 'object' && (it.opts.strictKeywords ? (typeof $additionalItems == 'object' && Object.keys($additionalItems).length > 0) || $additionalItems === false : it.util.schemaHasRules($additionalItems, it.RULES.all))) { - $it.schema = $additionalItems; - $it.schemaPath = it.schemaPath + '.additionalItems'; - $it.errSchemaPath = it.errSchemaPath + '/additionalItems'; - out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') { for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; - $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); - var $passData = $data + '[' + $idx + ']'; - $it.dataPathArr[$dataNxt] = $idx; - var $code = it.validate($it); - $it.baseId = $currentBaseId; - if (it.util.varOccurences($code, $nextData) < 2) { - out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; +RequestSigner.prototype.stringToSign = function() { + return [ + 'AWS4-HMAC-SHA256', + this.getDateTime(), + this.credentialString(), + hash(this.canonicalString(), 'hex'), + ].join('\n') +} + +RequestSigner.prototype.canonicalString = function() { + if (!this.parsedPath) this.prepareRequest() + + var pathStr = this.parsedPath.path, + query = this.parsedPath.query, + headers = this.request.headers, + queryStr = '', + normalizePath = this.service !== 's3', + decodePath = this.service === 's3' || this.request.doNotEncodePath, + decodeSlashesInPath = this.service === 's3', + firstValOnly = this.service === 's3', + bodyHash + + if (this.service === 's3' && this.request.signQuery) { + bodyHash = 'UNSIGNED-PAYLOAD' + } else if (this.isCodeCommitGit) { + bodyHash = '' + } else { + bodyHash = headers['X-Amz-Content-Sha256'] || headers['x-amz-content-sha256'] || + hash(this.request.body || '', 'hex') + } + + if (query) { + var reducedQuery = Object.keys(query).reduce(function(obj, key) { + if (!key) return obj + obj[encodeRfc3986Full(key)] = !Array.isArray(query[key]) ? query[key] : + (firstValOnly ? query[key][0] : query[key]) + return obj + }, {}) + var encodedQueryPieces = [] + Object.keys(reducedQuery).sort().forEach(function(key) { + if (!Array.isArray(reducedQuery[key])) { + encodedQueryPieces.push(key + '=' + encodeRfc3986Full(reducedQuery[key])) } else { - out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; - } - if ($breakOnError) { - out += ' if (!' + ($nextValid) + ') break; '; - } - out += ' } } '; - if ($breakOnError) { - out += ' if (' + ($nextValid) + ') { '; - $closingBraces += '}'; + reducedQuery[key].map(encodeRfc3986Full).sort() + .forEach(function(val) { encodedQueryPieces.push(key + '=' + val) }) } - } - } else if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { - $it.schema = $schema; - $it.schemaPath = $schemaPath; - $it.errSchemaPath = $errSchemaPath; - out += ' for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; - $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); - var $passData = $data + '[' + $idx + ']'; - $it.dataPathArr[$dataNxt] = $idx; - var $code = it.validate($it); - $it.baseId = $currentBaseId; - if (it.util.varOccurences($code, $nextData) < 2) { - out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; - } else { - out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; - } - if ($breakOnError) { - out += ' if (!' + ($nextValid) + ') break; '; - } - out += ' }'; + }) + queryStr = encodedQueryPieces.join('&') + } + if (pathStr !== '/') { + if (normalizePath) pathStr = pathStr.replace(/\/{2,}/g, '/') + pathStr = pathStr.split('/').reduce(function(path, piece) { + if (normalizePath && piece === '..') { + path.pop() + } else if (!normalizePath || piece !== '.') { + if (decodePath) piece = decodeURIComponent(piece.replace(/\+/g, ' ')) + path.push(encodeRfc3986Full(piece)) + } + return path + }, []).join('/') + if (pathStr[0] !== '/') pathStr = '/' + pathStr + if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/') } - if ($breakOnError) { - out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + + return [ + this.request.method || 'GET', + pathStr, + queryStr, + this.canonicalHeaders() + '\n', + this.signedHeaders(), + bodyHash, + ].join('\n') +} + +RequestSigner.prototype.canonicalHeaders = function() { + var headers = this.request.headers + function trimAll(header) { + return header.toString().trim().replace(/\s+/g, ' ') } - return out; + return Object.keys(headers) + .filter(function(key) { return HEADERS_TO_IGNORE[key.toLowerCase()] == null }) + .sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1 }) + .map(function(key) { return key.toLowerCase() + ':' + trimAll(headers[key]) }) + .join('\n') } +RequestSigner.prototype.signedHeaders = function() { + var extraHeadersToInclude = this.extraHeadersToInclude, + extraHeadersToIgnore = this.extraHeadersToIgnore + return Object.keys(this.request.headers) + .map(function(key) { return key.toLowerCase() }) + .filter(function(key) { + return extraHeadersToInclude[key] || + (HEADERS_TO_IGNORE[key] == null && !extraHeadersToIgnore[key]) + }) + .sort() + .join(';') +} -/***/ }), +RequestSigner.prototype.credentialString = function() { + return [ + this.getDate(), + this.region, + this.service, + 'aws4_request', + ].join('/') +} -/***/ 39772: -/***/ ((module) => { +RequestSigner.prototype.defaultCredentials = function() { + var env = process.env + return { + accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY, + secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY, + sessionToken: env.AWS_SESSION_TOKEN, + } +} -"use strict"; +RequestSigner.prototype.parsePath = function() { + var path = this.request.path || '/' -module.exports = function generate_multipleOf(it, $keyword, $ruleType) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $isData = it.opts.$data && $schema && $schema.$data, - $schemaValue; - if ($isData) { - out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; - $schemaValue = 'schema' + $lvl; - } else { - $schemaValue = $schema; - } - if (!($isData || typeof $schema == 'number')) { - throw new Error($keyword + ' must be number'); - } - out += 'var division' + ($lvl) + ';if ('; - if ($isData) { - out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || '; - } - out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', '; - if (it.opts.multipleOfPrecision) { - out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' '; - } else { - out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') '; - } - out += ' ) '; - if ($isData) { - out += ' ) '; - } - out += ' ) { '; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should be multiple of '; - if ($isData) { - out += '\' + ' + ($schemaValue); - } else { - out += '' + ($schemaValue) + '\''; - } - } - if (it.opts.verbose) { - out += ' , schema: '; - if ($isData) { - out += 'validate.schema' + ($schemaPath); - } else { - out += '' + ($schema); - } - out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; + // S3 doesn't always encode characters > 127 correctly and + // all services don't encode characters > 255 correctly + // So if there are non-reserved chars (and it's not already all % encoded), just encode them all + if (/[^0-9A-Za-z;,/?:@&=+$\-_.!~*'()#%]/.test(path)) { + path = encodeURI(decodeURI(path)) } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + + var queryIx = path.indexOf('?'), + query = null + + if (queryIx >= 0) { + query = querystring.parse(path.slice(queryIx + 1)) + path = path.slice(0, queryIx) } - out += '} '; - if ($breakOnError) { - out += ' else { '; + + this.parsedPath = { + path: path, + query: query, } - return out; +} + +RequestSigner.prototype.formatPath = function() { + var path = this.parsedPath.path, + query = this.parsedPath.query + + if (!query) return path + + // Services don't support empty query string keys + if (query[''] != null) delete query[''] + + return path + '?' + encodeRfc3986(querystring.stringify(query)) +} + +aws4.RequestSigner = RequestSigner + +aws4.sign = function(request, credentials) { + return new RequestSigner(request, credentials).sign() } /***/ }), -/***/ 60750: +/***/ 74225: /***/ ((module) => { -"use strict"; +module.exports = function(size) { + return new LruCache(size) +} -module.exports = function generate_not(it, $keyword, $ruleType) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $errs = 'errs__' + $lvl; - var $it = it.util.copy(it); - $it.level++; - var $nextValid = 'valid' + $it.level; - if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { - $it.schema = $schema; - $it.schemaPath = $schemaPath; - $it.errSchemaPath = $errSchemaPath; - out += ' var ' + ($errs) + ' = errors; '; - var $wasComposite = it.compositeRule; - it.compositeRule = $it.compositeRule = true; - $it.createErrors = false; - var $allErrorsOption; - if ($it.opts.allErrors) { - $allErrorsOption = $it.opts.allErrors; - $it.opts.allErrors = false; - } - out += ' ' + (it.validate($it)) + ' '; - $it.createErrors = true; - if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption; - it.compositeRule = $it.compositeRule = $wasComposite; - out += ' if (' + ($nextValid) + ') { '; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; - if (it.opts.messages !== false) { - out += ' , message: \'should NOT be valid\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; - if (it.opts.allErrors) { - out += ' } '; - } +function LruCache(size) { + this.capacity = size | 0 + this.map = Object.create(null) + this.list = new DoublyLinkedList() +} + +LruCache.prototype.get = function(key) { + var node = this.map[key] + if (node == null) return undefined + this.used(node) + return node.val +} + +LruCache.prototype.set = function(key, val) { + var node = this.map[key] + if (node != null) { + node.val = val } else { - out += ' var err = '; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; - if (it.opts.messages !== false) { - out += ' , message: \'should NOT be valid\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - if ($breakOnError) { - out += ' if (false) { '; - } + if (!this.capacity) this.prune() + if (!this.capacity) return false + node = new DoublyLinkedNode(key, val) + this.map[key] = node + this.capacity-- } - return out; + this.used(node) + return true } +LruCache.prototype.used = function(node) { + this.list.moveToFront(node) +} -/***/ }), +LruCache.prototype.prune = function() { + var node = this.list.pop() + if (node != null) { + delete this.map[node.key] + this.capacity++ + } +} -/***/ 6106: -/***/ ((module) => { -"use strict"; +function DoublyLinkedList() { + this.firstNode = null + this.lastNode = null +} -module.exports = function generate_oneOf(it, $keyword, $ruleType) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $valid = 'valid' + $lvl; - var $errs = 'errs__' + $lvl; - var $it = it.util.copy(it); - var $closingBraces = ''; - $it.level++; - var $nextValid = 'valid' + $it.level; - var $currentBaseId = $it.baseId, - $prevValid = 'prevValid' + $lvl, - $passingSchemas = 'passingSchemas' + $lvl; - out += 'var ' + ($errs) + ' = errors , ' + ($prevValid) + ' = false , ' + ($valid) + ' = false , ' + ($passingSchemas) + ' = null; '; - var $wasComposite = it.compositeRule; - it.compositeRule = $it.compositeRule = true; - var arr1 = $schema; - if (arr1) { - var $sch, $i = -1, - l1 = arr1.length - 1; - while ($i < l1) { - $sch = arr1[$i += 1]; - if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { - $it.schema = $sch; - $it.schemaPath = $schemaPath + '[' + $i + ']'; - $it.errSchemaPath = $errSchemaPath + '/' + $i; - out += ' ' + (it.validate($it)) + ' '; - $it.baseId = $currentBaseId; - } else { - out += ' var ' + ($nextValid) + ' = true; '; - } - if ($i) { - out += ' if (' + ($nextValid) + ' && ' + ($prevValid) + ') { ' + ($valid) + ' = false; ' + ($passingSchemas) + ' = [' + ($passingSchemas) + ', ' + ($i) + ']; } else { '; - $closingBraces += '}'; - } - out += ' if (' + ($nextValid) + ') { ' + ($valid) + ' = ' + ($prevValid) + ' = true; ' + ($passingSchemas) + ' = ' + ($i) + '; }'; - } - } - it.compositeRule = $it.compositeRule = $wasComposite; - out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { passingSchemas: ' + ($passingSchemas) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should match exactly one schema in oneOf\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; +DoublyLinkedList.prototype.moveToFront = function(node) { + if (this.firstNode == node) return + + this.remove(node) + + if (this.firstNode == null) { + this.firstNode = node + this.lastNode = node + node.prev = null + node.next = null } else { - out += ' {} '; + node.prev = null + node.next = this.firstNode + node.next.prev = node + this.firstNode = node } - out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError(vErrors); '; - } else { - out += ' validate.errors = vErrors; return false; '; - } +} + +DoublyLinkedList.prototype.pop = function() { + var lastNode = this.lastNode + if (lastNode != null) { + this.remove(lastNode) } - out += '} else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }'; - if (it.opts.allErrors) { - out += ' } '; + return lastNode +} + +DoublyLinkedList.prototype.remove = function(node) { + if (this.firstNode == node) { + this.firstNode = node.next + } else if (node.prev != null) { + node.prev.next = node.next } - return out; + if (this.lastNode == node) { + this.lastNode = node.prev + } else if (node.next != null) { + node.next.prev = node.prev + } +} + + +function DoublyLinkedNode(key, val) { + this.key = key + this.val = val + this.prev = null + this.next = null } /***/ }), -/***/ 13912: -/***/ ((module) => { +/***/ 91403: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -module.exports = function generate_pattern(it, $keyword, $ruleType) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $isData = it.opts.$data && $schema && $schema.$data, - $schemaValue; - if ($isData) { - out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; - $schemaValue = 'schema' + $lvl; - } else { - $schemaValue = $schema; + +var CombinedStream = __nccwpck_require__(85443); +var util = __nccwpck_require__(73837); +var path = __nccwpck_require__(71017); +var http = __nccwpck_require__(13685); +var https = __nccwpck_require__(95687); +var parseUrl = (__nccwpck_require__(57310).parse); +var fs = __nccwpck_require__(57147); +var Stream = (__nccwpck_require__(12781).Stream); +var crypto = __nccwpck_require__(6113); +var mime = __nccwpck_require__(43583); +var asynckit = __nccwpck_require__(14812); +var setToStringTag = __nccwpck_require__(11770); +var hasOwn = __nccwpck_require__(62157); +var populate = __nccwpck_require__(47027); + +/** + * Create readable "multipart/form-data" streams. + * Can be used to submit forms + * and file uploads to other web applications. + * + * @constructor + * @param {object} options - Properties to be added/overriden for FormData and CombinedStream + */ +function FormData(options) { + if (!(this instanceof FormData)) { + return new FormData(options); } - var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema); - out += 'if ( '; - if ($isData) { - out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; + + this._overheadLength = 0; + this._valueLength = 0; + this._valuesToMeasure = []; + + CombinedStream.call(this); + + options = options || {}; // eslint-disable-line no-param-reassign + for (var option in options) { // eslint-disable-line no-restricted-syntax + this[option] = options[option]; } - out += ' !' + ($regexp) + '.test(' + ($data) + ') ) { '; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern: '; - if ($isData) { - out += '' + ($schemaValue); - } else { - out += '' + (it.util.toQuotedString($schema)); - } - out += ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should match pattern "'; - if ($isData) { - out += '\' + ' + ($schemaValue) + ' + \''; - } else { - out += '' + (it.util.escapeQuotes($schema)); - } - out += '"\' '; - } - if (it.opts.verbose) { - out += ' , schema: '; - if ($isData) { - out += 'validate.schema' + ($schemaPath); - } else { - out += '' + (it.util.toQuotedString($schema)); - } - out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; +} + +// make it a Stream +util.inherits(FormData, CombinedStream); + +FormData.LINE_BREAK = '\r\n'; +FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; + +FormData.prototype.append = function (field, value, options) { + options = options || {}; // eslint-disable-line no-param-reassign + + // allow filename as single option + if (typeof options === 'string') { + options = { filename: options }; // eslint-disable-line no-param-reassign } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + + var append = CombinedStream.prototype.append.bind(this); + + // all that streamy business can't handle numbers + if (typeof value === 'number' || value == null) { + value = String(value); // eslint-disable-line no-param-reassign } - out += '} '; - if ($breakOnError) { - out += ' else { '; + + // https://github.com/felixge/node-form-data/issues/38 + if (Array.isArray(value)) { + /* + * Please convert your array into string + * the way web server expects it + */ + this._error(new Error('Arrays are not supported.')); + return; } - return out; -} + var header = this._multiPartHeader(field, value, options); + var footer = this._multiPartFooter(); -/***/ }), + append(header); + append(value); + append(footer); -/***/ 52924: -/***/ ((module) => { + // pass along options.knownLength + this._trackLength(header, value, options); +}; -"use strict"; +FormData.prototype._trackLength = function (header, value, options) { + var valueLength = 0; -module.exports = function generate_properties(it, $keyword, $ruleType) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $errs = 'errs__' + $lvl; - var $it = it.util.copy(it); - var $closingBraces = ''; - $it.level++; - var $nextValid = 'valid' + $it.level; - var $key = 'key' + $lvl, - $idx = 'idx' + $lvl, - $dataNxt = $it.dataLevel = it.dataLevel + 1, - $nextData = 'data' + $dataNxt, - $dataProperties = 'dataProperties' + $lvl; - var $schemaKeys = Object.keys($schema || {}).filter(notProto), - $pProperties = it.schema.patternProperties || {}, - $pPropertyKeys = Object.keys($pProperties).filter(notProto), - $aProperties = it.schema.additionalProperties, - $someProperties = $schemaKeys.length || $pPropertyKeys.length, - $noAdditional = $aProperties === false, - $additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length, - $removeAdditional = it.opts.removeAdditional, - $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional, - $ownProperties = it.opts.ownProperties, - $currentBaseId = it.baseId; - var $required = it.schema.required; - if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) { - var $requiredHash = it.util.toHash($required); + /* + * used w/ getLengthSync(), when length is known. + * e.g. for streaming directly from a remote server, + * w/ a known file a size, and not wanting to wait for + * incoming file to finish to get its size. + */ + if (options.knownLength != null) { + valueLength += Number(options.knownLength); + } else if (Buffer.isBuffer(value)) { + valueLength = value.length; + } else if (typeof value === 'string') { + valueLength = Buffer.byteLength(value); } - function notProto(p) { - return p !== '__proto__'; + this._valueLength += valueLength; + + // @check why add CRLF? does this account for custom/multiple CRLFs? + this._overheadLength += Buffer.byteLength(header) + FormData.LINE_BREAK.length; + + // empty or either doesn't have path or not an http response or not a stream + if (!value || (!value.path && !(value.readable && hasOwn(value, 'httpVersion')) && !(value instanceof Stream))) { + return; } - out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;'; - if ($ownProperties) { - out += ' var ' + ($dataProperties) + ' = undefined;'; + + // no need to bother with the length + if (!options.knownLength) { + this._valuesToMeasure.push(value); } - if ($checkAdditional) { - if ($ownProperties) { - out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; +}; + +FormData.prototype._lengthRetriever = function (value, callback) { + if (hasOwn(value, 'fd')) { + // take read range into a account + // `end` = Infinity –> read file till the end + // + // TODO: Looks like there is bug in Node fs.createReadStream + // it doesn't respect `end` options without `start` options + // Fix it when node fixes it. + // https://github.com/joyent/node/issues/7819 + if (value.end != undefined && value.end != Infinity && value.start != undefined) { + // when end specified + // no need to calculate range + // inclusive, starts with 0 + callback(null, value.end + 1 - (value.start ? value.start : 0)); // eslint-disable-line callback-return + + // not that fast snoopy } else { - out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; - } - if ($someProperties) { - out += ' var isAdditional' + ($lvl) + ' = !(false '; - if ($schemaKeys.length) { - if ($schemaKeys.length > 8) { - out += ' || validate.schema' + ($schemaPath) + '.hasOwnProperty(' + ($key) + ') '; - } else { - var arr1 = $schemaKeys; - if (arr1) { - var $propertyKey, i1 = -1, - l1 = arr1.length - 1; - while (i1 < l1) { - $propertyKey = arr1[i1 += 1]; - out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' '; - } - } - } - } - if ($pPropertyKeys.length) { - var arr2 = $pPropertyKeys; - if (arr2) { - var $pProperty, $i = -1, - l2 = arr2.length - 1; - while ($i < l2) { - $pProperty = arr2[$i += 1]; - out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') '; - } + // still need to fetch file size from fs + fs.stat(value.path, function (err, stat) { + if (err) { + callback(err); + return; } - } - out += ' ); if (isAdditional' + ($lvl) + ') { '; + + // update final size based on the range options + var fileSize = stat.size - (value.start ? value.start : 0); + callback(null, fileSize); + }); } - if ($removeAdditional == 'all') { - out += ' delete ' + ($data) + '[' + ($key) + ']; '; - } else { - var $currentErrorPath = it.errorPath; - var $additionalProperty = '\' + ' + $key + ' + \''; - if (it.opts._errorDataPathProperty) { - it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + + // or http response + } else if (hasOwn(value, 'httpVersion')) { + callback(null, Number(value.headers['content-length'])); // eslint-disable-line callback-return + + // or request stream http://github.com/mikeal/request + } else if (hasOwn(value, 'httpModule')) { + // wait till response come back + value.on('response', function (response) { + value.pause(); + callback(null, Number(response.headers['content-length'])); + }); + value.resume(); + + // something else + } else { + callback('Unknown stream'); // eslint-disable-line callback-return + } +}; + +FormData.prototype._multiPartHeader = function (field, value, options) { + /* + * custom header specified (as string)? + * it becomes responsible for boundary + * (e.g. to handle extra CRLFs on .NET servers) + */ + if (typeof options.header === 'string') { + return options.header; + } + + var contentDisposition = this._getContentDisposition(value, options); + var contentType = this._getContentType(value, options); + + var contents = ''; + var headers = { + // add custom disposition as third element or keep it two elements if not + 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), + // if no content type. allow it to be empty array + 'Content-Type': [].concat(contentType || []) + }; + + // allow custom headers. + if (typeof options.header === 'object') { + populate(headers, options.header); + } + + var header; + for (var prop in headers) { // eslint-disable-line no-restricted-syntax + if (hasOwn(headers, prop)) { + header = headers[prop]; + + // skip nullish headers. + if (header == null) { + continue; // eslint-disable-line no-restricted-syntax, no-continue } - if ($noAdditional) { - if ($removeAdditional) { - out += ' delete ' + ($data) + '[' + ($key) + ']; '; - } else { - out += ' ' + ($nextValid) + ' = false; '; - var $currErrSchemaPath = $errSchemaPath; - $errSchemaPath = it.errSchemaPath + '/additionalProperties'; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \''; - if (it.opts._errorDataPathProperty) { - out += 'is an invalid additional property'; - } else { - out += 'should NOT have additional properties'; - } - out += '\' '; - } - if (it.opts.verbose) { - out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - $errSchemaPath = $currErrSchemaPath; - if ($breakOnError) { - out += ' break; '; - } - } - } else if ($additionalIsSchema) { - if ($removeAdditional == 'failing') { - out += ' var ' + ($errs) + ' = errors; '; - var $wasComposite = it.compositeRule; - it.compositeRule = $it.compositeRule = true; - $it.schema = $aProperties; - $it.schemaPath = it.schemaPath + '.additionalProperties'; - $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; - $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); - var $passData = $data + '[' + $key + ']'; - $it.dataPathArr[$dataNxt] = $key; - var $code = it.validate($it); - $it.baseId = $currentBaseId; - if (it.util.varOccurences($code, $nextData) < 2) { - out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; - } else { - out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; - } - out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; } '; - it.compositeRule = $it.compositeRule = $wasComposite; - } else { - $it.schema = $aProperties; - $it.schemaPath = it.schemaPath + '.additionalProperties'; - $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; - $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); - var $passData = $data + '[' + $key + ']'; - $it.dataPathArr[$dataNxt] = $key; - var $code = it.validate($it); - $it.baseId = $currentBaseId; - if (it.util.varOccurences($code, $nextData) < 2) { - out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; - } else { - out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; - } - if ($breakOnError) { - out += ' if (!' + ($nextValid) + ') break; '; - } - } + + // convert all headers to arrays. + if (!Array.isArray(header)) { + header = [header]; + } + + // add non-empty headers. + if (header.length) { + contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; } - it.errorPath = $currentErrorPath; - } - if ($someProperties) { - out += ' } '; - } - out += ' } '; - if ($breakOnError) { - out += ' if (' + ($nextValid) + ') { '; - $closingBraces += '}'; } } - var $useDefaults = it.opts.useDefaults && !it.compositeRule; - if ($schemaKeys.length) { - var arr3 = $schemaKeys; - if (arr3) { - var $propertyKey, i3 = -1, - l3 = arr3.length - 1; - while (i3 < l3) { - $propertyKey = arr3[i3 += 1]; - var $sch = $schema[$propertyKey]; - if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { - var $prop = it.util.getProperty($propertyKey), - $passData = $data + $prop, - $hasDefault = $useDefaults && $sch.default !== undefined; - $it.schema = $sch; - $it.schemaPath = $schemaPath + $prop; - $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey); - $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers); - $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey); - var $code = it.validate($it); - $it.baseId = $currentBaseId; - if (it.util.varOccurences($code, $nextData) < 2) { - $code = it.util.varReplace($code, $nextData, $passData); - var $useData = $passData; - } else { - var $useData = $nextData; - out += ' var ' + ($nextData) + ' = ' + ($passData) + '; '; - } - if ($hasDefault) { - out += ' ' + ($code) + ' '; - } else { - if ($requiredHash && $requiredHash[$propertyKey]) { - out += ' if ( ' + ($useData) + ' === undefined '; - if ($ownProperties) { - out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; - } - out += ') { ' + ($nextValid) + ' = false; '; - var $currentErrorPath = it.errorPath, - $currErrSchemaPath = $errSchemaPath, - $missingProperty = it.util.escapeQuotes($propertyKey); - if (it.opts._errorDataPathProperty) { - it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); - } - $errSchemaPath = it.errSchemaPath + '/required'; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \''; - if (it.opts._errorDataPathProperty) { - out += 'is a required property'; - } else { - out += 'should have required property \\\'' + ($missingProperty) + '\\\''; - } - out += '\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - $errSchemaPath = $currErrSchemaPath; - it.errorPath = $currentErrorPath; - out += ' } else { '; - } else { - if ($breakOnError) { - out += ' if ( ' + ($useData) + ' === undefined '; - if ($ownProperties) { - out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; - } - out += ') { ' + ($nextValid) + ' = true; } else { '; - } else { - out += ' if (' + ($useData) + ' !== undefined '; - if ($ownProperties) { - out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; - } - out += ' ) { '; - } - } - out += ' ' + ($code) + ' } '; - } - } - if ($breakOnError) { - out += ' if (' + ($nextValid) + ') { '; - $closingBraces += '}'; - } - } + + return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; +}; + +FormData.prototype._getContentDisposition = function (value, options) { // eslint-disable-line consistent-return + var filename; + + if (typeof options.filepath === 'string') { + // custom filepath for relative paths + filename = path.normalize(options.filepath).replace(/\\/g, '/'); + } else if (options.filename || (value && (value.name || value.path))) { + /* + * custom filename take precedence + * formidable and the browser add a name property + * fs- and request- streams have path property + */ + filename = path.basename(options.filename || (value && (value.name || value.path))); + } else if (value && value.readable && hasOwn(value, 'httpVersion')) { + // or try http response + filename = path.basename(value.client._httpMessage.path || ''); + } + + if (filename) { + return 'filename="' + filename + '"'; + } +}; + +FormData.prototype._getContentType = function (value, options) { + // use custom content-type above all + var contentType = options.contentType; + + // or try `name` from formidable, browser + if (!contentType && value && value.name) { + contentType = mime.lookup(value.name); + } + + // or try `path` from fs-, request- streams + if (!contentType && value && value.path) { + contentType = mime.lookup(value.path); + } + + // or if it's http-reponse + if (!contentType && value && value.readable && hasOwn(value, 'httpVersion')) { + contentType = value.headers['content-type']; + } + + // or guess it from the filepath or filename + if (!contentType && (options.filepath || options.filename)) { + contentType = mime.lookup(options.filepath || options.filename); + } + + // fallback to the default content type if `value` is not simple value + if (!contentType && value && typeof value === 'object') { + contentType = FormData.DEFAULT_CONTENT_TYPE; + } + + return contentType; +}; + +FormData.prototype._multiPartFooter = function () { + return function (next) { + var footer = FormData.LINE_BREAK; + + var lastPart = this._streams.length === 0; + if (lastPart) { + footer += this._lastBoundary(); + } + + next(footer); + }.bind(this); +}; + +FormData.prototype._lastBoundary = function () { + return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; +}; + +FormData.prototype.getHeaders = function (userHeaders) { + var header; + var formHeaders = { + 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() + }; + + for (header in userHeaders) { // eslint-disable-line no-restricted-syntax + if (hasOwn(userHeaders, header)) { + formHeaders[header.toLowerCase()] = userHeaders[header]; } } - if ($pPropertyKeys.length) { - var arr4 = $pPropertyKeys; - if (arr4) { - var $pProperty, i4 = -1, - l4 = arr4.length - 1; - while (i4 < l4) { - $pProperty = arr4[i4 += 1]; - var $sch = $pProperties[$pProperty]; - if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { - $it.schema = $sch; - $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty); - $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty); - if ($ownProperties) { - out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; - } else { - out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; - } - out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { '; - $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); - var $passData = $data + '[' + $key + ']'; - $it.dataPathArr[$dataNxt] = $key; - var $code = it.validate($it); - $it.baseId = $currentBaseId; - if (it.util.varOccurences($code, $nextData) < 2) { - out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; - } else { - out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; - } - if ($breakOnError) { - out += ' if (!' + ($nextValid) + ') break; '; - } - out += ' } '; - if ($breakOnError) { - out += ' else ' + ($nextValid) + ' = true; '; - } - out += ' } '; - if ($breakOnError) { - out += ' if (' + ($nextValid) + ') { '; - $closingBraces += '}'; - } - } + + return formHeaders; +}; + +FormData.prototype.setBoundary = function (boundary) { + if (typeof boundary !== 'string') { + throw new TypeError('FormData boundary must be a string'); + } + this._boundary = boundary; +}; + +FormData.prototype.getBoundary = function () { + if (!this._boundary) { + this._generateBoundary(); + } + + return this._boundary; +}; + +FormData.prototype.getBuffer = function () { + var dataBuffer = new Buffer.alloc(0); // eslint-disable-line new-cap + var boundary = this.getBoundary(); + + // Create the form content. Add Line breaks to the end of data. + for (var i = 0, len = this._streams.length; i < len; i++) { + if (typeof this._streams[i] !== 'function') { + // Add content to the buffer. + if (Buffer.isBuffer(this._streams[i])) { + dataBuffer = Buffer.concat([dataBuffer, this._streams[i]]); + } else { + dataBuffer = Buffer.concat([dataBuffer, Buffer.from(this._streams[i])]); + } + + // Add break after content. + if (typeof this._streams[i] !== 'string' || this._streams[i].substring(2, boundary.length + 2) !== boundary) { + dataBuffer = Buffer.concat([dataBuffer, Buffer.from(FormData.LINE_BREAK)]); } } } - if ($breakOnError) { - out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + + // Add the footer and return the Buffer object. + return Buffer.concat([dataBuffer, Buffer.from(this._lastBoundary())]); +}; + +FormData.prototype._generateBoundary = function () { + // This generates a 50 character boundary similar to those used by Firefox. + + // They are optimized for boyer-moore parsing. + this._boundary = '--------------------------' + crypto.randomBytes(12).toString('hex'); +}; + +// Note: getLengthSync DOESN'T calculate streams length +// As workaround one can calculate file size manually and add it as knownLength option +FormData.prototype.getLengthSync = function () { + var knownLength = this._overheadLength + this._valueLength; + + // Don't get confused, there are 3 "internal" streams for each keyval pair so it basically checks if there is any value added to the form + if (this._streams.length) { + knownLength += this._lastBoundary().length; } - return out; -} + // https://github.com/form-data/form-data/issues/40 + if (!this.hasKnownLength()) { + /* + * Some async length retrievers are present + * therefore synchronous length calculation is false. + * Please use getLength(callback) to get proper length + */ + this._error(new Error('Cannot calculate proper length in synchronous way.')); + } -/***/ }), + return knownLength; +}; -/***/ 19195: -/***/ ((module) => { +// Public API to check if length of added values is known +// https://github.com/form-data/form-data/issues/196 +// https://github.com/form-data/form-data/issues/262 +FormData.prototype.hasKnownLength = function () { + var hasKnownLength = true; -"use strict"; + if (this._valuesToMeasure.length) { + hasKnownLength = false; + } -module.exports = function generate_propertyNames(it, $keyword, $ruleType) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $errs = 'errs__' + $lvl; - var $it = it.util.copy(it); - var $closingBraces = ''; - $it.level++; - var $nextValid = 'valid' + $it.level; - out += 'var ' + ($errs) + ' = errors;'; - if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { - $it.schema = $schema; - $it.schemaPath = $schemaPath; - $it.errSchemaPath = $errSchemaPath; - var $key = 'key' + $lvl, - $idx = 'idx' + $lvl, - $i = 'i' + $lvl, - $invalidName = '\' + ' + $key + ' + \'', - $dataNxt = $it.dataLevel = it.dataLevel + 1, - $nextData = 'data' + $dataNxt, - $dataProperties = 'dataProperties' + $lvl, - $ownProperties = it.opts.ownProperties, - $currentBaseId = it.baseId; - if ($ownProperties) { - out += ' var ' + ($dataProperties) + ' = undefined; '; - } - if ($ownProperties) { - out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; - } else { - out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + return hasKnownLength; +}; + +FormData.prototype.getLength = function (cb) { + var knownLength = this._overheadLength + this._valueLength; + + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } + + if (!this._valuesToMeasure.length) { + process.nextTick(cb.bind(this, null, knownLength)); + return; + } + + asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function (err, values) { + if (err) { + cb(err); + return; } - out += ' var startErrs' + ($lvl) + ' = errors; '; - var $passData = $key; - var $wasComposite = it.compositeRule; - it.compositeRule = $it.compositeRule = true; - var $code = it.validate($it); - $it.baseId = $currentBaseId; - if (it.util.varOccurences($code, $nextData) < 2) { - out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; - } else { - out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + + values.forEach(function (length) { + knownLength += length; + }); + + cb(null, knownLength); + }); +}; + +FormData.prototype.submit = function (params, cb) { + var request; + var options; + var defaults = { method: 'post' }; + + // parse provided url if it's string or treat it as options object + if (typeof params === 'string') { + params = parseUrl(params); // eslint-disable-line no-param-reassign + /* eslint sort-keys: 0 */ + options = populate({ + port: params.port, + path: params.pathname, + host: params.hostname, + protocol: params.protocol + }, defaults); + } else { // use custom params + options = populate(params, defaults); + // if no port provided use default one + if (!options.port) { + options.port = options.protocol === 'https:' ? 443 : 80; } - it.compositeRule = $it.compositeRule = $wasComposite; - out += ' if (!' + ($nextValid) + ') { for (var ' + ($i) + '=startErrs' + ($lvl) + '; ' + ($i) + ' { "use strict"; -module.exports = function generate_ref(it, $keyword, $ruleType) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $valid = 'valid' + $lvl; - var $async, $refCode; - if ($schema == '#' || $schema == '#/') { - if (it.isRoot) { - $async = it.async; - $refCode = 'validate'; - } else { - $async = it.root.schema.$async === true; - $refCode = 'root.refVal[0]'; + +// populates missing values +module.exports = function (dst, src) { + Object.keys(src).forEach(function (prop) { + dst[prop] = dst[prop] || src[prop]; // eslint-disable-line no-param-reassign + }); + + return dst; +}; + + +/***/ }), + +/***/ 9417: +/***/ ((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]; } - } else { - var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot); - if ($refVal === undefined) { - var $message = it.MissingRefError.message(it.baseId, $schema); - if (it.opts.missingRefs == 'fail') { - it.logger.error($message); - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('$ref') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { ref: \'' + (it.util.escapeQuotes($schema)) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \'can\\\'t resolve reference ' + (it.util.escapeQuotes($schema)) + '\' '; - } - if (it.opts.verbose) { - out += ' , schema: ' + (it.util.toQuotedString($schema)) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - if ($breakOnError) { - out += ' if (false) { '; - } - } else if (it.opts.missingRefs == 'ignore') { - it.logger.warn($message); - if ($breakOnError) { - out += ' if (true) { '; - } + 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 { - throw new it.MissingRefError(it.baseId, $schema, $message); - } - } else if ($refVal.inline) { - var $it = it.util.copy(it); - $it.level++; - var $nextValid = 'valid' + $it.level; - $it.schema = $refVal.schema; - $it.schemaPath = ''; - $it.errSchemaPath = $schema; - var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code); - out += ' ' + ($code) + ' '; - if ($breakOnError) { - out += ' if (' + ($nextValid) + ') { '; + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; + } + + bi = str.indexOf(b, i + 1); } - } else { - $async = $refVal.$async === true || (it.async && $refVal.$async !== false); - $refCode = $refVal.code; - } - } - if ($refCode) { - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; - if (it.opts.passContext) { - out += ' ' + ($refCode) + '.call(this, '; - } else { - out += ' ' + ($refCode) + '( '; - } - out += ' ' + ($data) + ', (dataPath || \'\')'; - if (it.errorPath != '""') { - out += ' + ' + (it.errorPath); + + i = ai < bi && ai >= 0 ? ai : bi; } - var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', - $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; - out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ', rootData) '; - var __callValidate = out; - out = $$outStack.pop(); - if ($async) { - if (!it.async) throw new Error('async schema referenced by sync schema'); - if ($breakOnError) { - out += ' var ' + ($valid) + '; '; - } - out += ' try { await ' + (__callValidate) + '; '; - if ($breakOnError) { - out += ' ' + ($valid) + ' = true; '; - } - out += ' } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; '; - if ($breakOnError) { - out += ' ' + ($valid) + ' = false; '; - } - out += ' } '; - if ($breakOnError) { - out += ' if (' + ($valid) + ') { '; - } - } else { - out += ' if (!' + (__callValidate) + ') { if (vErrors === null) vErrors = ' + ($refCode) + '.errors; else vErrors = vErrors.concat(' + ($refCode) + '.errors); errors = vErrors.length; } '; - if ($breakOnError) { - out += ' else { '; - } + + if (begs.length) { + result = [ left, right ]; } } - return out; -} + return result; +} + + +/***/ }), + +/***/ 85848: +/***/ (function(module, exports, __nccwpck_require__) { + +/* module decorator */ module = __nccwpck_require__.nmd(module); +/*! https://mths.be/base64 v1.0.0 by @mathias | MIT license */ +;(function(root) { + + // Detect free variables `exports`. + var freeExports = true && exports; + + // Detect free variable `module`. + var freeModule = true && module && + module.exports == freeExports && module; + + // Detect free variable `global`, from Node.js or Browserified code, and use + // it as `root`. + var freeGlobal = typeof global == 'object' && global; + if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { + root = freeGlobal; + } + + /*--------------------------------------------------------------------------*/ + + var InvalidCharacterError = function(message) { + this.message = message; + }; + InvalidCharacterError.prototype = new Error; + InvalidCharacterError.prototype.name = 'InvalidCharacterError'; + + var error = function(message) { + // Note: the error messages used throughout this file match those used by + // the native `atob`/`btoa` implementation in Chromium. + throw new InvalidCharacterError(message); + }; + + var TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + // http://whatwg.org/html/common-microsyntaxes.html#space-character + var REGEX_SPACE_CHARACTERS = /[\t\n\f\r ]/g; + + // `decode` is designed to be fully compatible with `atob` as described in the + // HTML Standard. http://whatwg.org/html/webappapis.html#dom-windowbase64-atob + // The optimized base64-decoding algorithm used is based on @atk’s excellent + // implementation. https://gist.github.com/atk/1020396 + var decode = function(input) { + input = String(input) + .replace(REGEX_SPACE_CHARACTERS, ''); + var length = input.length; + if (length % 4 == 0) { + input = input.replace(/==?$/, ''); + length = input.length; + } + if ( + length % 4 == 1 || + // http://whatwg.org/C#alphanumeric-ascii-characters + /[^+a-zA-Z0-9/]/.test(input) + ) { + error( + 'Invalid character: the string to be decoded is not correctly encoded.' + ); + } + var bitCounter = 0; + var bitStorage; + var buffer; + var output = ''; + var position = -1; + while (++position < length) { + buffer = TABLE.indexOf(input.charAt(position)); + bitStorage = bitCounter % 4 ? bitStorage * 64 + buffer : buffer; + // Unless this is the first of a group of 4 characters… + if (bitCounter++ % 4) { + // …convert the first 8 bits to a single ASCII character. + output += String.fromCharCode( + 0xFF & bitStorage >> (-2 * bitCounter & 6) + ); + } + } + return output; + }; + + // `encode` is designed to be fully compatible with `btoa` as described in the + // HTML Standard: http://whatwg.org/html/webappapis.html#dom-windowbase64-btoa + var encode = function(input) { + input = String(input); + if (/[^\0-\xFF]/.test(input)) { + // Note: no need to special-case astral symbols here, as surrogates are + // matched, and the input is supposed to only contain ASCII anyway. + error( + 'The string to be encoded contains characters outside of the ' + + 'Latin1 range.' + ); + } + var padding = input.length % 3; + var output = ''; + var position = -1; + var a; + var b; + var c; + var buffer; + // Make sure any padding is handled outside of the loop. + var length = input.length - padding; + + while (++position < length) { + // Read three bytes, i.e. 24 bits. + a = input.charCodeAt(position) << 16; + b = input.charCodeAt(++position) << 8; + c = input.charCodeAt(++position); + buffer = a + b + c; + // Turn the 24 bits into four chunks of 6 bits each, and append the + // matching character for each of them to the output. + output += ( + TABLE.charAt(buffer >> 18 & 0x3F) + + TABLE.charAt(buffer >> 12 & 0x3F) + + TABLE.charAt(buffer >> 6 & 0x3F) + + TABLE.charAt(buffer & 0x3F) + ); + } + + if (padding == 2) { + a = input.charCodeAt(position) << 8; + b = input.charCodeAt(++position); + buffer = a + b; + output += ( + TABLE.charAt(buffer >> 10) + + TABLE.charAt((buffer >> 4) & 0x3F) + + TABLE.charAt((buffer << 2) & 0x3F) + + '=' + ); + } else if (padding == 1) { + buffer = input.charCodeAt(position); + output += ( + TABLE.charAt(buffer >> 2) + + TABLE.charAt((buffer << 4) & 0x3F) + + '==' + ); + } + + return output; + }; + + var base64 = { + 'encode': encode, + 'decode': decode, + 'version': '1.0.0' + }; + + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define(function() { + return base64; + }); + } else if (freeExports && !freeExports.nodeType) { + if (freeModule) { // in Node.js or RingoJS v0.8.0+ + freeModule.exports = base64; + } else { // in Narwhal or RingoJS v0.7.0- + for (var key in base64) { + base64.hasOwnProperty(key) && (freeExports[key] = base64[key]); + } + } + } else { // in Rhino or a web browser + root.base64 = base64; + } + +}(this)); + + +/***/ }), + +/***/ 45447: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var crypto_hash_sha512 = (__nccwpck_require__(68729).lowlevel.crypto_hash); + +/* + * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a + * result, it retains the original copyright and license. The two files are + * under slightly different (but compatible) licenses, and are here combined in + * one file. + * + * Credit for the actual porting work goes to: + * Devi Mandiri + */ + +/* + * The Blowfish portions are under the following license: + * + * Blowfish block cipher for OpenBSD + * Copyright 1997 Niels Provos + * All rights reserved. + * + * Implementation advice by David Mazieres . + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * The bcrypt_pbkdf portions are under the following license: + * + * Copyright (c) 2013 Ted Unangst + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/* + * Performance improvements (Javascript-specific): + * + * Copyright 2016, Joyent Inc + * Author: Alex Wilson + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +// Ported from OpenBSD bcrypt_pbkdf.c v1.9 + +var BLF_J = 0; + +var Blowfish = function() { + this.S = [ + new Uint32Array([ + 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, + 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, + 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, + 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, + 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, + 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, + 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, + 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, + 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, + 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, + 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, + 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, + 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, + 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, + 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, + 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, + 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, + 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, + 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, + 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, + 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, + 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, + 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, + 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, + 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, + 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, + 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, + 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, + 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, + 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, + 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, + 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, + 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, + 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, + 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, + 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, + 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, + 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, + 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, + 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, + 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, + 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, + 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, + 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, + 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, + 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, + 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, + 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, + 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, + 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, + 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, + 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, + 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, + 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, + 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, + 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, + 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, + 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, + 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, + 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, + 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, + 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, + 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, + 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a]), + new Uint32Array([ + 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, + 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, + 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, + 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, + 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, + 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, + 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, + 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, + 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, + 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, + 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, + 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, + 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, + 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, + 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, + 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, + 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, + 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, + 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, + 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, + 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, + 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, + 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, + 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, + 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, + 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, + 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, + 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, + 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, + 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, + 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, + 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, + 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, + 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, + 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, + 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, + 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, + 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, + 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, + 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, + 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, + 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, + 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, + 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, + 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, + 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, + 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, + 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, + 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, + 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, + 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, + 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, + 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, + 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, + 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, + 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, + 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, + 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, + 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, + 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, + 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, + 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, + 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, + 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7]), + new Uint32Array([ + 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, + 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, + 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, + 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, + 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, + 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, + 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, + 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, + 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, + 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, + 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, + 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, + 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, + 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, + 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, + 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, + 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, + 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, + 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, + 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, + 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, + 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, + 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, + 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, + 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, + 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, + 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, + 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, + 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, + 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, + 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, + 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, + 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, + 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, + 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, + 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, + 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, + 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, + 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, + 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, + 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, + 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, + 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, + 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, + 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, + 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, + 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, + 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, + 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, + 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, + 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, + 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, + 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, + 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, + 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, + 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, + 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, + 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, + 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, + 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, + 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, + 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, + 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, + 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0]), + new Uint32Array([ + 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, + 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, + 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, + 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, + 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, + 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, + 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, + 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, + 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, + 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, + 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, + 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, + 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, + 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, + 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, + 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, + 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, + 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, + 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, + 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, + 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, + 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, + 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, + 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, + 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, + 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, + 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, + 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, + 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, + 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, + 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, + 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, + 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, + 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, + 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, + 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, + 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, + 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, + 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, + 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, + 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, + 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, + 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, + 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, + 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, + 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, + 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, + 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, + 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, + 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, + 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, + 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, + 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, + 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, + 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, + 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, + 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, + 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, + 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, + 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, + 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, + 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, + 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, + 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6]) + ]; + this.P = new Uint32Array([ + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, + 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, + 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, + 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, + 0x9216d5d9, 0x8979fb1b]); +}; + +function F(S, x8, i) { + return (((S[0][x8[i+3]] + + S[1][x8[i+2]]) ^ + S[2][x8[i+1]]) + + S[3][x8[i]]); +}; + +Blowfish.prototype.encipher = function(x, x8) { + if (x8 === undefined) { + x8 = new Uint8Array(x.buffer); + if (x.byteOffset !== 0) + x8 = x8.subarray(x.byteOffset); + } + x[0] ^= this.P[0]; + for (var i = 1; i < 16; i += 2) { + x[1] ^= F(this.S, x8, 0) ^ this.P[i]; + x[0] ^= F(this.S, x8, 4) ^ this.P[i+1]; + } + var t = x[0]; + x[0] = x[1] ^ this.P[17]; + x[1] = t; +}; + +Blowfish.prototype.decipher = function(x) { + var x8 = new Uint8Array(x.buffer); + if (x.byteOffset !== 0) + x8 = x8.subarray(x.byteOffset); + x[0] ^= this.P[17]; + for (var i = 16; i > 0; i -= 2) { + x[1] ^= F(this.S, x8, 0) ^ this.P[i]; + x[0] ^= F(this.S, x8, 4) ^ this.P[i-1]; + } + var t = x[0]; + x[0] = x[1] ^ this.P[0]; + x[1] = t; +}; -/***/ }), +function stream2word(data, databytes){ + var i, temp = 0; + for (i = 0; i < 4; i++, BLF_J++) { + if (BLF_J >= databytes) BLF_J = 0; + temp = (temp << 8) | data[BLF_J]; + } + return temp; +}; -/***/ 8420: -/***/ ((module) => { +Blowfish.prototype.expand0state = function(key, keybytes) { + var d = new Uint32Array(2), i, k; + var d8 = new Uint8Array(d.buffer); -"use strict"; + for (i = 0, BLF_J = 0; i < 18; i++) { + this.P[i] ^= stream2word(key, keybytes); + } + BLF_J = 0; -module.exports = function generate_required(it, $keyword, $ruleType) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $valid = 'valid' + $lvl; - var $isData = it.opts.$data && $schema && $schema.$data, - $schemaValue; - if ($isData) { - out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; - $schemaValue = 'schema' + $lvl; - } else { - $schemaValue = $schema; + for (i = 0; i < 18; i += 2) { + this.encipher(d, d8); + this.P[i] = d[0]; + this.P[i+1] = d[1]; } - var $vSchema = 'schema' + $lvl; - if (!$isData) { - if ($schema.length < it.opts.loopRequired && it.schema.properties && Object.keys(it.schema.properties).length) { - var $required = []; - var arr1 = $schema; - if (arr1) { - var $property, i1 = -1, - l1 = arr1.length - 1; - while (i1 < l1) { - $property = arr1[i1 += 1]; - var $propertySch = it.schema.properties[$property]; - if (!($propertySch && (it.opts.strictKeywords ? (typeof $propertySch == 'object' && Object.keys($propertySch).length > 0) || $propertySch === false : it.util.schemaHasRules($propertySch, it.RULES.all)))) { - $required[$required.length] = $property; - } - } - } - } else { - var $required = $schema; + + for (i = 0; i < 4; i++) { + for (k = 0; k < 256; k += 2) { + this.encipher(d, d8); + this.S[i][k] = d[0]; + this.S[i][k+1] = d[1]; } } - if ($isData || $required.length) { - var $currentErrorPath = it.errorPath, - $loopRequired = $isData || $required.length >= it.opts.loopRequired, - $ownProperties = it.opts.ownProperties; - if ($breakOnError) { - out += ' var missing' + ($lvl) + '; '; - if ($loopRequired) { - if (!$isData) { - out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; - } - var $i = 'i' + $lvl, - $propertyPath = 'schema' + $lvl + '[' + $i + ']', - $missingProperty = '\' + ' + $propertyPath + ' + \''; - if (it.opts._errorDataPathProperty) { - it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); - } - out += ' var ' + ($valid) + ' = true; '; - if ($isData) { - out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; - } - out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined '; - if ($ownProperties) { - out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) '; - } - out += '; if (!' + ($valid) + ') break; } '; - if ($isData) { - out += ' } '; - } - out += ' if (!' + ($valid) + ') { '; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \''; - if (it.opts._errorDataPathProperty) { - out += 'is a required property'; - } else { - out += 'should have required property \\\'' + ($missingProperty) + '\\\''; - } - out += '\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += ' } else { '; - } else { - out += ' if ( '; - var arr2 = $required; - if (arr2) { - var $propertyKey, $i = -1, - l2 = arr2.length - 1; - while ($i < l2) { - $propertyKey = arr2[$i += 1]; - if ($i) { - out += ' || '; - } - var $prop = it.util.getProperty($propertyKey), - $useData = $data + $prop; - out += ' ( ( ' + ($useData) + ' === undefined '; - if ($ownProperties) { - out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; - } - out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) '; - } - } - out += ') { '; - var $propertyPath = 'missing' + $lvl, - $missingProperty = '\' + ' + $propertyPath + ' + \''; - if (it.opts._errorDataPathProperty) { - it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; - } - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \''; - if (it.opts._errorDataPathProperty) { - out += 'is a required property'; - } else { - out += 'should have required property \\\'' + ($missingProperty) + '\\\''; - } - out += '\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += ' } else { '; - } - } else { - if ($loopRequired) { - if (!$isData) { - out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; - } - var $i = 'i' + $lvl, - $propertyPath = 'schema' + $lvl + '[' + $i + ']', - $missingProperty = '\' + ' + $propertyPath + ' + \''; - if (it.opts._errorDataPathProperty) { - it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); - } - if ($isData) { - out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) { var err = '; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \''; - if (it.opts._errorDataPathProperty) { - out += 'is a required property'; - } else { - out += 'should have required property \\\'' + ($missingProperty) + '\\\''; - } - out += '\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { '; - } - out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined '; - if ($ownProperties) { - out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) '; - } - out += ') { var err = '; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \''; - if (it.opts._errorDataPathProperty) { - out += 'is a required property'; - } else { - out += 'should have required property \\\'' + ($missingProperty) + '\\\''; - } - out += '\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } '; - if ($isData) { - out += ' } '; - } - } else { - var arr3 = $required; - if (arr3) { - var $propertyKey, i3 = -1, - l3 = arr3.length - 1; - while (i3 < l3) { - $propertyKey = arr3[i3 += 1]; - var $prop = it.util.getProperty($propertyKey), - $missingProperty = it.util.escapeQuotes($propertyKey), - $useData = $data + $prop; - if (it.opts._errorDataPathProperty) { - it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); - } - out += ' if ( ' + ($useData) + ' === undefined '; - if ($ownProperties) { - out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; - } - out += ') { var err = '; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \''; - if (it.opts._errorDataPathProperty) { - out += 'is a required property'; - } else { - out += 'should have required property \\\'' + ($missingProperty) + '\\\''; - } - out += '\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; - } - } - } +}; + +Blowfish.prototype.expandstate = function(data, databytes, key, keybytes) { + var d = new Uint32Array(2), i, k; + + for (i = 0, BLF_J = 0; i < 18; i++) { + this.P[i] ^= stream2word(key, keybytes); + } + + for (i = 0, BLF_J = 0; i < 18; i += 2) { + d[0] ^= stream2word(data, databytes); + d[1] ^= stream2word(data, databytes); + this.encipher(d); + this.P[i] = d[0]; + this.P[i+1] = d[1]; + } + + for (i = 0; i < 4; i++) { + for (k = 0; k < 256; k += 2) { + d[0] ^= stream2word(data, databytes); + d[1] ^= stream2word(data, databytes); + this.encipher(d); + this.S[i][k] = d[0]; + this.S[i][k+1] = d[1]; } - it.errorPath = $currentErrorPath; - } else if ($breakOnError) { - out += ' if (true) {'; } - return out; -} + BLF_J = 0; +}; +Blowfish.prototype.enc = function(data, blocks) { + for (var i = 0; i < blocks; i++) { + this.encipher(data.subarray(i*2)); + } +}; -/***/ }), +Blowfish.prototype.dec = function(data, blocks) { + for (var i = 0; i < blocks; i++) { + this.decipher(data.subarray(i*2)); + } +}; -/***/ 24995: -/***/ ((module) => { +var BCRYPT_BLOCKS = 8, + BCRYPT_HASHSIZE = 32; -"use strict"; +function bcrypt_hash(sha2pass, sha2salt, out) { + var state = new Blowfish(), + cdata = new Uint32Array(BCRYPT_BLOCKS), i, + ciphertext = new Uint8Array([79,120,121,99,104,114,111,109,97,116,105, + 99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109, + 105,116,101]); //"OxychromaticBlowfishSwatDynamite" -module.exports = function generate_uniqueItems(it, $keyword, $ruleType) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $valid = 'valid' + $lvl; - var $isData = it.opts.$data && $schema && $schema.$data, - $schemaValue; - if ($isData) { - out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; - $schemaValue = 'schema' + $lvl; - } else { - $schemaValue = $schema; + state.expandstate(sha2salt, 64, sha2pass, 64); + for (i = 0; i < 64; i++) { + state.expand0state(sha2salt, 64); + state.expand0state(sha2pass, 64); } - if (($schema || $isData) && it.opts.uniqueItems !== false) { - if ($isData) { - out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { '; - } - out += ' var i = ' + ($data) + '.length , ' + ($valid) + ' = true , j; if (i > 1) { '; - var $itemType = it.schema.items && it.schema.items.type, - $typeIsArray = Array.isArray($itemType); - if (!$itemType || $itemType == 'object' || $itemType == 'array' || ($typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0))) { - out += ' outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } '; - } else { - out += ' var itemIndices = {}, item; for (;i--;) { var item = ' + ($data) + '[i]; '; - var $method = 'checkDataType' + ($typeIsArray ? 's' : ''); - out += ' if (' + (it.util[$method]($itemType, 'item', it.opts.strictNumbers, true)) + ') continue; '; - if ($typeIsArray) { - out += ' if (typeof item == \'string\') item = \'"\' + item; '; - } - out += ' if (typeof itemIndices[item] == \'number\') { ' + ($valid) + ' = false; j = itemIndices[item]; break; } itemIndices[item] = i; } '; - } - out += ' } '; - if ($isData) { - out += ' } '; - } - out += ' if (!' + ($valid) + ') { '; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } '; - if (it.opts.messages !== false) { - out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' '; - } - if (it.opts.verbose) { - out += ' , schema: '; - if ($isData) { - out += 'validate.schema' + ($schemaPath); - } else { - out += '' + ($schema); - } - out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += ' } '; - if ($breakOnError) { - out += ' else { '; - } - } else { - if ($breakOnError) { - out += ' if (true) { '; - } + + for (i = 0; i < BCRYPT_BLOCKS; i++) + cdata[i] = stream2word(ciphertext, ciphertext.byteLength); + for (i = 0; i < 64; i++) + state.enc(cdata, cdata.byteLength / 8); + + for (i = 0; i < BCRYPT_BLOCKS; i++) { + out[4*i+3] = cdata[i] >>> 24; + out[4*i+2] = cdata[i] >>> 16; + out[4*i+1] = cdata[i] >>> 8; + out[4*i+0] = cdata[i]; } - return out; -} +}; +function bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) { + var sha2pass = new Uint8Array(64), + sha2salt = new Uint8Array(64), + out = new Uint8Array(BCRYPT_HASHSIZE), + tmpout = new Uint8Array(BCRYPT_HASHSIZE), + countsalt = new Uint8Array(saltlen+4), + i, j, amt, stride, dest, count, + origkeylen = keylen; -/***/ }), + if (rounds < 1) + return -1; + if (passlen === 0 || saltlen === 0 || keylen === 0 || + keylen > (out.byteLength * out.byteLength) || saltlen > (1<<20)) + return -1; -/***/ 49585: -/***/ ((module) => { + stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength); + amt = Math.floor((keylen + stride - 1) / stride); -"use strict"; + for (i = 0; i < saltlen; i++) + countsalt[i] = salt[i]; -module.exports = function generate_validate(it, $keyword, $ruleType) { - var out = ''; - var $async = it.schema.$async === true, - $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'), - $id = it.self._getId(it.schema); - if (it.opts.strictKeywords) { - var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords); - if ($unknownKwd) { - var $keywordsMsg = 'unknown keyword: ' + $unknownKwd; - if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg); - else throw new Error($keywordsMsg); - } - } - if (it.isTop) { - out += ' var validate = '; - if ($async) { - it.async = true; - out += 'async '; - } - out += 'function(data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; '; - if ($id && (it.opts.sourceCode || it.opts.processCode)) { - out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' '; - } - } - if (typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref)) { - var $keyword = 'false schema'; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $errorKeyword; - var $data = 'data' + ($dataLvl || ''); - var $valid = 'valid' + $lvl; - if (it.schema === false) { - if (it.isTop) { - $breakOnError = true; - } else { - out += ' var ' + ($valid) + ' = false; '; - } - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; - if (it.opts.messages !== false) { - out += ' , message: \'boolean schema is false\' '; - } - if (it.opts.verbose) { - out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - } else { - if (it.isTop) { - if ($async) { - out += ' return data; '; - } else { - out += ' validate.errors = null; return true; '; - } - } else { - out += ' var ' + ($valid) + ' = true; '; - } - } - if (it.isTop) { - out += ' }; return validate; '; - } - return out; - } - if (it.isTop) { - var $top = it.isTop, - $lvl = it.level = 0, - $dataLvl = it.dataLevel = 0, - $data = 'data'; - it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema)); - it.baseId = it.baseId || it.rootId; - delete it.isTop; - it.dataPathArr = [""]; - if (it.schema.default !== undefined && it.opts.useDefaults && it.opts.strictDefaults) { - var $defaultMsg = 'default is ignored in the schema root'; - if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); - else throw new Error($defaultMsg); - } - out += ' var vErrors = null; '; - out += ' var errors = 0; '; - out += ' if (rootData === undefined) rootData = data; '; - } else { - var $lvl = it.level, - $dataLvl = it.dataLevel, - $data = 'data' + ($dataLvl || ''); - if ($id) it.baseId = it.resolve.url(it.baseId, $id); - if ($async && !it.async) throw new Error('async schema in sync schema'); - out += ' var errs_' + ($lvl) + ' = errors;'; - } - var $valid = 'valid' + $lvl, - $breakOnError = !it.opts.allErrors, - $closingBraces1 = '', - $closingBraces2 = ''; - var $errorKeyword; - var $typeSchema = it.schema.type, - $typeIsArray = Array.isArray($typeSchema); - if ($typeSchema && it.opts.nullable && it.schema.nullable === true) { - if ($typeIsArray) { - if ($typeSchema.indexOf('null') == -1) $typeSchema = $typeSchema.concat('null'); - } else if ($typeSchema != 'null') { - $typeSchema = [$typeSchema, 'null']; - $typeIsArray = true; - } - } - if ($typeIsArray && $typeSchema.length == 1) { - $typeSchema = $typeSchema[0]; - $typeIsArray = false; - } - if (it.schema.$ref && $refKeywords) { - if (it.opts.extendRefs == 'fail') { - throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)'); - } else if (it.opts.extendRefs !== true) { - $refKeywords = false; - it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"'); - } - } - if (it.schema.$comment && it.opts.$comment) { - out += ' ' + (it.RULES.all.$comment.code(it, '$comment')); - } - if ($typeSchema) { - if (it.opts.coerceTypes) { - var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema); + crypto_hash_sha512(sha2pass, pass, passlen); + + for (count = 1; keylen > 0; count++) { + countsalt[saltlen+0] = count >>> 24; + countsalt[saltlen+1] = count >>> 16; + countsalt[saltlen+2] = count >>> 8; + countsalt[saltlen+3] = count; + + crypto_hash_sha512(sha2salt, countsalt, saltlen + 4); + bcrypt_hash(sha2pass, sha2salt, tmpout); + for (i = out.byteLength; i--;) + out[i] = tmpout[i]; + + for (i = 1; i < rounds; i++) { + crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength); + bcrypt_hash(sha2pass, sha2salt, tmpout); + for (j = 0; j < out.byteLength; j++) + out[j] ^= tmpout[j]; } - var $rulesGroup = it.RULES.types[$typeSchema]; - if ($coerceToTypes || $typeIsArray || $rulesGroup === true || ($rulesGroup && !$shouldUseGroup($rulesGroup))) { - var $schemaPath = it.schemaPath + '.type', - $errSchemaPath = it.errSchemaPath + '/type'; - var $schemaPath = it.schemaPath + '.type', - $errSchemaPath = it.errSchemaPath + '/type', - $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType'; - out += ' if (' + (it.util[$method]($typeSchema, $data, it.opts.strictNumbers, true)) + ') { '; - if ($coerceToTypes) { - var $dataType = 'dataType' + $lvl, - $coerced = 'coerced' + $lvl; - out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; var ' + ($coerced) + ' = undefined; '; - if (it.opts.coerceTypes == 'array') { - out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ') && ' + ($data) + '.length == 1) { ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + '; if (' + (it.util.checkDataType(it.schema.type, $data, it.opts.strictNumbers)) + ') ' + ($coerced) + ' = ' + ($data) + '; } '; - } - out += ' if (' + ($coerced) + ' !== undefined) ; '; - var arr1 = $coerceToTypes; - if (arr1) { - var $type, $i = -1, - l1 = arr1.length - 1; - while ($i < l1) { - $type = arr1[$i += 1]; - if ($type == 'string') { - out += ' else if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; '; - } else if ($type == 'number' || $type == 'integer') { - out += ' else if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' '; - if ($type == 'integer') { - out += ' && !(' + ($data) + ' % 1)'; - } - out += ')) ' + ($coerced) + ' = +' + ($data) + '; '; - } else if ($type == 'boolean') { - out += ' else if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; '; - } else if ($type == 'null') { - out += ' else if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; '; - } else if (it.opts.coerceTypes == 'array' && $type == 'array') { - out += ' else if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; '; - } - } - } - out += ' else { '; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; - if ($typeIsArray) { - out += '' + ($typeSchema.join(",")); - } else { - out += '' + ($typeSchema); - } - out += '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should be '; - if ($typeIsArray) { - out += '' + ($typeSchema.join(",")); - } else { - out += '' + ($typeSchema); - } - out += '\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += ' } if (' + ($coerced) + ' !== undefined) { '; - var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', - $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; - out += ' ' + ($data) + ' = ' + ($coerced) + '; '; - if (!$dataLvl) { - out += 'if (' + ($parentData) + ' !== undefined)'; - } - out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } '; - } else { - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; - if ($typeIsArray) { - out += '' + ($typeSchema.join(",")); - } else { - out += '' + ($typeSchema); - } - out += '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should be '; - if ($typeIsArray) { - out += '' + ($typeSchema.join(",")); - } else { - out += '' + ($typeSchema); - } - out += '\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - } - out += ' } '; + + amt = Math.min(amt, keylen); + for (i = 0; i < amt; i++) { + dest = i * stride + (count - 1); + if (dest >= origkeylen) + break; + key[dest] = out[i]; } + keylen -= i; } - if (it.schema.$ref && !$refKeywords) { - out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' '; - if ($breakOnError) { - out += ' } if (errors === '; - if ($top) { - out += '0'; - } else { - out += 'errs_' + ($lvl); - } - out += ') { '; - $closingBraces2 += '}'; - } - } else { - var arr2 = it.RULES; - if (arr2) { - var $rulesGroup, i2 = -1, - l2 = arr2.length - 1; - while (i2 < l2) { - $rulesGroup = arr2[i2 += 1]; - if ($shouldUseGroup($rulesGroup)) { - if ($rulesGroup.type) { - out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data, it.opts.strictNumbers)) + ') { '; - } - if (it.opts.useDefaults) { - if ($rulesGroup.type == 'object' && it.schema.properties) { - var $schema = it.schema.properties, - $schemaKeys = Object.keys($schema); - var arr3 = $schemaKeys; - if (arr3) { - var $propertyKey, i3 = -1, - l3 = arr3.length - 1; - while (i3 < l3) { - $propertyKey = arr3[i3 += 1]; - var $sch = $schema[$propertyKey]; - if ($sch.default !== undefined) { - var $passData = $data + it.util.getProperty($propertyKey); - if (it.compositeRule) { - if (it.opts.strictDefaults) { - var $defaultMsg = 'default is ignored for: ' + $passData; - if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); - else throw new Error($defaultMsg); - } - } else { - out += ' if (' + ($passData) + ' === undefined '; - if (it.opts.useDefaults == 'empty') { - out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' '; - } - out += ' ) ' + ($passData) + ' = '; - if (it.opts.useDefaults == 'shared') { - out += ' ' + (it.useDefault($sch.default)) + ' '; - } else { - out += ' ' + (JSON.stringify($sch.default)) + ' '; - } - out += '; '; - } - } - } - } - } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) { - var arr4 = it.schema.items; - if (arr4) { - var $sch, $i = -1, - l4 = arr4.length - 1; - while ($i < l4) { - $sch = arr4[$i += 1]; - if ($sch.default !== undefined) { - var $passData = $data + '[' + $i + ']'; - if (it.compositeRule) { - if (it.opts.strictDefaults) { - var $defaultMsg = 'default is ignored for: ' + $passData; - if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); - else throw new Error($defaultMsg); - } - } else { - out += ' if (' + ($passData) + ' === undefined '; - if (it.opts.useDefaults == 'empty') { - out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' '; - } - out += ' ) ' + ($passData) + ' = '; - if (it.opts.useDefaults == 'shared') { - out += ' ' + (it.useDefault($sch.default)) + ' '; - } else { - out += ' ' + (JSON.stringify($sch.default)) + ' '; - } - out += '; '; - } - } - } - } - } - } - var arr5 = $rulesGroup.rules; - if (arr5) { - var $rule, i5 = -1, - l5 = arr5.length - 1; - while (i5 < l5) { - $rule = arr5[i5 += 1]; - if ($shouldUseRule($rule)) { - var $code = $rule.code(it, $rule.keyword, $rulesGroup.type); - if ($code) { - out += ' ' + ($code) + ' '; - if ($breakOnError) { - $closingBraces1 += '}'; - } - } - } - } - } - if ($breakOnError) { - out += ' ' + ($closingBraces1) + ' '; - $closingBraces1 = ''; - } - if ($rulesGroup.type) { - out += ' } '; - if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) { - out += ' else { '; - var $schemaPath = it.schemaPath + '.type', - $errSchemaPath = it.errSchemaPath + '/type'; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; - if ($typeIsArray) { - out += '' + ($typeSchema.join(",")); - } else { - out += '' + ($typeSchema); - } - out += '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should be '; - if ($typeIsArray) { - out += '' + ($typeSchema.join(",")); - } else { - out += '' + ($typeSchema); - } - out += '\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += ' } '; - } - } - if ($breakOnError) { - out += ' if (errors === '; - if ($top) { - out += '0'; - } else { - out += 'errs_' + ($lvl); - } - out += ') { '; - $closingBraces2 += '}'; - } - } - } - } + + return 0; +}; + +module.exports = { + BLOCKS: BCRYPT_BLOCKS, + HASHSIZE: BCRYPT_HASHSIZE, + hash: bcrypt_hash, + pbkdf: bcrypt_pbkdf +}; + + +/***/ }), + +/***/ 83682: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var register = __nccwpck_require__(44670); +var addHook = __nccwpck_require__(5549); +var removeHook = __nccwpck_require__(6819); + +// 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; } - if ($breakOnError) { - out += ' ' + ($closingBraces2) + ' '; + return HookCollection(); +} + +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; + + +/***/ }), + +/***/ 5549: +/***/ ((module) => { + +module.exports = addHook; + +function addHook(state, kind, name, hook) { + var orig = hook; + if (!state.registry[name]) { + state.registry[name] = []; } - if ($top) { - if ($async) { - out += ' if (errors === 0) return data; '; - out += ' else throw new ValidationError(vErrors); '; - } else { - out += ' validate.errors = vErrors; '; - out += ' return errors === 0; '; - } - out += ' }; return validate;'; - } else { - out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';'; + + if (kind === "before") { + hook = function (method, options) { + return Promise.resolve() + .then(orig.bind(null, options)) + .then(method.bind(null, options)); + }; } - function $shouldUseGroup($rulesGroup) { - var rules = $rulesGroup.rules; - for (var i = 0; i < rules.length; i++) - if ($shouldUseRule(rules[i])) return true; + 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; + }); + }; } - function $shouldUseRule($rule) { - return it.schema[$rule.keyword] !== undefined || ($rule.implements && $ruleImplementsSomeKeyword($rule)); + if (kind === "error") { + hook = function (method, options) { + return Promise.resolve() + .then(method.bind(null, options)) + .catch(function (error) { + return orig(error, options); + }); + }; } - function $ruleImplementsSomeKeyword($rule) { - var impl = $rule.implements; - for (var i = 0; i < impl.length; i++) - if (it.schema[impl[i]] !== undefined) return true; + state.registry[name].push({ + hook: hook, + orig: orig, + }); +} + + +/***/ }), + +/***/ 44670: +/***/ ((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"); } - return out; + + 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 state.registry[name].reduce(function (method, registered) { + return registered.hook.bind(null, method, options); + }, method)(); + }); } /***/ }), -/***/ 53297: +/***/ 6819: +/***/ ((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); +} + + +/***/ }), + +/***/ 33717: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +var concatMap = __nccwpck_require__(86891); +var balanced = __nccwpck_require__(9417); +module.exports = expandTop; -var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i; -var customRuleCode = __nccwpck_require__(5912); -var definitionSchema = __nccwpck_require__(10458); +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'; -module.exports = { - add: addKeyword, - get: getKeyword, - remove: removeKeyword, - validate: validateKeyword -}; +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} -/** - * Define custom keyword - * @this Ajv - * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords). - * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`. - * @return {Ajv} this for method chaining - */ -function addKeyword(keyword, definition) { - /* jshint validthis: true */ - /* eslint no-shadow: 0 */ - var RULES = this.RULES; - if (RULES.keywords[keyword]) - throw new Error('Keyword ' + keyword + ' is already defined'); +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} - if (!IDENTIFIER.test(keyword)) - throw new Error('Keyword ' + keyword + ' is not a valid identifier'); - if (definition) { - this.validateKeyword(definition, true); +// 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 dataType = definition.type; - if (Array.isArray(dataType)) { - for (var i=0; i= y; +} + +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 metaSchema = definition.metaSchema; - if (metaSchema) { - if (definition.$data && this._opts.$data) { - metaSchema = { - anyOf: [ - metaSchema, - { '$ref': 'https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#' } - ] - }; + 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; + }); } - definition.validateSchema = this.compile(metaSchema, true); } } - RULES.keywords[keyword] = RULES.all[keyword] = true; + // 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) + : ['']; - function _addRule(keyword, dataType, definition) { - var ruleGroup; - for (var i=0; i 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) }); + } - if (!ruleGroup) { - ruleGroup = { type: dataType, rules: [] }; - RULES.push(ruleGroup); + 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); } + } - var rule = { - keyword: keyword, - definition: definition, - custom: true, - code: customRuleCode, - implements: definition.implements - }; - ruleGroup.rules.push(rule); - RULES.custom[keyword] = rule; + return expansions; +} + + + +/***/ }), + +/***/ 29700: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +// Copyright (C) 2011-2015 John Hewson +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +// IN THE SOFTWARE. + +var stream = __nccwpck_require__(12781), + util = __nccwpck_require__(73837), + timers = __nccwpck_require__(39512); + +// convinience API +module.exports = function(readStream, options) { + return module.exports.createStream(readStream, options); +}; + +// basic API +module.exports.createStream = function(readStream, options) { + if (readStream) { + return createLineStream(readStream, options); + } else { + return new LineStream(options); } +}; - return this; +// deprecated API +module.exports.createLineStream = function(readStream) { + console.log('WARNING: byline#createLineStream is deprecated and will be removed soon'); + return createLineStream(readStream); +}; + +function createLineStream(readStream, options) { + if (!readStream) { + throw new Error('expected readStream'); + } + if (!readStream.readable) { + throw new Error('readStream must be readable'); + } + var ls = new LineStream(options); + readStream.pipe(ls); + return ls; } +// +// using the new node v0.10 "streams2" API +// -/** - * Get keyword - * @this Ajv - * @param {String} keyword pre-defined or custom keyword. - * @return {Object|Boolean} custom keyword definition, `true` if it is a predefined keyword, `false` otherwise. - */ -function getKeyword(keyword) { - /* jshint validthis: true */ - var rule = this.RULES.custom[keyword]; - return rule ? rule.definition : this.RULES.keywords[keyword] || false; +module.exports.LineStream = LineStream; + +function LineStream(options) { + stream.Transform.call(this, options); + options = options || {}; + + // use objectMode to stop the output from being buffered + // which re-concatanates the lines, just without newlines. + this._readableState.objectMode = true; + this._lineBuffer = []; + this._keepEmptyLines = options.keepEmptyLines || false; + this._lastChunkEndedWithCR = false; + + // take the source's encoding if we don't have one + var self = this; + this.on('pipe', function(src) { + if (!self.encoding) { + // but we can't do this for old-style streams + if (src instanceof stream.Readable) { + self.encoding = src._readableState.encoding; + } + } + }); } +util.inherits(LineStream, stream.Transform); + +LineStream.prototype._transform = function(chunk, encoding, done) { + // decode binary chunks as UTF-8 + encoding = encoding || 'utf8'; + + if (Buffer.isBuffer(chunk)) { + if (encoding == 'buffer') { + chunk = chunk.toString(); // utf8 + encoding = 'utf8'; + } + else { + chunk = chunk.toString(encoding); + } + } + this._chunkEncoding = encoding; + + // see: http://www.unicode.org/reports/tr18/#Line_Boundaries + var lines = chunk.split(/\r\n|[\n\v\f\r\x85\u2028\u2029]/g); + + // don't split CRLF which spans chunks + if (this._lastChunkEndedWithCR && chunk[0] == '\n') { + lines.shift(); + } + + if (this._lineBuffer.length > 0) { + this._lineBuffer[this._lineBuffer.length - 1] += lines[0]; + lines.shift(); + } + this._lastChunkEndedWithCR = chunk[chunk.length - 1] == '\r'; + this._lineBuffer = this._lineBuffer.concat(lines); + this._pushBuffer(encoding, 1, done); +}; -/** - * Remove keyword - * @this Ajv - * @param {String} keyword pre-defined or custom keyword. - * @return {Ajv} this for method chaining - */ -function removeKeyword(keyword) { - /* jshint validthis: true */ - var RULES = this.RULES; - delete RULES.keywords[keyword]; - delete RULES.all[keyword]; - delete RULES.custom[keyword]; - for (var i=0; i keep) { + var line = this._lineBuffer.shift(); + // skip empty lines + if (this._keepEmptyLines || line.length > 0 ) { + if (!this.push(this._reencode(line, encoding))) { + // when the high-water mark is reached, defer pushes until the next tick + var self = this; + timers.setImmediate(function() { + self._pushBuffer(encoding, keep, done); + }); + return; } } } - return this; -} + done(); +}; +LineStream.prototype._flush = function(done) { + this._pushBuffer(this._chunkEncoding, 0, done); +}; -/** - * Validate keyword definition - * @this Ajv - * @param {Object} definition keyword definition object. - * @param {Boolean} throwError true to throw exception if definition is invalid - * @return {boolean} validation result - */ -function validateKeyword(definition, throwError) { - validateKeyword.errors = null; - var v = this._validateKeyword = this._validateKeyword - || this.compile(definitionSchema, true); +// see Readable::push +LineStream.prototype._reencode = function(line, chunkEncoding) { + if (this.encoding && this.encoding != chunkEncoding) { + return new Buffer(line, chunkEncoding).toString(this.encoding); + } + else if (this.encoding) { + // this should be the most common case, i.e. we're using an encoded source stream + return line; + } + else { + return new Buffer(line, chunkEncoding); + } +}; - if (v(definition)) return true; - validateKeyword.errors = v.errors; - if (throwError) - throw new Error('custom keyword definition is invalid: ' + this.errorsText(v.errors)); - else - return false; -} +/***/ }), + +/***/ 2286: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +const { + V4MAPPED, + ADDRCONFIG, + ALL, + promises: { + Resolver: AsyncResolver + }, + lookup: dnsLookup +} = __nccwpck_require__(17578); +const {promisify} = __nccwpck_require__(73837); +const os = __nccwpck_require__(22037); + +const kCacheableLookupCreateConnection = Symbol('cacheableLookupCreateConnection'); +const kCacheableLookupInstance = Symbol('cacheableLookupInstance'); +const kExpires = Symbol('expires'); + +const supportsALL = typeof ALL === 'number'; + +const verifyAgent = agent => { + if (!(agent && typeof agent.createConnection === 'function')) { + throw new Error('Expected an Agent instance as the first argument'); + } +}; + +const map4to6 = entries => { + for (const entry of entries) { + if (entry.family === 6) { + continue; + } + + entry.address = `::ffff:${entry.address}`; + entry.family = 6; + } +}; + +const getIfaceInfo = () => { + let has4 = false; + let has6 = false; + + for (const device of Object.values(os.networkInterfaces())) { + for (const iface of device) { + if (iface.internal) { + continue; + } + + if (iface.family === 'IPv6') { + has6 = true; + } else { + has4 = true; + } + + if (has4 && has6) { + return {has4, has6}; + } + } + } + + return {has4, has6}; +}; + +const isIterable = map => { + return Symbol.iterator in map; +}; + +const ttl = {ttl: true}; +const all = {all: true}; + +class CacheableLookup { + constructor({ + cache = new Map(), + maxTtl = Infinity, + fallbackDuration = 3600, + errorTtl = 0.15, + resolver = new AsyncResolver(), + lookup = dnsLookup + } = {}) { + this.maxTtl = maxTtl; + this.errorTtl = errorTtl; + + this._cache = cache; + this._resolver = resolver; + this._dnsLookup = promisify(lookup); + + if (this._resolver instanceof AsyncResolver) { + this._resolve4 = this._resolver.resolve4.bind(this._resolver); + this._resolve6 = this._resolver.resolve6.bind(this._resolver); + } else { + this._resolve4 = promisify(this._resolver.resolve4.bind(this._resolver)); + this._resolve6 = promisify(this._resolver.resolve6.bind(this._resolver)); + } + + this._iface = getIfaceInfo(); + + this._pending = {}; + this._nextRemovalTime = false; + this._hostnamesToFallback = new Set(); + + if (fallbackDuration < 1) { + this._fallback = false; + } else { + this._fallback = true; + + const interval = setInterval(() => { + this._hostnamesToFallback.clear(); + }, fallbackDuration * 1000); + + /* istanbul ignore next: There is no `interval.unref()` when running inside an Electron renderer */ + if (interval.unref) { + interval.unref(); + } + } + + this.lookup = this.lookup.bind(this); + this.lookupAsync = this.lookupAsync.bind(this); + } + + set servers(servers) { + this.clear(); + + this._resolver.setServers(servers); + } + + get servers() { + return this._resolver.getServers(); + } + + lookup(hostname, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } else if (typeof options === 'number') { + options = { + family: options + }; + } + + if (!callback) { + throw new Error('Callback must be a function.'); + } + + // eslint-disable-next-line promise/prefer-await-to-then + this.lookupAsync(hostname, options).then(result => { + if (options.all) { + callback(null, result); + } else { + callback(null, result.address, result.family, result.expires, result.ttl); + } + }, callback); + } + + async lookupAsync(hostname, options = {}) { + if (typeof options === 'number') { + options = { + family: options + }; + } + + let cached = await this.query(hostname); + + if (options.family === 6) { + const filtered = cached.filter(entry => entry.family === 6); + + if (options.hints & V4MAPPED) { + if ((supportsALL && options.hints & ALL) || filtered.length === 0) { + map4to6(cached); + } else { + cached = filtered; + } + } else { + cached = filtered; + } + } else if (options.family === 4) { + cached = cached.filter(entry => entry.family === 4); + } + + if (options.hints & ADDRCONFIG) { + const {_iface} = this; + cached = cached.filter(entry => entry.family === 6 ? _iface.has6 : _iface.has4); + } + + if (cached.length === 0) { + const error = new Error(`cacheableLookup ENOTFOUND ${hostname}`); + error.code = 'ENOTFOUND'; + error.hostname = hostname; + + throw error; + } + + if (options.all) { + return cached; + } + + return cached[0]; + } + + async query(hostname) { + let cached = await this._cache.get(hostname); + + if (!cached) { + const pending = this._pending[hostname]; + + if (pending) { + cached = await pending; + } else { + const newPromise = this.queryAndCache(hostname); + this._pending[hostname] = newPromise; + + try { + cached = await newPromise; + } finally { + delete this._pending[hostname]; + } + } + } + + cached = cached.map(entry => { + return {...entry}; + }); + + return cached; + } + + async _resolve(hostname) { + const wrap = async promise => { + try { + return await promise; + } catch (error) { + if (error.code === 'ENODATA' || error.code === 'ENOTFOUND') { + return []; + } + + throw error; + } + }; + + // ANY is unsafe as it doesn't trigger new queries in the underlying server. + const [A, AAAA] = await Promise.all([ + this._resolve4(hostname, ttl), + this._resolve6(hostname, ttl) + ].map(promise => wrap(promise))); + + let aTtl = 0; + let aaaaTtl = 0; + let cacheTtl = 0; + + const now = Date.now(); + + for (const entry of A) { + entry.family = 4; + entry.expires = now + (entry.ttl * 1000); + + aTtl = Math.max(aTtl, entry.ttl); + } + + for (const entry of AAAA) { + entry.family = 6; + entry.expires = now + (entry.ttl * 1000); + + aaaaTtl = Math.max(aaaaTtl, entry.ttl); + } + + if (A.length > 0) { + if (AAAA.length > 0) { + cacheTtl = Math.min(aTtl, aaaaTtl); + } else { + cacheTtl = aTtl; + } + } else { + cacheTtl = aaaaTtl; + } + + return { + entries: [ + ...A, + ...AAAA + ], + cacheTtl + }; + } + + async _lookup(hostname) { + try { + const entries = await this._dnsLookup(hostname, { + all: true + }); + + return { + entries, + cacheTtl: 0 + }; + } catch (_) { + return { + entries: [], + cacheTtl: 0 + }; + } + } + + async _set(hostname, data, cacheTtl) { + if (this.maxTtl > 0 && cacheTtl > 0) { + cacheTtl = Math.min(cacheTtl, this.maxTtl) * 1000; + data[kExpires] = Date.now() + cacheTtl; + + try { + await this._cache.set(hostname, data, cacheTtl); + } catch (error) { + this.lookupAsync = async () => { + const cacheError = new Error('Cache Error. Please recreate the CacheableLookup instance.'); + cacheError.cause = error; + + throw cacheError; + }; + } + + if (isIterable(this._cache)) { + this._tick(cacheTtl); + } + } + } + + async queryAndCache(hostname) { + if (this._hostnamesToFallback.has(hostname)) { + return this._dnsLookup(hostname, all); + } + + let query = await this._resolve(hostname); + + if (query.entries.length === 0 && this._fallback) { + query = await this._lookup(hostname); + + if (query.entries.length !== 0) { + // Use `dns.lookup(...)` for that particular hostname + this._hostnamesToFallback.add(hostname); + } + } + + const cacheTtl = query.entries.length === 0 ? this.errorTtl : query.cacheTtl; + await this._set(hostname, query.entries, cacheTtl); + + return query.entries; + } + + _tick(ms) { + const nextRemovalTime = this._nextRemovalTime; + + if (!nextRemovalTime || ms < nextRemovalTime) { + clearTimeout(this._removalTimeout); + + this._nextRemovalTime = ms; + + this._removalTimeout = setTimeout(() => { + this._nextRemovalTime = false; + + let nextExpiry = Infinity; + + const now = Date.now(); + + for (const [hostname, entries] of this._cache) { + const expires = entries[kExpires]; + + if (now >= expires) { + this._cache.delete(hostname); + } else if (expires < nextExpiry) { + nextExpiry = expires; + } + } + + if (nextExpiry !== Infinity) { + this._tick(nextExpiry - now); + } + }, ms); + + /* istanbul ignore next: There is no `timeout.unref()` when running inside an Electron renderer */ + if (this._removalTimeout.unref) { + this._removalTimeout.unref(); + } + } + } + + install(agent) { + verifyAgent(agent); + + if (kCacheableLookupCreateConnection in agent) { + throw new Error('CacheableLookup has been already installed'); + } + + agent[kCacheableLookupCreateConnection] = agent.createConnection; + agent[kCacheableLookupInstance] = this; + + agent.createConnection = (options, callback) => { + if (!('lookup' in options)) { + options.lookup = this.lookup; + } + + return agent[kCacheableLookupCreateConnection](options, callback); + }; + } + + uninstall(agent) { + verifyAgent(agent); + + if (agent[kCacheableLookupCreateConnection]) { + if (agent[kCacheableLookupInstance] !== this) { + throw new Error('The agent is not owned by this CacheableLookup instance'); + } + + agent.createConnection = agent[kCacheableLookupCreateConnection]; -/***/ }), + delete agent[kCacheableLookupCreateConnection]; + delete agent[kCacheableLookupInstance]; + } + } -/***/ 99348: -/***/ ((module) => { + updateInterfaceInfo() { + const {_iface} = this; -// Copyright 2011 Mark Cavage All rights reserved. + this._iface = getIfaceInfo(); + if ((_iface.has4 && !this._iface.has4) || (_iface.has6 && !this._iface.has6)) { + this._cache.clear(); + } + } -module.exports = { + clear(hostname) { + if (hostname) { + this._cache.delete(hostname); + return; + } - newInvalidAsn1Error: function (msg) { - var e = new Error(); - e.name = 'InvalidAsn1Error'; - e.message = msg || ''; - return e; - } + this._cache.clear(); + } +} -}; +module.exports = CacheableLookup; +module.exports["default"] = CacheableLookup; /***/ }), -/***/ 194: +/***/ 24340: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Copyright 2011 Mark Cavage All rights reserved. +"use strict"; -var errors = __nccwpck_require__(99348); -var types = __nccwpck_require__(42473); +const {PassThrough: PassThroughStream} = __nccwpck_require__(12781); -var Reader = __nccwpck_require__(20290); -var Writer = __nccwpck_require__(43200); +module.exports = options => { + options = {...options}; + const {array} = options; + let {encoding} = options; + const isBuffer = encoding === 'buffer'; + let objectMode = false; -// --- Exports + if (array) { + objectMode = !(encoding || isBuffer); + } else { + encoding = encoding || 'utf8'; + } -module.exports = { + if (isBuffer) { + encoding = null; + } - Reader: Reader, + const stream = new PassThroughStream({objectMode}); - Writer: Writer + if (encoding) { + stream.setEncoding(encoding); + } -}; + let length = 0; + const chunks = []; -for (var t in types) { - if (types.hasOwnProperty(t)) - module.exports[t] = types[t]; -} -for (var e in errors) { - if (errors.hasOwnProperty(e)) - module.exports[e] = errors[e]; -} + stream.on('data', chunk => { + chunks.push(chunk); + if (objectMode) { + length = chunks.length; + } else { + length += chunk.length; + } + }); -/***/ }), + stream.getBufferedValue = () => { + if (array) { + return chunks; + } -/***/ 20290: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return isBuffer ? Buffer.concat(chunks, length) : chunks.join(''); + }; -// Copyright 2011 Mark Cavage All rights reserved. + stream.getBufferedLength = () => length; -var assert = __nccwpck_require__(39491); -var Buffer = (__nccwpck_require__(15118).Buffer); + return stream; +}; -var ASN1 = __nccwpck_require__(42473); -var errors = __nccwpck_require__(99348); +/***/ }), -// --- Globals +/***/ 97040: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var newInvalidAsn1Error = errors.newInvalidAsn1Error; +"use strict"; +const {constants: BufferConstants} = __nccwpck_require__(14300); +const pump = __nccwpck_require__(18341); +const bufferStream = __nccwpck_require__(24340); +class MaxBufferError extends Error { + constructor() { + super('maxBuffer exceeded'); + this.name = 'MaxBufferError'; + } +} -// --- API +async function getStream(inputStream, options) { + if (!inputStream) { + return Promise.reject(new Error('Expected a stream')); + } -function Reader(data) { - if (!data || !Buffer.isBuffer(data)) - throw new TypeError('data must be a node Buffer'); + options = { + maxBuffer: Infinity, + ...options + }; - this._buf = data; - this._size = data.length; + const {maxBuffer} = options; - // These hold the "current" state - this._len = 0; - this._offset = 0; -} + let stream; + await new Promise((resolve, reject) => { + const rejectPromise = error => { + // Don't retrieve an oversized buffer. + if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) { + error.bufferedData = stream.getBufferedValue(); + } -Object.defineProperty(Reader.prototype, 'length', { - enumerable: true, - get: function () { return (this._len); } -}); + reject(error); + }; -Object.defineProperty(Reader.prototype, 'offset', { - enumerable: true, - get: function () { return (this._offset); } -}); + stream = pump(inputStream, bufferStream(options), error => { + if (error) { + rejectPromise(error); + return; + } -Object.defineProperty(Reader.prototype, 'remain', { - get: function () { return (this._size - this._offset); } -}); + resolve(); + }); -Object.defineProperty(Reader.prototype, 'buffer', { - get: function () { return (this._buf.slice(this._offset)); } -}); + stream.on('data', () => { + if (stream.getBufferedLength() > maxBuffer) { + rejectPromise(new MaxBufferError()); + } + }); + }); + return stream.getBufferedValue(); +} -/** - * Reads a single byte and advances offset; you can pass in `true` to make this - * a "peek" operation (i.e., get the byte, but don't advance the offset). - * - * @param {Boolean} peek true means don't move offset. - * @return {Number} the next byte, null if not enough data. - */ -Reader.prototype.readByte = function (peek) { - if (this._size - this._offset < 1) - return null; +module.exports = getStream; +// TODO: Remove this for the next major release +module.exports["default"] = getStream; +module.exports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'}); +module.exports.array = (stream, options) => getStream(stream, {...options, array: true}); +module.exports.MaxBufferError = MaxBufferError; - var b = this._buf[this._offset] & 0xff; - if (!peek) - this._offset += 1; +/***/ }), - return b; -}; +/***/ 78116: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; -Reader.prototype.peek = function () { - return this.readByte(true); -}; +const EventEmitter = __nccwpck_require__(82361); +const urlLib = __nccwpck_require__(57310); +const normalizeUrl = __nccwpck_require__(17952); +const getStream = __nccwpck_require__(97040); +const CachePolicy = __nccwpck_require__(61002); +const Response = __nccwpck_require__(9004); +const lowercaseKeys = __nccwpck_require__(9662); +const cloneResponse = __nccwpck_require__(81312); +const Keyv = __nccwpck_require__(51531); -/** - * Reads a (potentially) variable length off the BER buffer. This call is - * not really meant to be called directly, as callers have to manipulate - * the internal buffer afterwards. - * - * As a result of this call, you can call `Reader.length`, until the - * next thing called that does a readLength. - * - * @return {Number} the amount of offset to advance the buffer. - * @throws {InvalidAsn1Error} on bad ASN.1 - */ -Reader.prototype.readLength = function (offset) { - if (offset === undefined) - offset = this._offset; +class CacheableRequest { + constructor(request, cacheAdapter) { + if (typeof request !== 'function') { + throw new TypeError('Parameter `request` must be a function'); + } - if (offset >= this._size) - return null; + this.cache = new Keyv({ + uri: typeof cacheAdapter === 'string' && cacheAdapter, + store: typeof cacheAdapter !== 'string' && cacheAdapter, + namespace: 'cacheable-request' + }); - var lenB = this._buf[offset++] & 0xff; - if (lenB === null) - return null; + return this.createCacheableRequest(request); + } - if ((lenB & 0x80) === 0x80) { - lenB &= 0x7f; + createCacheableRequest(request) { + return (opts, cb) => { + let url; + if (typeof opts === 'string') { + url = normalizeUrlObject(urlLib.parse(opts)); + opts = {}; + } else if (opts instanceof urlLib.URL) { + url = normalizeUrlObject(urlLib.parse(opts.toString())); + opts = {}; + } else { + const [pathname, ...searchParts] = (opts.path || '').split('?'); + const search = searchParts.length > 0 ? + `?${searchParts.join('?')}` : + ''; + url = normalizeUrlObject({ ...opts, pathname, search }); + } - if (lenB === 0) - throw newInvalidAsn1Error('Indefinite length not supported'); + opts = { + headers: {}, + method: 'GET', + cache: true, + strictTtl: false, + automaticFailover: false, + ...opts, + ...urlObjectToRequestOptions(url) + }; + opts.headers = lowercaseKeys(opts.headers); - if (lenB > 4) - throw newInvalidAsn1Error('encoding too long'); + const ee = new EventEmitter(); + const normalizedUrlString = normalizeUrl( + urlLib.format(url), + { + stripWWW: false, + removeTrailingSlash: false, + stripAuthentication: false + } + ); + const key = `${opts.method}:${normalizedUrlString}`; + let revalidate = false; + let madeRequest = false; - if (this._size - offset < lenB) - return null; + const makeRequest = opts => { + madeRequest = true; + let requestErrored = false; + let requestErrorCallback; - this._len = 0; - for (var i = 0; i < lenB; i++) - this._len = (this._len << 8) + (this._buf[offset++] & 0xff); + const requestErrorPromise = new Promise(resolve => { + requestErrorCallback = () => { + if (!requestErrored) { + requestErrored = true; + resolve(); + } + }; + }); - } else { - // Wasn't a variable length - this._len = lenB; - } + const handler = response => { + if (revalidate && !opts.forceRefresh) { + response.status = response.statusCode; + const revalidatedPolicy = CachePolicy.fromObject(revalidate.cachePolicy).revalidatedPolicy(opts, response); + if (!revalidatedPolicy.modified) { + const headers = revalidatedPolicy.policy.responseHeaders(); + response = new Response(revalidate.statusCode, headers, revalidate.body, revalidate.url); + response.cachePolicy = revalidatedPolicy.policy; + response.fromCache = true; + } + } - return offset; -}; + if (!response.fromCache) { + response.cachePolicy = new CachePolicy(opts, response, opts); + response.fromCache = false; + } + let clonedResponse; + if (opts.cache && response.cachePolicy.storable()) { + clonedResponse = cloneResponse(response); -/** - * Parses the next sequence in this BER buffer. - * - * To get the length of the sequence, call `Reader.length`. - * - * @return {Number} the sequence's tag. - */ -Reader.prototype.readSequence = function (tag) { - var seq = this.peek(); - if (seq === null) - return null; - if (tag !== undefined && tag !== seq) - throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + - ': got 0x' + seq.toString(16)); + (async () => { + try { + const bodyPromise = getStream.buffer(response); - var o = this.readLength(this._offset + 1); // stored in `length` - if (o === null) - return null; + await Promise.race([ + requestErrorPromise, + new Promise(resolve => response.once('end', resolve)) + ]); - this._offset = o; - return seq; -}; + if (requestErrored) { + return; + } + const body = await bodyPromise; -Reader.prototype.readInt = function () { - return this._readTag(ASN1.Integer); -}; + const value = { + cachePolicy: response.cachePolicy.toObject(), + url: response.url, + statusCode: response.fromCache ? revalidate.statusCode : response.statusCode, + body + }; + let ttl = opts.strictTtl ? response.cachePolicy.timeToLive() : undefined; + if (opts.maxTtl) { + ttl = ttl ? Math.min(ttl, opts.maxTtl) : opts.maxTtl; + } -Reader.prototype.readBoolean = function () { - return (this._readTag(ASN1.Boolean) === 0 ? false : true); -}; + await this.cache.set(key, value, ttl); + } catch (error) { + ee.emit('error', new CacheableRequest.CacheError(error)); + } + })(); + } else if (opts.cache && revalidate) { + (async () => { + try { + await this.cache.delete(key); + } catch (error) { + ee.emit('error', new CacheableRequest.CacheError(error)); + } + })(); + } + ee.emit('response', clonedResponse || response); + if (typeof cb === 'function') { + cb(clonedResponse || response); + } + }; -Reader.prototype.readEnumeration = function () { - return this._readTag(ASN1.Enumeration); -}; + try { + const req = request(opts, handler); + req.once('error', requestErrorCallback); + req.once('abort', requestErrorCallback); + ee.emit('request', req); + } catch (error) { + ee.emit('error', new CacheableRequest.RequestError(error)); + } + }; + (async () => { + const get = async opts => { + await Promise.resolve(); -Reader.prototype.readString = function (tag, retbuf) { - if (!tag) - tag = ASN1.OctetString; + const cacheEntry = opts.cache ? await this.cache.get(key) : undefined; + if (typeof cacheEntry === 'undefined') { + return makeRequest(opts); + } - var b = this.peek(); - if (b === null) - return null; + const policy = CachePolicy.fromObject(cacheEntry.cachePolicy); + if (policy.satisfiesWithoutRevalidation(opts) && !opts.forceRefresh) { + const headers = policy.responseHeaders(); + const response = new Response(cacheEntry.statusCode, headers, cacheEntry.body, cacheEntry.url); + response.cachePolicy = policy; + response.fromCache = true; - if (b !== tag) - throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + - ': got 0x' + b.toString(16)); + ee.emit('response', response); + if (typeof cb === 'function') { + cb(response); + } + } else { + revalidate = cacheEntry; + opts.headers = policy.revalidationHeaders(opts); + makeRequest(opts); + } + }; - var o = this.readLength(this._offset + 1); // stored in `length` + const errorHandler = error => ee.emit('error', new CacheableRequest.CacheError(error)); + this.cache.once('error', errorHandler); + ee.on('response', () => this.cache.removeListener('error', errorHandler)); - if (o === null) - return null; + try { + await get(opts); + } catch (error) { + if (opts.automaticFailover && !madeRequest) { + makeRequest(opts); + } - if (this.length > this._size - o) - return null; + ee.emit('error', new CacheableRequest.CacheError(error)); + } + })(); - this._offset = o; + return ee; + }; + } +} - if (this.length === 0) - return retbuf ? Buffer.alloc(0) : ''; +function urlObjectToRequestOptions(url) { + const options = { ...url }; + options.path = `${url.pathname || '/'}${url.search || ''}`; + delete options.pathname; + delete options.search; + return options; +} - var str = this._buf.slice(this._offset, this._offset + this.length); - this._offset += this.length; +function normalizeUrlObject(url) { + // If url was parsed by url.parse or new URL: + // - hostname will be set + // - host will be hostname[:port] + // - port will be set if it was explicit in the parsed string + // Otherwise, url was from request options: + // - hostname or host may be set + // - host shall not have port encoded + return { + protocol: url.protocol, + auth: url.auth, + hostname: url.hostname || url.host || 'localhost', + port: url.port, + pathname: url.pathname, + search: url.search + }; +} - return retbuf ? str : str.toString('utf8'); +CacheableRequest.RequestError = class extends Error { + constructor(error) { + super(error.message); + this.name = 'RequestError'; + Object.assign(this, error); + } }; -Reader.prototype.readOID = function (tag) { - if (!tag) - tag = ASN1.OID; - - var b = this.readString(tag, true); - if (b === null) - return null; +CacheableRequest.CacheError = class extends Error { + constructor(error) { + super(error.message); + this.name = 'CacheError'; + Object.assign(this, error); + } +}; - var values = []; - var value = 0; +module.exports = CacheableRequest; - for (var i = 0; i < b.length; i++) { - var byte = b[i] & 0xff; - value <<= 7; - value += byte & 0x7f; - if ((byte & 0x80) === 0) { - values.push(value); - value = 0; - } - } +/***/ }), - value = values.shift(); - values.unshift(value % 40); - values.unshift((value / 40) >> 0); +/***/ 19227: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return values.join('.'); -}; +"use strict"; -Reader.prototype._readTag = function (tag) { - assert.ok(tag !== undefined); +var bind = __nccwpck_require__(69839); - var b = this.peek(); +var $apply = __nccwpck_require__(54177); +var $call = __nccwpck_require__(2808); +var $reflectApply = __nccwpck_require__(48309); - if (b === null) - return null; +/** @type {import('./actualApply')} */ +module.exports = $reflectApply || bind.call($call, $apply); - if (b !== tag) - throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + - ': got 0x' + b.toString(16)); - var o = this.readLength(this._offset + 1); // stored in `length` - if (o === null) - return null; +/***/ }), - if (this.length > 4) - throw newInvalidAsn1Error('Integer too long: ' + this.length); +/***/ 54177: +/***/ ((module) => { - if (this.length > this._size - o) - return null; - this._offset = o; +"use strict"; - var fb = this._buf[this._offset]; - var value = 0; - for (var i = 0; i < this.length; i++) { - value <<= 8; - value |= (this._buf[this._offset++] & 0xff); - } +/** @type {import('./functionApply')} */ +module.exports = Function.prototype.apply; - if ((fb & 0x80) === 0x80 && i !== 4) - value -= (1 << (i * 8)); - return value >> 0; -}; +/***/ }), +/***/ 2808: +/***/ ((module) => { +"use strict"; -// --- Exported API -module.exports = Reader; +/** @type {import('./functionCall')} */ +module.exports = Function.prototype.call; /***/ }), -/***/ 42473: -/***/ ((module) => { +/***/ 86815: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Copyright 2011 Mark Cavage All rights reserved. +"use strict"; -module.exports = { - EOC: 0, - Boolean: 1, - Integer: 2, - BitString: 3, - OctetString: 4, - Null: 5, - OID: 6, - ObjectDescriptor: 7, - External: 8, - Real: 9, // float - Enumeration: 10, - PDV: 11, - Utf8String: 12, - RelativeOID: 13, - Sequence: 16, - Set: 17, - NumericString: 18, - PrintableString: 19, - T61String: 20, - VideotexString: 21, - IA5String: 22, - UTCTime: 23, - GeneralizedTime: 24, - GraphicString: 25, - VisibleString: 26, - GeneralString: 28, - UniversalString: 29, - CharacterString: 30, - BMPString: 31, - Constructor: 32, - Context: 128 +var bind = __nccwpck_require__(69839); +var $TypeError = __nccwpck_require__(6361); + +var $call = __nccwpck_require__(2808); +var $actualApply = __nccwpck_require__(19227); + +/** @type {(args: [Function, thisArg?: unknown, ...args: unknown[]]) => Function} TODO FIXME, find a way to use import('.') */ +module.exports = function callBindBasic(args) { + if (args.length < 1 || typeof args[0] !== 'function') { + throw new $TypeError('a function is required'); + } + return $actualApply(bind, $call, args); }; /***/ }), -/***/ 43200: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 85316: +/***/ ((module) => { -// Copyright 2011 Mark Cavage All rights reserved. +"use strict"; -var assert = __nccwpck_require__(39491); -var Buffer = (__nccwpck_require__(15118).Buffer); -var ASN1 = __nccwpck_require__(42473); -var errors = __nccwpck_require__(99348); +/* eslint no-invalid-this: 1 */ -// --- Globals +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var toStr = Object.prototype.toString; +var max = Math.max; +var funcType = '[object Function]'; -var newInvalidAsn1Error = errors.newInvalidAsn1Error; +var concatty = function concatty(a, b) { + var arr = []; -var DEFAULT_OPTS = { - size: 1024, - growthFactor: 8 + for (var i = 0; i < a.length; i += 1) { + arr[i] = a[i]; + } + for (var j = 0; j < b.length; j += 1) { + arr[j + a.length] = b[j]; + } + + return arr; }; +var slicy = function slicy(arrLike, offset) { + var arr = []; + for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { + arr[j] = arrLike[i]; + } + return arr; +}; -// --- Helpers +var joiny = function (arr, joiner) { + var str = ''; + for (var i = 0; i < arr.length; i += 1) { + str += arr[i]; + if (i + 1 < arr.length) { + str += joiner; + } + } + return str; +}; -function merge(from, to) { - assert.ok(from); - assert.equal(typeof (from), 'object'); - assert.ok(to); - assert.equal(typeof (to), 'object'); +module.exports = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.apply(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slicy(arguments, 1); - var keys = Object.getOwnPropertyNames(from); - keys.forEach(function (key) { - if (to[key]) - return; + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + concatty(args, arguments) + ); + if (Object(result) === result) { + return result; + } + return this; + } + return target.apply( + that, + concatty(args, arguments) + ); - var value = Object.getOwnPropertyDescriptor(from, key); - Object.defineProperty(to, key, value); - }); + }; - return to; -} + var boundLength = max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs[i] = '$' + i; + } + bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } -// --- API + return bound; +}; -function Writer(options) { - options = merge(DEFAULT_OPTS, options || {}); - this._buf = Buffer.alloc(options.size || 1024); - this._size = this._buf.length; - this._offset = 0; - this._options = options; +/***/ }), - // A list of offsets in the buffer where we need to insert - // sequence tag/len pairs. - this._seq = []; -} +/***/ 69839: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Object.defineProperty(Writer.prototype, 'buffer', { - get: function () { - if (this._seq.length) - throw newInvalidAsn1Error(this._seq.length + ' unended sequence(s)'); +"use strict"; - return (this._buf.slice(0, this._offset)); - } -}); -Writer.prototype.writeByte = function (b) { - if (typeof (b) !== 'number') - throw new TypeError('argument must be a Number'); +var implementation = __nccwpck_require__(85316); - this._ensure(1); - this._buf[this._offset++] = b; -}; +module.exports = Function.prototype.bind || implementation; -Writer.prototype.writeInt = function (i, tag) { - if (typeof (i) !== 'number') - throw new TypeError('argument must be a Number'); - if (typeof (tag) !== 'number') - tag = ASN1.Integer; +/***/ }), - var sz = 4; +/***/ 48309: +/***/ ((module) => { - while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) && - (sz > 1)) { - sz--; - i <<= 8; - } +"use strict"; - if (sz > 4) - throw newInvalidAsn1Error('BER ints cannot be > 0xffffffff'); - this._ensure(2 + sz); - this._buf[this._offset++] = tag; - this._buf[this._offset++] = sz; +/** @type {import('./reflectApply')} */ +module.exports = typeof Reflect !== 'undefined' && Reflect && Reflect.apply; - while (sz-- > 0) { - this._buf[this._offset++] = ((i & 0xff000000) >>> 24); - i <<= 8; - } -}; +/***/ }), +/***/ 35684: +/***/ ((module) => { -Writer.prototype.writeNull = function () { - this.writeByte(ASN1.Null); - this.writeByte(0x00); -}; +function Caseless (dict) { + this.dict = dict || {} +} +Caseless.prototype.set = function (name, value, clobber) { + if (typeof name === 'object') { + for (var i in name) { + this.set(i, name[i], value) + } + } else { + if (typeof clobber === 'undefined') clobber = true + var has = this.has(name) + if (!clobber && has) this.dict[has] = this.dict[has] + ',' + value + else this.dict[has || name] = value + return has + } +} +Caseless.prototype.has = function (name) { + var keys = Object.keys(this.dict) + , name = name.toLowerCase() + ; + for (var i=0;i { - this._ensure(3); - this._buf[this._offset++] = tag; - this._buf[this._offset++] = 0x01; - this._buf[this._offset++] = b ? 0xff : 0x00; -}; +"use strict"; +const fs = __nccwpck_require__(57147) +const path = __nccwpck_require__(71017) -Writer.prototype.writeString = function (s, tag) { - if (typeof (s) !== 'string') - throw new TypeError('argument must be a string (was: ' + typeof (s) + ')'); - if (typeof (tag) !== 'number') - tag = ASN1.OctetString; +/* istanbul ignore next */ +const LCHOWN = fs.lchown ? 'lchown' : 'chown' +/* istanbul ignore next */ +const LCHOWNSYNC = fs.lchownSync ? 'lchownSync' : 'chownSync' - var len = Buffer.byteLength(s); - this.writeByte(tag); - this.writeLength(len); - if (len) { - this._ensure(len); - this._buf.write(s, this._offset); - this._offset += len; +/* istanbul ignore next */ +const needEISDIRHandled = fs.lchown && + !process.version.match(/v1[1-9]+\./) && + !process.version.match(/v10\.[6-9]/) + +const lchownSync = (path, uid, gid) => { + try { + return fs[LCHOWNSYNC](path, uid, gid) + } catch (er) { + if (er.code !== 'ENOENT') + throw er } -}; +} +/* istanbul ignore next */ +const chownSync = (path, uid, gid) => { + try { + return fs.chownSync(path, uid, gid) + } catch (er) { + if (er.code !== 'ENOENT') + throw er + } +} -Writer.prototype.writeBuffer = function (buf, tag) { - if (typeof (tag) !== 'number') - throw new TypeError('tag must be a number'); - if (!Buffer.isBuffer(buf)) - throw new TypeError('argument must be a buffer'); +/* istanbul ignore next */ +const handleEISDIR = + needEISDIRHandled ? (path, uid, gid, cb) => er => { + // Node prior to v10 had a very questionable implementation of + // fs.lchown, which would always try to call fs.open on a directory + // Fall back to fs.chown in those cases. + if (!er || er.code !== 'EISDIR') + cb(er) + else + fs.chown(path, uid, gid, cb) + } + : (_, __, ___, cb) => cb - this.writeByte(tag); - this.writeLength(buf.length); - this._ensure(buf.length); - buf.copy(this._buf, this._offset, 0, buf.length); - this._offset += buf.length; -}; +/* istanbul ignore next */ +const handleEISDirSync = + needEISDIRHandled ? (path, uid, gid) => { + try { + return lchownSync(path, uid, gid) + } catch (er) { + if (er.code !== 'EISDIR') + throw er + chownSync(path, uid, gid) + } + } + : (path, uid, gid) => lchownSync(path, uid, gid) +// fs.readdir could only accept an options object as of node v6 +const nodeVersion = process.version +let readdir = (path, options, cb) => fs.readdir(path, options, cb) +let readdirSync = (path, options) => fs.readdirSync(path, options) +/* istanbul ignore next */ +if (/^v4\./.test(nodeVersion)) + readdir = (path, options, cb) => fs.readdir(path, cb) -Writer.prototype.writeStringArray = function (strings) { - if ((!strings instanceof Array)) - throw new TypeError('argument must be an Array[String]'); +const chown = (cpath, uid, gid, cb) => { + fs[LCHOWN](cpath, uid, gid, handleEISDIR(cpath, uid, gid, er => { + // Skip ENOENT error + cb(er && er.code !== 'ENOENT' ? er : null) + })) +} - var self = this; - strings.forEach(function (s) { - self.writeString(s); - }); -}; +const chownrKid = (p, child, uid, gid, cb) => { + if (typeof child === 'string') + return fs.lstat(path.resolve(p, child), (er, stats) => { + // Skip ENOENT error + if (er) + return cb(er.code !== 'ENOENT' ? er : null) + stats.name = child + chownrKid(p, stats, uid, gid, cb) + }) -// This is really to solve DER cases, but whatever for now -Writer.prototype.writeOID = function (s, tag) { - if (typeof (s) !== 'string') - throw new TypeError('argument must be a string'); - if (typeof (tag) !== 'number') - tag = ASN1.OID; + if (child.isDirectory()) { + chownr(path.resolve(p, child.name), uid, gid, er => { + if (er) + return cb(er) + const cpath = path.resolve(p, child.name) + chown(cpath, uid, gid, cb) + }) + } else { + const cpath = path.resolve(p, child.name) + chown(cpath, uid, gid, cb) + } +} - if (!/^([0-9]+\.){3,}[0-9]+$/.test(s)) - throw new Error('argument is not a valid OID string'); - function encodeOctet(bytes, octet) { - if (octet < 128) { - bytes.push(octet); - } else if (octet < 16384) { - bytes.push((octet >>> 7) | 0x80); - bytes.push(octet & 0x7F); - } else if (octet < 2097152) { - bytes.push((octet >>> 14) | 0x80); - bytes.push(((octet >>> 7) | 0x80) & 0xFF); - bytes.push(octet & 0x7F); - } else if (octet < 268435456) { - bytes.push((octet >>> 21) | 0x80); - bytes.push(((octet >>> 14) | 0x80) & 0xFF); - bytes.push(((octet >>> 7) | 0x80) & 0xFF); - bytes.push(octet & 0x7F); - } else { - bytes.push(((octet >>> 28) | 0x80) & 0xFF); - bytes.push(((octet >>> 21) | 0x80) & 0xFF); - bytes.push(((octet >>> 14) | 0x80) & 0xFF); - bytes.push(((octet >>> 7) | 0x80) & 0xFF); - bytes.push(octet & 0x7F); +const chownr = (p, uid, gid, cb) => { + readdir(p, { withFileTypes: true }, (er, children) => { + // any error other than ENOTDIR or ENOTSUP means it's not readable, + // or doesn't exist. give up. + if (er) { + if (er.code === 'ENOENT') + return cb() + else if (er.code !== 'ENOTDIR' && er.code !== 'ENOTSUP') + return cb(er) + } + if (er || !children.length) + return chown(p, uid, gid, cb) + + let len = children.length + let errState = null + const then = er => { + if (errState) + return + if (er) + return cb(errState = er) + if (-- len === 0) + return chown(p, uid, gid, cb) + } + + children.forEach(child => chownrKid(p, child, uid, gid, then)) + }) +} + +const chownrKidSync = (p, child, uid, gid) => { + if (typeof child === 'string') { + try { + const stats = fs.lstatSync(path.resolve(p, child)) + stats.name = child + child = stats + } catch (er) { + if (er.code === 'ENOENT') + return + else + throw er } } - var tmp = s.split('.'); - var bytes = []; - bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10)); - tmp.slice(2).forEach(function (b) { - encodeOctet(bytes, parseInt(b, 10)); - }); + if (child.isDirectory()) + chownrSync(path.resolve(p, child.name), uid, gid) - var self = this; - this._ensure(2 + bytes.length); - this.writeByte(tag); - this.writeLength(bytes.length); - bytes.forEach(function (b) { - self.writeByte(b); - }); -}; + handleEISDirSync(path.resolve(p, child.name), uid, gid) +} +const chownrSync = (p, uid, gid) => { + let children + try { + children = readdirSync(p, { withFileTypes: true }) + } catch (er) { + if (er.code === 'ENOENT') + return + else if (er.code === 'ENOTDIR' || er.code === 'ENOTSUP') + return handleEISDirSync(p, uid, gid) + else + throw er + } -Writer.prototype.writeLength = function (len) { - if (typeof (len) !== 'number') - throw new TypeError('argument must be a Number'); + if (children && children.length) + children.forEach(child => chownrKidSync(p, child, uid, gid)) - this._ensure(4); + return handleEISDirSync(p, uid, gid) +} - if (len <= 0x7f) { - this._buf[this._offset++] = len; - } else if (len <= 0xff) { - this._buf[this._offset++] = 0x81; - this._buf[this._offset++] = len; - } else if (len <= 0xffff) { - this._buf[this._offset++] = 0x82; - this._buf[this._offset++] = len >> 8; - this._buf[this._offset++] = len; - } else if (len <= 0xffffff) { - this._buf[this._offset++] = 0x83; - this._buf[this._offset++] = len >> 16; - this._buf[this._offset++] = len >> 8; - this._buf[this._offset++] = len; - } else { - throw newInvalidAsn1Error('Length too long (> 4 bytes)'); - } -}; +module.exports = chownr +chownr.sync = chownrSync -Writer.prototype.startSequence = function (tag) { - if (typeof (tag) !== 'number') - tag = ASN1.Sequence | ASN1.Constructor; - this.writeByte(tag); - this._seq.push(this._offset); - this._ensure(3); - this._offset += 3; -}; +/***/ }), +/***/ 27972: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Writer.prototype.endSequence = function () { - var seq = this._seq.pop(); - var start = seq + 3; - var len = this._offset - start; +"use strict"; - if (len <= 0x7f) { - this._shift(start, len, -2); - this._buf[seq] = len; - } else if (len <= 0xff) { - this._shift(start, len, -1); - this._buf[seq] = 0x81; - this._buf[seq + 1] = len; - } else if (len <= 0xffff) { - this._buf[seq] = 0x82; - this._buf[seq + 1] = len >> 8; - this._buf[seq + 2] = len; - } else if (len <= 0xffffff) { - this._shift(start, len, 1); - this._buf[seq] = 0x83; - this._buf[seq + 1] = len >> 16; - this._buf[seq + 2] = len >> 8; - this._buf[seq + 3] = len; - } else { - throw newInvalidAsn1Error('Sequence too long'); - } -}; +const os = __nccwpck_require__(22037); +const extractPathRegex = /\s+at.*(?:\(|\s)(.*)\)?/; +const pathRegex = /^(?:(?:(?:node|(?:internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)\.js:\d+:\d+)|native)/; +const homeDir = typeof os.homedir === 'undefined' ? '' : os.homedir(); -Writer.prototype._shift = function (start, len, shift) { - assert.ok(start !== undefined); - assert.ok(len !== undefined); - assert.ok(shift); +module.exports = (stack, options) => { + options = Object.assign({pretty: false}, options); - this._buf.copy(this._buf, start + shift, start, start + len); - this._offset += shift; -}; + return stack.replace(/\\/g, '/') + .split('\n') + .filter(line => { + const pathMatches = line.match(extractPathRegex); + if (pathMatches === null || !pathMatches[1]) { + return true; + } -Writer.prototype._ensure = function (len) { - assert.ok(len); + const match = pathMatches[1]; - if (this._size - this._offset < len) { - var sz = this._size * this._options.growthFactor; - if (sz - this._offset < len) - sz += len; + // Electron + if ( + match.includes('.app/Contents/Resources/electron.asar') || + match.includes('.app/Contents/Resources/default_app.asar') + ) { + return false; + } - var buf = Buffer.alloc(sz); + return !pathRegex.test(match); + }) + .filter(line => line.trim() !== '') + .map(line => { + if (options.pretty) { + return line.replace(extractPathRegex, (m, p1) => m.replace(p1, p1.replace(homeDir, '~'))); + } - this._buf.copy(buf, 0, 0, this._offset); - this._buf = buf; - this._size = sz; - } + return line; + }) + .join('\n'); }; +/***/ }), -// --- Exported API +/***/ 69372: +/***/ ((module) => { -module.exports = Writer; +"use strict"; -/***/ }), +// We define these manually to ensure they're always copied +// even if they would move up the prototype chain +// https://nodejs.org/api/http.html#http_class_http_incomingmessage +const knownProps = [ + 'destroy', + 'setTimeout', + 'socket', + 'headers', + 'trailers', + 'rawHeaders', + 'statusCode', + 'httpVersion', + 'httpVersionMinor', + 'httpVersionMajor', + 'rawTrailers', + 'statusMessage' +]; -/***/ 80970: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +module.exports = (fromStream, toStream) => { + const fromProps = new Set(Object.keys(fromStream).concat(knownProps)); -// Copyright 2011 Mark Cavage All rights reserved. + for (const prop of fromProps) { + // Don't overwrite existing properties + if (prop in toStream) { + continue; + } -// If you have no idea what ASN.1 or BER is, see this: -// ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc + toStream[prop] = typeof fromStream[prop] === 'function' ? fromStream[prop].bind(fromStream) : fromStream[prop]; + } +}; -var Ber = __nccwpck_require__(194); +/***/ }), +/***/ 81312: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// --- Exported API +"use strict"; -module.exports = { - Ber: Ber, +const PassThrough = (__nccwpck_require__(12781).PassThrough); +const mimicResponse = __nccwpck_require__(69372); - BerReader: Ber.Reader, +const cloneResponse = response => { + if (!(response && response.pipe)) { + throw new TypeError('Parameter `response` must be a response stream.'); + } - BerWriter: Ber.Writer + const clone = new PassThrough(); + mimicResponse(response, clone); + return response.pipe(clone); }; +module.exports = cloneResponse; + /***/ }), -/***/ 66631: +/***/ 85443: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Copyright (c) 2012, Mark Cavage. All rights reserved. -// Copyright 2015 Joyent, Inc. - -var assert = __nccwpck_require__(39491); -var Stream = (__nccwpck_require__(12781).Stream); var util = __nccwpck_require__(73837); +var Stream = (__nccwpck_require__(12781).Stream); +var DelayedStream = __nccwpck_require__(18611); +module.exports = CombinedStream; +function CombinedStream() { + this.writable = false; + this.readable = true; + this.dataSize = 0; + this.maxDataSize = 2 * 1024 * 1024; + this.pauseStreams = true; -///--- Globals + this._released = false; + this._streams = []; + this._currentStream = null; + this._insideLoop = false; + this._pendingNext = false; +} +util.inherits(CombinedStream, Stream); -/* JSSTYLED */ -var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/; +CombinedStream.create = function(options) { + var combinedStream = new this(); + options = options || {}; + for (var option in options) { + combinedStream[option] = options[option]; + } -///--- Internal + return combinedStream; +}; -function _capitalize(str) { - return (str.charAt(0).toUpperCase() + str.slice(1)); -} +CombinedStream.isStreamLike = function(stream) { + return (typeof stream !== 'function') + && (typeof stream !== 'string') + && (typeof stream !== 'boolean') + && (typeof stream !== 'number') + && (!Buffer.isBuffer(stream)); +}; -function _toss(name, expected, oper, arg, actual) { - throw new assert.AssertionError({ - message: util.format('%s (%s) is required', name, expected), - actual: (actual === undefined) ? typeof (arg) : actual(arg), - expected: expected, - operator: oper || '===', - stackStartFunction: _toss.caller - }); -} +CombinedStream.prototype.append = function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); -function _getClass(arg) { - return (Object.prototype.toString.call(arg).slice(8, -1)); -} + if (isStreamLike) { + if (!(stream instanceof DelayedStream)) { + var newStream = DelayedStream.create(stream, { + maxDataSize: Infinity, + pauseStream: this.pauseStreams, + }); + stream.on('data', this._checkDataSize.bind(this)); + stream = newStream; + } -function noop() { - // Why even bother with asserts? -} + this._handleErrors(stream); + if (this.pauseStreams) { + stream.pause(); + } + } -///--- Exports + this._streams.push(stream); + return this; +}; -var types = { - bool: { - check: function (arg) { return typeof (arg) === 'boolean'; } - }, - func: { - check: function (arg) { return typeof (arg) === 'function'; } - }, - string: { - check: function (arg) { return typeof (arg) === 'string'; } - }, - object: { - check: function (arg) { - return typeof (arg) === 'object' && arg !== null; - } - }, - number: { - check: function (arg) { - return typeof (arg) === 'number' && !isNaN(arg); - } - }, - finite: { - check: function (arg) { - return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg); - } - }, - buffer: { - check: function (arg) { return Buffer.isBuffer(arg); }, - operator: 'Buffer.isBuffer' - }, - array: { - check: function (arg) { return Array.isArray(arg); }, - operator: 'Array.isArray' - }, - stream: { - check: function (arg) { return arg instanceof Stream; }, - operator: 'instanceof', - actual: _getClass - }, - date: { - check: function (arg) { return arg instanceof Date; }, - operator: 'instanceof', - actual: _getClass - }, - regexp: { - check: function (arg) { return arg instanceof RegExp; }, - operator: 'instanceof', - actual: _getClass - }, - uuid: { - check: function (arg) { - return typeof (arg) === 'string' && UUID_REGEXP.test(arg); - }, - operator: 'isUUID' - } +CombinedStream.prototype.pipe = function(dest, options) { + Stream.prototype.pipe.call(this, dest, options); + this.resume(); + return dest; }; -function _setExports(ndebug) { - var keys = Object.keys(types); - var out; +CombinedStream.prototype._getNext = function() { + this._currentStream = null; - /* re-export standard assert */ - if (process.env.NODE_NDEBUG) { - out = noop; - } else { - out = function (arg, msg) { - if (!arg) { - _toss(msg, 'true', arg); - } - }; - } + if (this._insideLoop) { + this._pendingNext = true; + return; // defer call + } - /* standard checks */ - keys.forEach(function (k) { - if (ndebug) { - out[k] = noop; - return; - } - var type = types[k]; - out[k] = function (arg, msg) { - if (!type.check(arg)) { - _toss(msg, k, type.operator, arg, type.actual); - } - }; - }); + this._insideLoop = true; + try { + do { + this._pendingNext = false; + this._realGetNext(); + } while (this._pendingNext); + } finally { + this._insideLoop = false; + } +}; - /* optional checks */ - keys.forEach(function (k) { - var name = 'optional' + _capitalize(k); - if (ndebug) { - out[name] = noop; - return; - } - var type = types[k]; - out[name] = function (arg, msg) { - if (arg === undefined || arg === null) { - return; - } - if (!type.check(arg)) { - _toss(msg, k, type.operator, arg, type.actual); - } - }; - }); +CombinedStream.prototype._realGetNext = function() { + var stream = this._streams.shift(); - /* arrayOf checks */ - keys.forEach(function (k) { - var name = 'arrayOf' + _capitalize(k); - if (ndebug) { - out[name] = noop; - return; - } - var type = types[k]; - var expected = '[' + k + ']'; - out[name] = function (arg, msg) { - if (!Array.isArray(arg)) { - _toss(msg, expected, type.operator, arg, type.actual); - } - var i; - for (i = 0; i < arg.length; i++) { - if (!type.check(arg[i])) { - _toss(msg, expected, type.operator, arg, type.actual); - } - } - }; - }); - /* optionalArrayOf checks */ - keys.forEach(function (k) { - var name = 'optionalArrayOf' + _capitalize(k); - if (ndebug) { - out[name] = noop; - return; - } - var type = types[k]; - var expected = '[' + k + ']'; - out[name] = function (arg, msg) { - if (arg === undefined || arg === null) { - return; - } - if (!Array.isArray(arg)) { - _toss(msg, expected, type.operator, arg, type.actual); - } - var i; - for (i = 0; i < arg.length; i++) { - if (!type.check(arg[i])) { - _toss(msg, expected, type.operator, arg, type.actual); - } - } - }; - }); + if (typeof stream == 'undefined') { + this.end(); + return; + } - /* re-export built-in assertions */ - Object.keys(assert).forEach(function (k) { - if (k === 'AssertionError') { - out[k] = assert[k]; - return; - } - if (ndebug) { - out[k] = noop; - return; - } - out[k] = assert[k]; - }); + if (typeof stream !== 'function') { + this._pipeNext(stream); + return; + } - /* export ourselves (for unit tests _only_) */ - out._setExports = _setExports; + var getStream = stream; + getStream(function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('data', this._checkDataSize.bind(this)); + this._handleErrors(stream); + } - return out; -} + this._pipeNext(stream); + }.bind(this)); +}; -module.exports = _setExports(process.env.NODE_NDEBUG); +CombinedStream.prototype._pipeNext = function(stream) { + this._currentStream = stream; + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('end', this._getNext.bind(this)); + stream.pipe(this, {end: false}); + return; + } -/***/ }), + var value = stream; + this.write(value); + this._getNext(); +}; -/***/ 41299: -/***/ (function(__unused_webpack_module, exports) { +CombinedStream.prototype._handleErrors = function(stream) { + var self = this; + stream.on('error', function(err) { + self._emitError(err); + }); +}; -!function(e,t){ true?t(exports):0}(this,(function(e){"use strict";class t extends Error{constructor(e){super(null!=e?`Timed out after waiting for ${e} ms`:"Timed out"),Object.setPrototypeOf(this,t.prototype)}}const o=(e,t)=>new Promise(((o,n)=>{try{e.schedule(o,t)}catch(e){n(e)}})),n={schedule:(e,t)=>{let o;const n=e=>{null!=e&&clearTimeout(e),o=void 0};return o=setTimeout((()=>{n(o),e()}),t),{cancel:()=>n(o)}}},i=Number.POSITIVE_INFINITY,r=(e,r,l)=>{var u,s;const c=null!==(u="number"==typeof r?r:null==r?void 0:r.timeout)&&void 0!==u?u:5e3,d=null!==(s="number"==typeof r?l:null==r?void 0:r.intervalBetweenAttempts)&&void 0!==s?s:50;let a=!1;const f=()=>new Promise(((t,i)=>{const r=()=>{a||new Promise(((t,o)=>{try{t(e())}catch(e){o(e)}})).then((e=>{e?t(e):o(n,d).then(r).catch(i)})).catch(i)};r()})),T=c!==i?()=>o(n,c).then((()=>{throw a=!0,new t(c)})):void 0;return null!=T?Promise.race([f(),T()]):f()};e.DEFAULT_INTERVAL_BETWEEN_ATTEMPTS_IN_MS=50,e.DEFAULT_TIMEOUT_IN_MS=5e3,e.TimeoutError=t,e.WAIT_FOREVER=i,e.default=r,e.waitUntil=r,Object.defineProperty(e,"__esModule",{value:!0})}));//# sourceMappingURL=index.js.map +CombinedStream.prototype.write = function(data) { + this.emit('data', data); +}; +CombinedStream.prototype.pause = function() { + if (!this.pauseStreams) { + return; + } -/***/ }), + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause(); + this.emit('pause'); +}; -/***/ 14812: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +CombinedStream.prototype.resume = function() { + if (!this._released) { + this._released = true; + this.writable = true; + this._getNext(); + } -module.exports = -{ - parallel : __nccwpck_require__(8210), - serial : __nccwpck_require__(50445), - serialOrdered : __nccwpck_require__(3578) + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume(); + this.emit('resume'); }; +CombinedStream.prototype.end = function() { + this._reset(); + this.emit('end'); +}; -/***/ }), +CombinedStream.prototype.destroy = function() { + this._reset(); + this.emit('close'); +}; -/***/ 1700: -/***/ ((module) => { +CombinedStream.prototype._reset = function() { + this.writable = false; + this._streams = []; + this._currentStream = null; +}; -// API -module.exports = abort; +CombinedStream.prototype._checkDataSize = function() { + this._updateDataSize(); + if (this.dataSize <= this.maxDataSize) { + return; + } -/** - * Aborts leftover active jobs - * - * @param {object} state - current state object - */ -function abort(state) -{ - Object.keys(state.jobs).forEach(clean.bind(state)); + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'; + this._emitError(new Error(message)); +}; - // reset leftover jobs - state.jobs = {}; -} +CombinedStream.prototype._updateDataSize = function() { + this.dataSize = 0; -/** - * Cleans up leftover job by invoking abort function for the provided job id - * - * @this state - * @param {string|number} key - job id to abort - */ -function clean(key) -{ - if (typeof this.jobs[key] == 'function') - { - this.jobs[key](); - } -} + var self = this; + this._streams.forEach(function(stream) { + if (!stream.dataSize) { + return; + } + self.dataSize += stream.dataSize; + }); -/***/ }), + if (this._currentStream && this._currentStream.dataSize) { + this.dataSize += this._currentStream.dataSize; + } +}; -/***/ 72794: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +CombinedStream.prototype._emitError = function(err) { + this._reset(); + this.emit('error', err); +}; -var defer = __nccwpck_require__(15295); -// API -module.exports = async; +/***/ }), -/** - * Runs provided callback asynchronously - * even if callback itself is not - * - * @param {function} callback - callback to invoke - * @returns {function} - augmented callback - */ -function async(callback) -{ - var isAsync = false; +/***/ 17044: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // check if async happened - defer(function() { isAsync = true; }); +"use strict"; - return function async_callback(err, result) - { - if (isAsync) - { - callback(err, result); - } - else - { - defer(function nextTick_callback() - { - callback(err, result); - }); - } - }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.action = void 0; +const commander = __nccwpck_require__(86987); +function action() { + return (target, propertyKey, descriptor) => { + commander.action(target[propertyKey]); + }; } - +exports.action = action; +//# sourceMappingURL=action.decorator.js.map /***/ }), -/***/ 15295: -/***/ ((module) => { - -module.exports = defer; +/***/ 71303: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * Runs provided function on next iteration of the event loop - * - * @param {function} fn - function to run - */ -function defer(fn) -{ - var nextTick = typeof setImmediate == 'function' - ? setImmediate - : ( - typeof process == 'object' && typeof process.nextTick == 'function' - ? process.nextTick - : null - ); +"use strict"; - if (nextTick) - { - nextTick(fn); - } - else - { - setTimeout(fn, 0); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.alias = void 0; +const program = __nccwpck_require__(86987); +function alias(text) { + return (target) => { + program.usage(text); + }; } - +exports.alias = alias; +//# sourceMappingURL=alias.decorator.js.map /***/ }), -/***/ 9023: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var async = __nccwpck_require__(72794) - , abort = __nccwpck_require__(1700) - ; +/***/ 55508: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// API -module.exports = iterate; +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.variadicArg = exports.requiredArg = exports.optionalArg = void 0; +const metadata_1 = __nccwpck_require__(104); +const models_1 = __nccwpck_require__(84908); +const utils_1 = __nccwpck_require__(66725); /** - * Iterates over each job object - * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {object} state - current job status - * @param {function} callback - invoked when all elements processed + * Parameter decorator used in subcommand function to denote an optional argument. */ -function iterate(list, iterator, state, callback) -{ - // store current index - var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; - - state.jobs[key] = runJob(iterator, key, list[key], function(error, output) - { - // don't repeat yourself - // skip secondary callbacks - if (!(key in state.jobs)) - { - return; - } - - // clean up jobs - delete state.jobs[key]; - - if (error) - { - // don't process rest of the results - // stop still active jobs - // and reset the list - abort(state); - } - else - { - state.results[key] = output; - } - - // return salvaged results - callback(error, state.results); - }); +function optionalArg(name) { + return (target, propertyKey, parameterIndex) => { + const args = (0, utils_1.decorateIfNot)(metadata_1.ArgsMetadata, [], target, propertyKey); + args.unshift(new models_1.OptionalArg(name, parameterIndex)); + }; } - +exports.optionalArg = optionalArg; /** - * Runs iterator over provided job element - * - * @param {function} iterator - iterator to invoke - * @param {string|number} key - key/index of the element in the list of jobs - * @param {mixed} item - job description - * @param {function} callback - invoked after iterator is done with the job - * @returns {function|mixed} - job abort function or something else + * Parameter decorator used in subcommand function to denote a required argument. */ -function runJob(iterator, key, item, callback) -{ - var aborter; +function requiredArg(name) { + return (target, propertyKey, parameterIndex) => { + const args = (0, utils_1.decorateIfNot)(metadata_1.ArgsMetadata, [], target, propertyKey); + args.unshift(new models_1.RequiredArg(name, parameterIndex)); + }; +} +exports.requiredArg = requiredArg; +/** + * Parameter decorator used in subcommand function to denote variadic arguments. + */ +function variadicArg(name) { + return (target, propertyKey, parameterIndex) => { + const args = (0, utils_1.decorateIfNot)(metadata_1.ArgsMetadata, [], target, propertyKey); + args.unshift(new models_1.VariadicArg(name, parameterIndex)); + }; +} +exports.variadicArg = variadicArg; +//# sourceMappingURL=arg.decorator.js.map - // allow shortcut if iterator expects only two arguments - if (iterator.length == 2) - { - aborter = iterator(item, async(callback)); - } - // otherwise go with full three arguments - else - { - aborter = iterator(item, key, async(callback)); - } +/***/ }), - return aborter; -} +/***/ 71196: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; -/***/ }), +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.args = void 0; +const commander = __nccwpck_require__(86987); +function args() { + return (target, propertyKey, parameterIndex) => { + commander + .option(propertyKey) + .action(target[propertyKey]); + }; +} +exports.args = args; +//# sourceMappingURL=arguments.decorator.js.map -/***/ 42474: -/***/ ((module) => { +/***/ }), -// API -module.exports = state; +/***/ 69904: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * Creates initial state object - * for iteration over list - * - * @param {array|object} list - list to iterate over - * @param {function|null} sortMethod - function to use for keys sort, - * or `null` to keep them as is - * @returns {object} - initial state object - */ -function state(list, sortMethod) -{ - var isNamedList = !Array.isArray(list) - , initState = - { - index : 0, - keyedList: isNamedList || sortMethod ? Object.keys(list) : null, - jobs : {}, - results : isNamedList ? {} : [], - size : isNamedList ? Object.keys(list).length : list.length - } - ; +"use strict"; - if (sortMethod) - { - // sort array keys based on it's values - // sort object's keys just on own merit - initState.keyedList.sort(isNamedList ? sortMethod : function(a, b) - { - return sortMethod(list[a], list[b]); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.commandOption = void 0; +const metadata_1 = __nccwpck_require__(104); +const utils_1 = __nccwpck_require__(66725); +function commandOption(...args) { + return ((target, propertyKey, descriptor) => { + args[0] = args[0] || `--${String(propertyKey)}`; + (0, utils_1.decorateIfNot)(metadata_1.CommandOptionsMetadata, [], target, propertyKey); + const options = Reflect.getMetadata(metadata_1.CommandOptionsMetadata, target, propertyKey); + options.push(args); }); - } - - return initState; } - +exports.commandOption = commandOption; +//# sourceMappingURL=command-option.decorator.js.map /***/ }), -/***/ 37942: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 1442: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -var abort = __nccwpck_require__(1700) - , async = __nccwpck_require__(72794) - ; +"use strict"; -// API -module.exports = terminator; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.command = void 0; +const commander = __nccwpck_require__(86987); +const helpers_1 = __nccwpck_require__(69882); +const metadata_1 = __nccwpck_require__(104); +function command() { + return (target, propertyKey, descriptor) => { + try { + const cmd = (0, helpers_1.prepareSubcommand)(target, propertyKey); + let chain = commander.command(cmd); + if (Reflect.hasMetadata(metadata_1.CommandOptionsMetadata, target, propertyKey)) { + const options = Reflect.getMetadata(metadata_1.CommandOptionsMetadata, target, propertyKey); + chain = options.reduce((prev, opt) => { + const [arg1, arg2, arg3, arg4] = opt; + return chain.option(arg1, arg2, arg3, arg4); + }, chain); + } + chain.action((...args) => __awaiter(this, void 0, void 0, function* () { + const context = args[args.length - 1]; + const cmdArgs = args.slice(0, args.length - 1); + try { + const result = target[propertyKey].apply(context, cmdArgs); + if (result instanceof Promise) { + yield result; + } + } + catch (_a) { + process.exit(1); + } + finally { + process.exit(0); + } + })); + } + catch (e) { + console.error(e.message); + process.exit(1); + } + }; +} +exports.command = command; +//# sourceMappingURL=command.decorator.js.map -/** - * Terminates jobs in the attached state context - * - * @this AsyncKitState# - * @param {function} callback - final callback to invoke after termination - */ -function terminator(callback) -{ - if (!Object.keys(this.jobs).length) - { - return; - } +/***/ }), - // fast forward iteration index - this.index = this.size; +/***/ 14432: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // abort jobs - abort(this); +"use strict"; - // send back results we have so far - async(callback)(null, this.results); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.description = void 0; +const program = __nccwpck_require__(86987); +function description(text) { + return (target) => { + program.description(text); + }; } - +exports.description = description; +//# sourceMappingURL=description.decorator.js.map /***/ }), -/***/ 8210: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var iterate = __nccwpck_require__(9023) - , initState = __nccwpck_require__(42474) - , terminator = __nccwpck_require__(37942) - ; - -// Public API -module.exports = parallel; +/***/ 90154: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -/** - * Runs iterator over provided array elements in parallel - * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {function} callback - invoked when all elements processed - * @returns {function} - jobs terminator - */ -function parallel(list, iterator, callback) -{ - var state = initState(list); +"use strict"; - while (state.index < (state['keyedList'] || list).length) - { - iterate(list, iterator, state, function(error, result) - { - if (error) - { - callback(error, result); - return; - } +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (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 })); +__exportStar(__nccwpck_require__(104), exports); +__exportStar(__nccwpck_require__(17044), exports); +__exportStar(__nccwpck_require__(71303), exports); +__exportStar(__nccwpck_require__(55508), exports); +__exportStar(__nccwpck_require__(71196), exports); +__exportStar(__nccwpck_require__(69904), exports); +__exportStar(__nccwpck_require__(1442), exports); +__exportStar(__nccwpck_require__(14432), exports); +__exportStar(__nccwpck_require__(98166), exports); +__exportStar(__nccwpck_require__(42991), exports); +__exportStar(__nccwpck_require__(3813), exports); +__exportStar(__nccwpck_require__(84768), exports); +__exportStar(__nccwpck_require__(98162), exports); +//# sourceMappingURL=index.js.map - // looks like it's the last one - if (Object.keys(state.jobs).length === 0) - { - callback(null, state.results); - return; - } - }); +/***/ }), - state.index++; - } +/***/ 98166: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return terminator.bind(state, callback); -} +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.on = void 0; +const commander = __nccwpck_require__(86987); +function on(event, handler) { + return (target, propertyKey, descriptor) => { + commander.on(event, handler); + }; +} +exports.on = on; +//# sourceMappingURL=on.decorator.js.map /***/ }), -/***/ 50445: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var serialOrdered = __nccwpck_require__(3578); +/***/ 42991: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// Public API -module.exports = serial; +"use strict"; -/** - * Runs iterator over provided array elements in series - * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {function} callback - invoked when all elements processed - * @returns {function} - jobs terminator - */ -function serial(list, iterator, callback) -{ - return serialOrdered(list, iterator, null, callback); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.option = void 0; +const metadata_1 = __nccwpck_require__(104); +const models_1 = __nccwpck_require__(84908); +const utils_1 = __nccwpck_require__(66725); +function option(...args) { + return ((target, propertyKey) => { + args[0] = args[0] || `--${String(propertyKey)}`; + (0, utils_1.decorateIfNot)(metadata_1.OptionsMetadata, [], target, propertyKey); + const options = Reflect.getMetadata(metadata_1.OptionsMetadata, target, propertyKey); + options.push(new models_1.Option(propertyKey, args)); + }); } - +exports.option = option; +//# sourceMappingURL=option.decorator.js.map /***/ }), -/***/ 3578: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var iterate = __nccwpck_require__(9023) - , initState = __nccwpck_require__(42474) - , terminator = __nccwpck_require__(37942) - ; - -// Public API -module.exports = serialOrdered; -// sorting helpers -module.exports.ascending = ascending; -module.exports.descending = descending; +/***/ 3813: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * Runs iterator over provided sorted array elements in series - * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {function} sortMethod - custom sort function - * @param {function} callback - invoked when all elements processed - * @returns {function} - jobs terminator - */ -function serialOrdered(list, iterator, sortMethod, callback) -{ - var state = initState(list, sortMethod); +"use strict"; - iterate(list, iterator, state, function iteratorHandler(error, result) - { - if (error) - { - callback(error, result); - return; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.program = void 0; +const commander = __nccwpck_require__(86987); +const helpers_1 = __nccwpck_require__(69882); +const metadata_1 = __nccwpck_require__(104); +let instances = 0; +function program() { + instances += 1; + if (instances > 1) { + throw new Error('Only one instance of @program is permitted.'); } - - state.index++; - - // are we there yet? - if (state.index < (state['keyedList'] || list).length) - { - iterate(list, iterator, state, iteratorHandler); - return; + return function (constructor) { + const mixin = class extends constructor { + constructor(...args) { + super(...args); + if (!this.run) { + console.error('Program class must define a run() method.'); + process.exit(1); + } + const cmd = (0, helpers_1.prepareCommand)(this, 'run'); + if (cmd) { + commander.command(cmd); + } + const options = Object.keys(this).reduce((list, prop) => { + if (Reflect.hasMetadata(metadata_1.OptionsMetadata, this, prop)) { + const metadata = Reflect.getMetadata(metadata_1.OptionsMetadata, this, prop); + list.push(metadata); + } + return list; + }, []); + const chainAfterOptions = options + .reduce((prev, option) => { + return prev.option.apply(prev, option[0].args); + }, commander); + commander.parse(process.argv); + if (this.run) { + this.run.apply(commander, (0, helpers_1.injectArgs)(commander, this, 'run')); + } + } + }; + (0, helpers_1.initCommander)(constructor); + return mixin; + }; +} +exports.program = program; +function prepareProgram(target) { + let argList = ''; + if (Reflect.hasMetadata(metadata_1.OptionsMetadata, target)) { + const args = Reflect.getMetadata(metadata_1.OptionsMetadata, target); + argList = args + .map((arg) => { + return arg.toString(); + }) + .join(' ') + .replace(/^(.)/, ' $1'); } - - // done here - callback(null, state.results); - }); - - return terminator.bind(state, callback); + return `${argList}`; } +//# sourceMappingURL=program.decorator.js.map -/* - * -- Sort methods - */ +/***/ }), -/** - * sort helper to sort array elements in ascending order - * - * @param {mixed} a - an item to compare - * @param {mixed} b - an item to compare - * @returns {number} - comparison result - */ -function ascending(a, b) -{ - return a < b ? -1 : a > b ? 1 : 0; -} +/***/ 84768: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * sort helper to sort array elements in descending order - * - * @param {mixed} a - an item to compare - * @param {mixed} b - an item to compare - * @returns {number} - comparison result - */ -function descending(a, b) -{ - return -1 * ascending(a, b); -} +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.usage = void 0; +const commander = __nccwpck_require__(86987); +function usage(text) { + return (target) => { + commander.usage(text); + }; +} +exports.usage = usage; +//# sourceMappingURL=usage.decorator.js.map /***/ }), -/***/ 96342: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - +/***/ 98162: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/*! - * Copyright 2010 LearnBoost - * - * 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. - */ +"use strict"; -/** - * Module dependencies. - */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.version = void 0; +const helpers_1 = __nccwpck_require__(69882); +const metadata_1 = __nccwpck_require__(104); +function version(text) { + return (target) => { + (0, helpers_1.initCommander)(target); + const program = Reflect.getMetadata(metadata_1.ProgramMetadata, target); + program.version(text); + }; +} +exports.version = version; +//# sourceMappingURL=version.decorator.js.map -var crypto = __nccwpck_require__(6113) - , parse = (__nccwpck_require__(57310).parse) - ; +/***/ }), -/** - * Valid keys. - */ +/***/ 69882: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -var keys = - [ 'acl' - , 'location' - , 'logging' - , 'notification' - , 'partNumber' - , 'policy' - , 'requestPayment' - , 'torrent' - , 'uploadId' - , 'uploads' - , 'versionId' - , 'versioning' - , 'versions' - , 'website' - ] +"use strict"; -/** - * Return an "Authorization" header value with the given `options` - * in the form of "AWS :" - * - * @param {Object} options - * @return {String} - * @api private - */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (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 })); +__exportStar(__nccwpck_require__(65339), exports); +__exportStar(__nccwpck_require__(70), exports); +__exportStar(__nccwpck_require__(11413), exports); +//# sourceMappingURL=index.js.map -function authorization (options) { - return 'AWS ' + options.key + ':' + sign(options) -} +/***/ }), -module.exports = authorization -module.exports.authorization = authorization +/***/ 65339: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * Simple HMAC-SHA1 Wrapper - * - * @param {Object} options - * @return {String} - * @api private - */ +"use strict"; -function hmacSha1 (options) { - return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64') +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.initCommander = void 0; +const commander = __nccwpck_require__(86987); +const metadata_1 = __nccwpck_require__(104); +function initCommander(target) { + if (!Reflect.hasMetadata(metadata_1.ProgramMetadata, target)) { + const decorator = Reflect.metadata(metadata_1.ProgramMetadata, commander); + Reflect.decorate([decorator], target); + } } +exports.initCommander = initCommander; +//# sourceMappingURL=init-commander.js.map -module.exports.hmacSha1 = hmacSha1 - -/** - * Create a base64 sha1 HMAC for `options`. - * - * @param {Object} options - * @return {String} - * @api private - */ +/***/ }), -function sign (options) { - options.message = stringToSign(options) - return hmacSha1(options) -} -module.exports.sign = sign +/***/ 70: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * Create a base64 sha1 HMAC for `options`. - * - * Specifically to be used with S3 presigned URLs - * - * @param {Object} options - * @return {String} - * @api private - */ +"use strict"; -function signQuery (options) { - options.message = queryStringToSign(options) - return hmacSha1(options) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.injectArgs = void 0; +const metadata_1 = __nccwpck_require__(104); +const index_1 = __nccwpck_require__(84908); +function injectArgs(program, target, propertyKey) { + if (Reflect.hasMetadata(metadata_1.ArgsMetadata, target, propertyKey)) { + const args = Reflect.getMetadata(metadata_1.ArgsMetadata, target, propertyKey); + const predicate = (arg) => arg instanceof index_1.VariadicArg; + const variadic = args.find(predicate); + if (variadic && (args.findIndex(predicate) !== (args.length - 1))) { + throw new TypeError(`Variadic argument must be specified last the argument list of the ${String(propertyKey)}() function.`); + } + const argv = []; + let index = 0; + for (let i = 0; i < args.length; i += 1) { + if (args.find(arg => arg.index === i)) { + argv.push(program.args[index]); + index += 1; + } + else { + argv.push(undefined); + } + } + return argv; + } } -module.exports.signQuery= signQuery +exports.injectArgs = injectArgs; +//# sourceMappingURL=inject-args.js.map -/** - * Return a string for sign() with the given `options`. - * - * Spec: - * - * \n - * \n - * \n - * \n - * [headers\n] - * - * - * @param {Object} options - * @return {String} - * @api private - */ +/***/ }), -function stringToSign (options) { - var headers = options.amazonHeaders || '' - if (headers) headers += '\n' - var r = - [ options.verb - , options.md5 - , options.contentType - , options.date ? options.date.toUTCString() : '' - , headers + options.resource - ] - return r.join('\n') -} -module.exports.stringToSign = stringToSign +/***/ 11413: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * Return a string for sign() with the given `options`, but is meant exclusively - * for S3 presigned URLs - * - * Spec: - * - * \n - * - * - * @param {Object} options - * @return {String} - * @api private - */ +"use strict"; -function queryStringToSign (options){ - return 'GET\n\n\n' + options.date + '\n' + options.resource +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.prepareSubcommand = exports.prepareCommand = void 0; +const metadata_1 = __nccwpck_require__(104); +const index_1 = __nccwpck_require__(84908); +function prepareCommand(target, propertyKey) { + let argList = ''; + if (Reflect.hasMetadata(metadata_1.ArgsMetadata, target, propertyKey)) { + const args = Reflect.getMetadata(metadata_1.ArgsMetadata, target, propertyKey); + const predicate = (arg) => arg instanceof index_1.VariadicArg; + const variadic = args.find(predicate); + if (variadic && (args.findIndex(predicate) !== (args.length - 1))) { + throw new TypeError(`Variadic argument must be specified last the argument list of the ${String(propertyKey)}() function.`); + } + argList = args + .map((arg) => { + return arg.toString(); + }) + .join(' ') + .replace(/^(.)/, '$1'); + } + return `${argList}`; } -module.exports.queryStringToSign = queryStringToSign - -/** - * Perform the following: - * - * - ignore non-amazon headers - * - lowercase fields - * - sort lexicographically - * - trim whitespace between ":" - * - join with newline - * - * @param {Object} headers - * @return {String} - * @api private - */ - -function canonicalizeHeaders (headers) { - var buf = [] - , fields = Object.keys(headers) - ; - for (var i = 0, len = fields.length; i < len; ++i) { - var field = fields[i] - , val = headers[field] - , field = field.toLowerCase() - ; - if (0 !== field.indexOf('x-amz')) continue - buf.push(field + ':' + val) - } - return buf.sort().join('\n') +exports.prepareCommand = prepareCommand; +function prepareSubcommand(target, propertyKey) { + const argList = prepareCommand(target, propertyKey); + return `${String(propertyKey)} ${argList}`; } -module.exports.canonicalizeHeaders = canonicalizeHeaders - -/** - * Perform the following: - * - * - ignore non sub-resources - * - sort lexicographically - * - * @param {String} resource - * @return {String} - * @api private - */ +exports.prepareSubcommand = prepareSubcommand; +//# sourceMappingURL=prepare-command.js.map -function canonicalizeResource (resource) { - var url = parse(resource, true) - , path = url.pathname - , buf = [] - ; +/***/ }), - Object.keys(url.query).forEach(function(key){ - if (!~keys.indexOf(key)) return - var val = '' == url.query[key] ? '' : '=' + encodeURIComponent(url.query[key]) - buf.push(key + val) - }) +/***/ 40451: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - return path + (buf.length ? '?' + buf.sort().join('&') : '') -} -module.exports.canonicalizeResource = canonicalizeResource +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (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 })); +exports.Option = exports.Command = void 0; +__nccwpck_require__(29977); +var commander_1 = __nccwpck_require__(86987); +Object.defineProperty(exports, "Command", ({ enumerable: true, get: function () { return commander_1.Command; } })); +Object.defineProperty(exports, "Option", ({ enumerable: true, get: function () { return commander_1.Option; } })); +__exportStar(__nccwpck_require__(90154), exports); +//# sourceMappingURL=index.js.map /***/ }), -/***/ 16071: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 104: +/***/ ((__unused_webpack_module, exports) => { -var aws4 = exports, - url = __nccwpck_require__(57310), - querystring = __nccwpck_require__(63477), - crypto = __nccwpck_require__(6113), - lru = __nccwpck_require__(74225), - credentialsCache = lru(1000) +"use strict"; -// http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SubcommandMetadata = exports.ProgramMetadata = exports.OptionsMetadata = exports.CommandOptionsMetadata = exports.ArgsMetadata = void 0; +exports.ArgsMetadata = Symbol('ArgsMetadata'); +exports.CommandOptionsMetadata = Symbol('CommandOptionsMetadata'); +exports.OptionsMetadata = Symbol('OptionsMetadata'); +exports.ProgramMetadata = Symbol('ProgramMetadata'); +exports.SubcommandMetadata = Symbol('SubcommandMetadata'); +//# sourceMappingURL=metadata.js.map -function hmac(key, string, encoding) { - return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding) -} +/***/ }), -function hash(string, encoding) { - return crypto.createHash('sha256').update(string, 'utf8').digest(encoding) -} +/***/ 6312: +/***/ ((__unused_webpack_module, exports) => { -// This function assumes the string has already been percent encoded -function encodeRfc3986(urlEncodedString) { - return urlEncodedString.replace(/[!'()*]/g, function(c) { - return '%' + c.charCodeAt(0).toString(16).toUpperCase() - }) -} +"use strict"; -function encodeRfc3986Full(str) { - return encodeRfc3986(encodeURIComponent(str)) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.VariadicArg = exports.RequiredArg = exports.OptionalArg = exports.CommandArg = void 0; +class CommandArg { + constructor(name, index) { + this.name = name; + this.index = index; + if (typeof name === 'symbol') { + throw new TypeError('Symbols are not supported as argument names.'); + } + } } - -// A bit of a combination of: -// https://github.com/aws/aws-sdk-java-v2/blob/dc695de6ab49ad03934e1b02e7263abbd2354be0/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/AbstractAws4Signer.java#L59 -// https://github.com/aws/aws-sdk-js/blob/18cb7e5b463b46239f9fdd4a65e2ff8c81831e8f/lib/signers/v4.js#L191-L199 -// https://github.com/mhart/aws4fetch/blob/b3aed16b6f17384cf36ea33bcba3c1e9f3bdfefd/src/main.js#L25-L34 -var HEADERS_TO_IGNORE = { - 'authorization': true, - 'connection': true, - 'x-amzn-trace-id': true, - 'user-agent': true, - 'expect': true, - 'presigned-expires': true, - 'range': true, +exports.CommandArg = CommandArg; +class OptionalArg extends CommandArg { + toString() { + return `[${String(this.name)}]`; + } } +exports.OptionalArg = OptionalArg; +class RequiredArg extends CommandArg { + toString() { + return `<${String(this.name)}>`; + } +} +exports.RequiredArg = RequiredArg; +class VariadicArg extends CommandArg { + toString() { + return `[${String(this.name)}...]`; + } +} +exports.VariadicArg = VariadicArg; +//# sourceMappingURL=arg.model.js.map -// request: { path | body, [host], [method], [headers], [service], [region] } -// credentials: { accessKeyId, secretAccessKey, [sessionToken] } -function RequestSigner(request, credentials) { - - if (typeof request === 'string') request = url.parse(request) - - var headers = request.headers = (request.headers || {}), - hostParts = (!this.service || !this.region) && this.matchHost(request.hostname || request.host || headers.Host || headers.host) - - this.request = request - this.credentials = credentials || this.defaultCredentials() - - this.service = request.service || hostParts[0] || '' - this.region = request.region || hostParts[1] || 'us-east-1' - - // SES uses a different domain from the service name - if (this.service === 'email') this.service = 'ses' - - if (!request.method && request.body) - request.method = 'POST' +/***/ }), - if (!headers.Host && !headers.host) { - headers.Host = request.hostname || request.host || this.createHost() +/***/ 84908: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - // If a port is specified explicitly, use it as is - if (request.port) - headers.Host += ':' + request.port - } - if (!request.hostname && !request.host) - request.hostname = headers.Host || headers.host +"use strict"; - this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT' +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (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 })); +__exportStar(__nccwpck_require__(6312), exports); +__exportStar(__nccwpck_require__(4860), exports); +//# sourceMappingURL=index.js.map - this.extraHeadersToIgnore = request.extraHeadersToIgnore || Object.create(null) - this.extraHeadersToInclude = request.extraHeadersToInclude || Object.create(null) -} +/***/ }), -RequestSigner.prototype.matchHost = function(host) { - var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/) - var hostParts = (match || []).slice(1, 3) +/***/ 4860: +/***/ ((__unused_webpack_module, exports) => { - // ES's hostParts are sometimes the other way round, if the value that is expected - // to be region equals ‘es’ switch them back - // e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com - if (hostParts[1] === 'es' || hostParts[1] === 'aoss') - hostParts = hostParts.reverse() +"use strict"; - if (hostParts[1] == 's3') { - hostParts[0] = 's3' - hostParts[1] = 'us-east-1' - } else { - for (var i = 0; i < 2; i++) { - if (/^s3-/.test(hostParts[i])) { - hostParts[1] = hostParts[i].slice(3) - hostParts[0] = 's3' - break - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Option = void 0; +class Option { + constructor(name, args) { + this.name = name; + this.args = args; } - } - - return hostParts } +exports.Option = Option; +//# sourceMappingURL=option.model.js.map -// http://docs.aws.amazon.com/general/latest/gr/rande.html -RequestSigner.prototype.isSingleRegion = function() { - // Special case for S3 and SimpleDB in us-east-1 - if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1') return true +/***/ }), - return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts'] - .indexOf(this.service) >= 0 -} +/***/ 65058: +/***/ ((__unused_webpack_module, exports) => { -RequestSigner.prototype.createHost = function() { - var region = this.isSingleRegion() ? '' : '.' + this.region, - subdomain = this.service === 'ses' ? 'email' : this.service - return subdomain + region + '.amazonaws.com' -} +"use strict"; -RequestSigner.prototype.prepareRequest = function() { - this.parsePath() +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.decorateIfNot = void 0; +function decorateIfNot(metadataKey, value, target, propertyKey) { + if (!Reflect.hasMetadata(metadataKey, target, propertyKey)) { + const decorator = Reflect.metadata(metadataKey, value); + Reflect.decorate([decorator], target, propertyKey); + } + return Reflect.getMetadata(metadataKey, target, propertyKey); +} +exports.decorateIfNot = decorateIfNot; +//# sourceMappingURL=decorateIfNot.js.map - var request = this.request, headers = request.headers, query +/***/ }), - if (request.signQuery) { +/***/ 66725: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - this.parsedPath.query = query = this.parsedPath.query || {} +"use strict"; - if (this.credentials.sessionToken) - query['X-Amz-Security-Token'] = this.credentials.sessionToken +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (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 })); +__exportStar(__nccwpck_require__(65058), exports); +//# sourceMappingURL=index.js.map - if (this.service === 's3' && !query['X-Amz-Expires']) - query['X-Amz-Expires'] = 86400 +/***/ }), - if (query['X-Amz-Date']) - this.datetime = query['X-Amz-Date'] - else - query['X-Amz-Date'] = this.getDateTime() +/***/ 86891: +/***/ ((module) => { - query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256' - query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString() - query['X-Amz-SignedHeaders'] = this.signedHeaders() +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; +}; - } else { +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; - if (!request.doNotModifyHeaders && !this.isCodeCommitGit) { - if (request.body && !headers['Content-Type'] && !headers['content-type']) - headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8' - if (request.body && !headers['Content-Length'] && !headers['content-length']) - headers['Content-Length'] = Buffer.byteLength(request.body) +/***/ }), - if (this.credentials.sessionToken && !headers['X-Amz-Security-Token'] && !headers['x-amz-security-token']) - headers['X-Amz-Security-Token'] = this.credentials.sessionToken +/***/ 95898: +/***/ ((__unused_webpack_module, exports) => { - if (this.service === 's3' && !headers['X-Amz-Content-Sha256'] && !headers['x-amz-content-sha256']) - headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex') +var __webpack_unused_export__; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - if (headers['X-Amz-Date'] || headers['x-amz-date']) - this.datetime = headers['X-Amz-Date'] || headers['x-amz-date'] - else - headers['X-Amz-Date'] = this.getDateTime() - } +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. - delete headers.Authorization - delete headers.authorization +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); } + return objectToString(arg) === '[object Array]'; } +__webpack_unused_export__ = isArray; -RequestSigner.prototype.sign = function() { - if (!this.parsedPath) this.prepareRequest() - - if (this.request.signQuery) { - this.parsedPath.query['X-Amz-Signature'] = this.signature() - } else { - this.request.headers.Authorization = this.authHeader() - } +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +__webpack_unused_export__ = isBoolean; - this.request.path = this.formatPath() +function isNull(arg) { + return arg === null; +} +__webpack_unused_export__ = isNull; - return this.request +function isNullOrUndefined(arg) { + return arg == null; } +__webpack_unused_export__ = isNullOrUndefined; -RequestSigner.prototype.getDateTime = function() { - if (!this.datetime) { - var headers = this.request.headers, - date = new Date(headers.Date || headers.date || new Date) +function isNumber(arg) { + return typeof arg === 'number'; +} +__webpack_unused_export__ = isNumber; - this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, '') +function isString(arg) { + return typeof arg === 'string'; +} +__webpack_unused_export__ = isString; - // Remove the trailing 'Z' on the timestamp string for CodeCommit git access - if (this.isCodeCommitGit) this.datetime = this.datetime.slice(0, -1) - } - return this.datetime +function isSymbol(arg) { + return typeof arg === 'symbol'; } +__webpack_unused_export__ = isSymbol; -RequestSigner.prototype.getDate = function() { - return this.getDateTime().substr(0, 8) +function isUndefined(arg) { + return arg === void 0; } +__webpack_unused_export__ = isUndefined; -RequestSigner.prototype.authHeader = function() { - return [ - 'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(), - 'SignedHeaders=' + this.signedHeaders(), - 'Signature=' + this.signature(), - ].join(', ') +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; } +__webpack_unused_export__ = isRegExp; -RequestSigner.prototype.signature = function() { - var date = this.getDate(), - cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(), - kDate, kRegion, kService, kCredentials = credentialsCache.get(cacheKey) - if (!kCredentials) { - kDate = hmac('AWS4' + this.credentials.secretAccessKey, date) - kRegion = hmac(kDate, this.region) - kService = hmac(kRegion, this.service) - kCredentials = hmac(kService, 'aws4_request') - credentialsCache.set(cacheKey, kCredentials) - } - return hmac(kCredentials, this.stringToSign(), 'hex') +function isObject(arg) { + return typeof arg === 'object' && arg !== null; } +__webpack_unused_export__ = isObject; -RequestSigner.prototype.stringToSign = function() { - return [ - 'AWS4-HMAC-SHA256', - this.getDateTime(), - this.credentialString(), - hash(this.canonicalString(), 'hex'), - ].join('\n') +function isDate(d) { + return objectToString(d) === '[object Date]'; } +__webpack_unused_export__ = isDate; -RequestSigner.prototype.canonicalString = function() { - if (!this.parsedPath) this.prepareRequest() +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.VZ = isError; - var pathStr = this.parsedPath.path, - query = this.parsedPath.query, - headers = this.request.headers, - queryStr = '', - normalizePath = this.service !== 's3', - decodePath = this.service === 's3' || this.request.doNotEncodePath, - decodeSlashesInPath = this.service === 's3', - firstValOnly = this.service === 's3', - bodyHash +function isFunction(arg) { + return typeof arg === 'function'; +} +__webpack_unused_export__ = isFunction; - if (this.service === 's3' && this.request.signQuery) { - bodyHash = 'UNSIGNED-PAYLOAD' - } else if (this.isCodeCommitGit) { - bodyHash = '' - } else { - bodyHash = headers['X-Amz-Content-Sha256'] || headers['x-amz-content-sha256'] || - hash(this.request.body || '', 'hex') - } +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +__webpack_unused_export__ = isPrimitive; - if (query) { - var reducedQuery = Object.keys(query).reduce(function(obj, key) { - if (!key) return obj - obj[encodeRfc3986Full(key)] = !Array.isArray(query[key]) ? query[key] : - (firstValOnly ? query[key][0] : query[key]) - return obj - }, {}) - var encodedQueryPieces = [] - Object.keys(reducedQuery).sort().forEach(function(key) { - if (!Array.isArray(reducedQuery[key])) { - encodedQueryPieces.push(key + '=' + encodeRfc3986Full(reducedQuery[key])) - } else { - reducedQuery[key].map(encodeRfc3986Full).sort() - .forEach(function(val) { encodedQueryPieces.push(key + '=' + val) }) - } - }) - queryStr = encodedQueryPieces.join('&') - } - if (pathStr !== '/') { - if (normalizePath) pathStr = pathStr.replace(/\/{2,}/g, '/') - pathStr = pathStr.split('/').reduce(function(path, piece) { - if (normalizePath && piece === '..') { - path.pop() - } else if (!normalizePath || piece !== '.') { - if (decodePath) piece = decodeURIComponent(piece.replace(/\+/g, ' ')) - path.push(encodeRfc3986Full(piece)) - } - return path - }, []).join('/') - if (pathStr[0] !== '/') pathStr = '/' + pathStr - if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/') - } +__webpack_unused_export__ = Buffer.isBuffer; - return [ - this.request.method || 'GET', - pathStr, - queryStr, - this.canonicalHeaders() + '\n', - this.signedHeaders(), - bodyHash, - ].join('\n') +function objectToString(o) { + return Object.prototype.toString.call(o); } -RequestSigner.prototype.canonicalHeaders = function() { - var headers = this.request.headers - function trimAll(header) { - return header.toString().trim().replace(/\s+/g, ' ') - } - return Object.keys(headers) - .filter(function(key) { return HEADERS_TO_IGNORE[key.toLowerCase()] == null }) - .sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1 }) - .map(function(key) { return key.toLowerCase() + ':' + trimAll(headers[key]) }) - .join('\n') -} -RequestSigner.prototype.signedHeaders = function() { - var extraHeadersToInclude = this.extraHeadersToInclude, - extraHeadersToIgnore = this.extraHeadersToIgnore - return Object.keys(this.request.headers) - .map(function(key) { return key.toLowerCase() }) - .filter(function(key) { - return extraHeadersToInclude[key] || - (HEADERS_TO_IGNORE[key] == null && !extraHeadersToIgnore[key]) - }) - .sort() - .join(';') -} +/***/ }), -RequestSigner.prototype.credentialString = function() { - return [ - this.getDate(), - this.region, - this.service, - 'aws4_request', - ].join('/') -} +/***/ 83121: +/***/ ((module, exports, __nccwpck_require__) => { -RequestSigner.prototype.defaultCredentials = function() { - var env = process.env - return { - accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY, - secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY, - sessionToken: env.AWS_SESSION_TOKEN, +const nodeFetch = __nccwpck_require__(80467) +const realFetch = nodeFetch.default || nodeFetch + +const fetch = function (url, options) { + // Support schemaless URIs on the server for parity with the browser. + // Ex: //github.com/ -> https://github.com/ + if (/^\/\//.test(url)) { + url = 'https:' + url } + return realFetch.call(this, url, options) } -RequestSigner.prototype.parsePath = function() { - var path = this.request.path || '/' +fetch.ponyfill = true - // S3 doesn't always encode characters > 127 correctly and - // all services don't encode characters > 255 correctly - // So if there are non-reserved chars (and it's not already all % encoded), just encode them all - if (/[^0-9A-Za-z;,/?:@&=+$\-_.!~*'()#%]/.test(path)) { - path = encodeURI(decodeURI(path)) - } +module.exports = exports = fetch +exports.fetch = fetch +exports.Headers = nodeFetch.Headers +exports.Request = nodeFetch.Request +exports.Response = nodeFetch.Response - var queryIx = path.indexOf('?'), - query = null +// Needed for TypeScript consumers without esModuleInterop. +exports["default"] = fetch - if (queryIx >= 0) { - query = querystring.parse(path.slice(queryIx + 1)) - path = path.slice(0, queryIx) - } - this.parsedPath = { - path: path, - query: query, - } -} +/***/ }), -RequestSigner.prototype.formatPath = function() { - var path = this.parsedPath.path, - query = this.parsedPath.query +/***/ 72746: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (!query) return path +"use strict"; - // Services don't support empty query string keys - if (query[''] != null) delete query[''] - return path + '?' + encodeRfc3986(querystring.stringify(query)) +const cp = __nccwpck_require__(32081); +const parse = __nccwpck_require__(66855); +const enoent = __nccwpck_require__(44101); + +function spawn(command, args, options) { + // Parse the arguments + const parsed = parse(command, args, options); + + // Spawn the child process + const spawned = cp.spawn(parsed.command, parsed.args, parsed.options); + + // Hook into child process "exit" event to emit an error if the command + // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 + enoent.hookChildProcess(spawned, parsed); + + return spawned; } -aws4.RequestSigner = RequestSigner +function spawnSync(command, args, options) { + // Parse the arguments + const parsed = parse(command, args, options); -aws4.sign = function(request, credentials) { - return new RequestSigner(request, credentials).sign() + // Spawn the child process + const result = cp.spawnSync(parsed.command, parsed.args, parsed.options); + + // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 + result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); + + return result; } +module.exports = spawn; +module.exports.spawn = spawn; +module.exports.sync = spawnSync; + +module.exports._parse = parse; +module.exports._enoent = enoent; + /***/ }), -/***/ 74225: +/***/ 44101: /***/ ((module) => { -module.exports = function(size) { - return new LruCache(size) -} +"use strict"; -function LruCache(size) { - this.capacity = size | 0 - this.map = Object.create(null) - this.list = new DoublyLinkedList() -} -LruCache.prototype.get = function(key) { - var node = this.map[key] - if (node == null) return undefined - this.used(node) - return node.val -} +const isWin = process.platform === 'win32'; -LruCache.prototype.set = function(key, val) { - var node = this.map[key] - if (node != null) { - node.val = val - } else { - if (!this.capacity) this.prune() - if (!this.capacity) return false - node = new DoublyLinkedNode(key, val) - this.map[key] = node - this.capacity-- - } - this.used(node) - return true +function notFoundError(original, syscall) { + return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), { + code: 'ENOENT', + errno: 'ENOENT', + syscall: `${syscall} ${original.command}`, + path: original.command, + spawnargs: original.args, + }); } -LruCache.prototype.used = function(node) { - this.list.moveToFront(node) +function hookChildProcess(cp, parsed) { + if (!isWin) { + return; + } + + const originalEmit = cp.emit; + + cp.emit = function (name, arg1) { + // If emitting "exit" event and exit code is 1, we need to check if + // the command exists and emit an "error" instead + // See https://github.com/IndigoUnited/node-cross-spawn/issues/16 + if (name === 'exit') { + const err = verifyENOENT(arg1, parsed); + + if (err) { + return originalEmit.call(cp, 'error', err); + } + } + + return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params + }; } -LruCache.prototype.prune = function() { - var node = this.list.pop() - if (node != null) { - delete this.map[node.key] - this.capacity++ - } +function verifyENOENT(status, parsed) { + if (isWin && status === 1 && !parsed.file) { + return notFoundError(parsed.original, 'spawn'); + } + + return null; } +function verifyENOENTSync(status, parsed) { + if (isWin && status === 1 && !parsed.file) { + return notFoundError(parsed.original, 'spawnSync'); + } -function DoublyLinkedList() { - this.firstNode = null - this.lastNode = null + return null; } -DoublyLinkedList.prototype.moveToFront = function(node) { - if (this.firstNode == node) return +module.exports = { + hookChildProcess, + verifyENOENT, + verifyENOENTSync, + notFoundError, +}; - this.remove(node) - if (this.firstNode == null) { - this.firstNode = node - this.lastNode = node - node.prev = null - node.next = null - } else { - node.prev = null - node.next = this.firstNode - node.next.prev = node - this.firstNode = node - } -} +/***/ }), -DoublyLinkedList.prototype.pop = function() { - var lastNode = this.lastNode - if (lastNode != null) { - this.remove(lastNode) - } - return lastNode +/***/ 66855: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const path = __nccwpck_require__(71017); +const resolveCommand = __nccwpck_require__(87274); +const escape = __nccwpck_require__(34274); +const readShebang = __nccwpck_require__(41252); + +const isWin = process.platform === 'win32'; +const isExecutableRegExp = /\.(?:com|exe)$/i; +const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; + +function detectShebang(parsed) { + parsed.file = resolveCommand(parsed); + + const shebang = parsed.file && readShebang(parsed.file); + + if (shebang) { + parsed.args.unshift(parsed.file); + parsed.command = shebang; + + return resolveCommand(parsed); + } + + return parsed.file; } -DoublyLinkedList.prototype.remove = function(node) { - if (this.firstNode == node) { - this.firstNode = node.next - } else if (node.prev != null) { - node.prev.next = node.next - } - if (this.lastNode == node) { - this.lastNode = node.prev - } else if (node.next != null) { - node.next.prev = node.prev - } +function parseNonShell(parsed) { + if (!isWin) { + return parsed; + } + + // Detect & add support for shebangs + const commandFile = detectShebang(parsed); + + // We don't need a shell if the command filename is an executable + const needsShell = !isExecutableRegExp.test(commandFile); + + // If a shell is required, use cmd.exe and take care of escaping everything correctly + // Note that `forceShell` is an hidden option used only in tests + if (parsed.options.forceShell || needsShell) { + // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/` + // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument + // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called, + // we need to double escape them + const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); + + // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar) + // This is necessary otherwise it will always fail with ENOENT in those cases + parsed.command = path.normalize(parsed.command); + + // Escape command & arguments + parsed.command = escape.command(parsed.command); + parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars)); + + const shellCommand = [parsed.command].concat(parsed.args).join(' '); + + parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; + parsed.command = process.env.comspec || 'cmd.exe'; + parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped + } + + return parsed; } +function parse(command, args, options) { + // Normalize arguments, similar to nodejs + if (args && !Array.isArray(args)) { + options = args; + args = null; + } -function DoublyLinkedNode(key, val) { - this.key = key - this.val = val - this.prev = null - this.next = null + args = args ? args.slice(0) : []; // Clone array to avoid changing the original + options = Object.assign({}, options); // Clone object to avoid changing the original + + // Build our parsed object + const parsed = { + command, + args, + options, + file: undefined, + original: { + command, + args, + }, + }; + + // Delegate further parsing to shell or non-shell + return options.shell ? parsed : parseNonShell(parsed); } +module.exports = parse; + /***/ }), -/***/ 91403: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 34274: +/***/ ((module) => { "use strict"; -var CombinedStream = __nccwpck_require__(85443); -var util = __nccwpck_require__(73837); -var path = __nccwpck_require__(71017); -var http = __nccwpck_require__(13685); -var https = __nccwpck_require__(95687); -var parseUrl = (__nccwpck_require__(57310).parse); -var fs = __nccwpck_require__(57147); -var Stream = (__nccwpck_require__(12781).Stream); -var crypto = __nccwpck_require__(6113); -var mime = __nccwpck_require__(43583); -var asynckit = __nccwpck_require__(14812); -var setToStringTag = __nccwpck_require__(11770); -var hasOwn = __nccwpck_require__(62157); -var populate = __nccwpck_require__(47027); +// See http://www.robvanderwoude.com/escapechars.php +const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; -/** - * Create readable "multipart/form-data" streams. - * Can be used to submit forms - * and file uploads to other web applications. - * - * @constructor - * @param {object} options - Properties to be added/overriden for FormData and CombinedStream - */ -function FormData(options) { - if (!(this instanceof FormData)) { - return new FormData(options); - } +function escapeCommand(arg) { + // Escape meta chars + arg = arg.replace(metaCharsRegExp, '^$1'); - this._overheadLength = 0; - this._valueLength = 0; - this._valuesToMeasure = []; + return arg; +} - CombinedStream.call(this); +function escapeArgument(arg, doubleEscapeMetaChars) { + // Convert to string + arg = `${arg}`; - options = options || {}; // eslint-disable-line no-param-reassign - for (var option in options) { // eslint-disable-line no-restricted-syntax - this[option] = options[option]; - } -} + // Algorithm below is based on https://qntm.org/cmd + // It's slightly altered to disable JS backtracking to avoid hanging on specially crafted input + // Please see https://github.com/moxystudio/node-cross-spawn/pull/160 for more information -// make it a Stream -util.inherits(FormData, CombinedStream); + // Sequence of backslashes followed by a double quote: + // double up all the backslashes and escape the double quote + arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"'); -FormData.LINE_BREAK = '\r\n'; -FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; + // Sequence of backslashes followed by the end of the string + // (which will become a double quote later): + // double up all the backslashes + arg = arg.replace(/(?=(\\+?)?)\1$/, '$1$1'); -FormData.prototype.append = function (field, value, options) { - options = options || {}; // eslint-disable-line no-param-reassign + // All other backslashes occur literally - // allow filename as single option - if (typeof options === 'string') { - options = { filename: options }; // eslint-disable-line no-param-reassign - } + // Quote the whole thing: + arg = `"${arg}"`; - var append = CombinedStream.prototype.append.bind(this); + // Escape meta chars + arg = arg.replace(metaCharsRegExp, '^$1'); - // all that streamy business can't handle numbers - if (typeof value === 'number' || value == null) { - value = String(value); // eslint-disable-line no-param-reassign - } + // Double escape meta chars if necessary + if (doubleEscapeMetaChars) { + arg = arg.replace(metaCharsRegExp, '^$1'); + } - // https://github.com/felixge/node-form-data/issues/38 - if (Array.isArray(value)) { - /* - * Please convert your array into string - * the way web server expects it - */ - this._error(new Error('Arrays are not supported.')); - return; - } + return arg; +} - var header = this._multiPartHeader(field, value, options); - var footer = this._multiPartFooter(); +module.exports.command = escapeCommand; +module.exports.argument = escapeArgument; - append(header); - append(value); - append(footer); - // pass along options.knownLength - this._trackLength(header, value, options); -}; +/***/ }), -FormData.prototype._trackLength = function (header, value, options) { - var valueLength = 0; +/***/ 41252: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /* - * used w/ getLengthSync(), when length is known. - * e.g. for streaming directly from a remote server, - * w/ a known file a size, and not wanting to wait for - * incoming file to finish to get its size. - */ - if (options.knownLength != null) { - valueLength += Number(options.knownLength); - } else if (Buffer.isBuffer(value)) { - valueLength = value.length; - } else if (typeof value === 'string') { - valueLength = Buffer.byteLength(value); - } +"use strict"; - this._valueLength += valueLength; - // @check why add CRLF? does this account for custom/multiple CRLFs? - this._overheadLength += Buffer.byteLength(header) + FormData.LINE_BREAK.length; +const fs = __nccwpck_require__(57147); +const shebangCommand = __nccwpck_require__(67032); - // empty or either doesn't have path or not an http response or not a stream - if (!value || (!value.path && !(value.readable && hasOwn(value, 'httpVersion')) && !(value instanceof Stream))) { - return; - } +function readShebang(command) { + // Read the first 150 bytes from the file + const size = 150; + const buffer = Buffer.alloc(size); - // no need to bother with the length - if (!options.knownLength) { - this._valuesToMeasure.push(value); - } -}; + let fd; -FormData.prototype._lengthRetriever = function (value, callback) { - if (hasOwn(value, 'fd')) { - // take read range into a account - // `end` = Infinity –> read file till the end - // - // TODO: Looks like there is bug in Node fs.createReadStream - // it doesn't respect `end` options without `start` options - // Fix it when node fixes it. - // https://github.com/joyent/node/issues/7819 - if (value.end != undefined && value.end != Infinity && value.start != undefined) { - // when end specified - // no need to calculate range - // inclusive, starts with 0 - callback(null, value.end + 1 - (value.start ? value.start : 0)); // eslint-disable-line callback-return + try { + fd = fs.openSync(command, 'r'); + fs.readSync(fd, buffer, 0, size, 0); + fs.closeSync(fd); + } catch (e) { /* Empty */ } - // not that fast snoopy - } else { - // still need to fetch file size from fs - fs.stat(value.path, function (err, stat) { - if (err) { - callback(err); - return; - } + // Attempt to extract shebang (null is returned if not a shebang) + return shebangCommand(buffer.toString()); +} - // update final size based on the range options - var fileSize = stat.size - (value.start ? value.start : 0); - callback(null, fileSize); - }); - } +module.exports = readShebang; - // or http response - } else if (hasOwn(value, 'httpVersion')) { - callback(null, Number(value.headers['content-length'])); // eslint-disable-line callback-return - // or request stream http://github.com/mikeal/request - } else if (hasOwn(value, 'httpModule')) { - // wait till response come back - value.on('response', function (response) { - value.pause(); - callback(null, Number(response.headers['content-length'])); - }); - value.resume(); +/***/ }), - // something else - } else { - callback('Unknown stream'); // eslint-disable-line callback-return - } -}; +/***/ 87274: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -FormData.prototype._multiPartHeader = function (field, value, options) { - /* - * custom header specified (as string)? - * it becomes responsible for boundary - * (e.g. to handle extra CRLFs on .NET servers) - */ - if (typeof options.header === 'string') { - return options.header; - } +"use strict"; - var contentDisposition = this._getContentDisposition(value, options); - var contentType = this._getContentType(value, options); - var contents = ''; - var headers = { - // add custom disposition as third element or keep it two elements if not - 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), - // if no content type. allow it to be empty array - 'Content-Type': [].concat(contentType || []) - }; +const path = __nccwpck_require__(71017); +const which = __nccwpck_require__(34207); +const getPathKey = __nccwpck_require__(20539); - // allow custom headers. - if (typeof options.header === 'object') { - populate(headers, options.header); - } +function resolveCommandAttempt(parsed, withoutPathExt) { + const env = parsed.options.env || process.env; + const cwd = process.cwd(); + const hasCustomCwd = parsed.options.cwd != null; + // Worker threads do not have process.chdir() + const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled; - var header; - for (var prop in headers) { // eslint-disable-line no-restricted-syntax - if (hasOwn(headers, prop)) { - header = headers[prop]; + // If a custom `cwd` was specified, we need to change the process cwd + // because `which` will do stat calls but does not support a custom cwd + if (shouldSwitchCwd) { + try { + process.chdir(parsed.options.cwd); + } catch (err) { + /* Empty */ + } + } - // skip nullish headers. - if (header == null) { - continue; // eslint-disable-line no-restricted-syntax, no-continue - } + let resolved; - // convert all headers to arrays. - if (!Array.isArray(header)) { - header = [header]; - } + try { + resolved = which.sync(parsed.command, { + path: env[getPathKey({ env })], + pathExt: withoutPathExt ? path.delimiter : undefined, + }); + } catch (e) { + /* Empty */ + } finally { + if (shouldSwitchCwd) { + process.chdir(cwd); + } + } - // add non-empty headers. - if (header.length) { - contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; - } + // If we successfully resolved, ensure that an absolute path is returned + // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it + if (resolved) { + resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved); } - } - return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; -}; + return resolved; +} -FormData.prototype._getContentDisposition = function (value, options) { // eslint-disable-line consistent-return - var filename; +function resolveCommand(parsed) { + return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); +} - if (typeof options.filepath === 'string') { - // custom filepath for relative paths - filename = path.normalize(options.filepath).replace(/\\/g, '/'); - } else if (options.filename || (value && (value.name || value.path))) { - /* - * custom filename take precedence - * formidable and the browser add a name property - * fs- and request- streams have path property - */ - filename = path.basename(options.filename || (value && (value.name || value.path))); - } else if (value && value.readable && hasOwn(value, 'httpVersion')) { - // or try http response - filename = path.basename(value.client._httpMessage.path || ''); - } +module.exports = resolveCommand; - if (filename) { - return 'filename="' + filename + '"'; - } -}; -FormData.prototype._getContentType = function (value, options) { - // use custom content-type above all - var contentType = options.contentType; +/***/ }), - // or try `name` from formidable, browser - if (!contentType && value && value.name) { - contentType = mime.lookup(value.name); - } +/***/ 28222: +/***/ ((module, exports, __nccwpck_require__) => { - // or try `path` from fs-, request- streams - if (!contentType && value && value.path) { - contentType = mime.lookup(value.path); - } +/* eslint-env browser */ - // or if it's http-reponse - if (!contentType && value && value.readable && hasOwn(value, 'httpVersion')) { - contentType = value.headers['content-type']; - } +/** + * This is the web browser implementation of `debug()`. + */ - // or guess it from the filepath or filename - if (!contentType && (options.filepath || options.filename)) { - contentType = mime.lookup(options.filepath || options.filename); - } +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; - // fallback to the default content type if `value` is not simple value - if (!contentType && value && typeof value === 'object') { - contentType = FormData.DEFAULT_CONTENT_TYPE; - } + 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`.'); + } + }; +})(); - return contentType; -}; +/** + * Colors. + */ -FormData.prototype._multiPartFooter = function () { - return function (next) { - var footer = FormData.LINE_BREAK; +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' +]; - var lastPart = this._streams.length === 0; - if (lastPart) { - footer += this._lastBoundary(); - } +/** + * 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 + */ - next(footer); - }.bind(this); -}; +// 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; + } -FormData.prototype._lastBoundary = function () { - return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; -}; + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } -FormData.prototype.getHeaders = function (userHeaders) { - var header; - var formHeaders = { - 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() - }; + // 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+)/)); +} - for (header in userHeaders) { // eslint-disable-line no-restricted-syntax - if (hasOwn(userHeaders, header)) { - formHeaders[header.toLowerCase()] = userHeaders[header]; - } - } +/** + * Colorize log arguments if enabled. + * + * @api public + */ - return formHeaders; -}; +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); -FormData.prototype.setBoundary = function (boundary) { - if (typeof boundary !== 'string') { - throw new TypeError('FormData boundary must be a string'); - } - this._boundary = boundary; -}; + if (!this.useColors) { + return; + } -FormData.prototype.getBoundary = function () { - if (!this._boundary) { - this._generateBoundary(); - } + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); - return this._boundary; -}; + // 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; + } + }); -FormData.prototype.getBuffer = function () { - var dataBuffer = new Buffer.alloc(0); // eslint-disable-line new-cap - var boundary = this.getBoundary(); + args.splice(lastC, 0, c); +} - // Create the form content. Add Line breaks to the end of data. - for (var i = 0, len = this._streams.length; i < len; i++) { - if (typeof this._streams[i] !== 'function') { - // Add content to the buffer. - if (Buffer.isBuffer(this._streams[i])) { - dataBuffer = Buffer.concat([dataBuffer, this._streams[i]]); - } else { - dataBuffer = Buffer.concat([dataBuffer, Buffer.from(this._streams[i])]); - } +/** + * 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 || (() => {}); - // Add break after content. - if (typeof this._streams[i] !== 'string' || this._streams[i].substring(2, boundary.length + 2) !== boundary) { - dataBuffer = Buffer.concat([dataBuffer, Buffer.from(FormData.LINE_BREAK)]); - } - } - } +/** + * 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? + } +} - // Add the footer and return the Buffer object. - return Buffer.concat([dataBuffer, Buffer.from(this._lastBoundary())]); -}; +/** + * 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? + } -FormData.prototype._generateBoundary = function () { - // This generates a 50 character boundary similar to those used by Firefox. + // 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; + } - // They are optimized for boyer-moore parsing. - this._boundary = '--------------------------' + crypto.randomBytes(12).toString('hex'); -}; + return r; +} -// Note: getLengthSync DOESN'T calculate streams length -// As workaround one can calculate file size manually and add it as knownLength option -FormData.prototype.getLengthSync = function () { - var knownLength = this._overheadLength + this._valueLength; +/** + * 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 + */ - // Don't get confused, there are 3 "internal" streams for each keyval pair so it basically checks if there is any value added to the form - if (this._streams.length) { - knownLength += this._lastBoundary().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? + } +} - // https://github.com/form-data/form-data/issues/40 - if (!this.hasKnownLength()) { - /* - * Some async length retrievers are present - * therefore synchronous length calculation is false. - * Please use getLength(callback) to get proper length - */ - this._error(new Error('Cannot calculate proper length in synchronous way.')); - } +module.exports = __nccwpck_require__(46243)(exports); - return knownLength; +const {formatters} = module.exports; + +/** + * 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; + } }; -// Public API to check if length of added values is known -// https://github.com/form-data/form-data/issues/196 -// https://github.com/form-data/form-data/issues/262 -FormData.prototype.hasKnownLength = function () { - var hasKnownLength = true; - if (this._valuesToMeasure.length) { - hasKnownLength = false; - } +/***/ }), - return hasKnownLength; -}; +/***/ 46243: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -FormData.prototype.getLength = function (cb) { - var knownLength = this._overheadLength + this._valueLength; - if (this._streams.length) { - knownLength += this._lastBoundary().length; - } +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ - if (!this._valuesToMeasure.length) { - process.nextTick(cb.bind(this, null, knownLength)); - return; - } +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__(80900); + createDebug.destroy = destroy; - asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function (err, values) { - if (err) { - cb(err); - return; - } + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); - values.forEach(function (length) { - knownLength += length; - }); + /** + * The currently active debug mode names, and names to skip. + */ - cb(null, knownLength); - }); -}; + createDebug.names = []; + createDebug.skips = []; -FormData.prototype.submit = function (params, cb) { - var request; - var options; - var defaults = { method: 'post' }; + /** + * 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 = {}; - // parse provided url if it's string or treat it as options object - if (typeof params === 'string') { - params = parseUrl(params); // eslint-disable-line no-param-reassign - /* eslint sort-keys: 0 */ - options = populate({ - port: params.port, - path: params.pathname, - host: params.hostname, - protocol: params.protocol - }, defaults); - } else { // use custom params - options = populate(params, defaults); - // if no port provided use default one - if (!options.port) { - options.port = options.protocol === 'https:' ? 443 : 80; - } - } + /** + * 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; - // put that good code in getHeaders to some use - options.headers = this.getHeaders(params.headers); + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } - // https if specified, fallback to http in any other case - if (options.protocol === 'https:') { - request = https.request(options); - } else { - request = http.request(options); - } + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; - // get content length and fire away - this.getLength(function (err, length) { - if (err && err !== 'Unknown stream') { - this._error(err); - return; - } + /** + * 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; - // add content length - if (length) { - request.setHeader('Content-Length', length); - } + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } - this.pipe(request); - if (cb) { - var onResponse; + const self = debug; - var callback = function (error, responce) { - request.removeListener('error', callback); - request.removeListener('response', onResponse); + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; - return cb.call(this, error, responce); - }; + args[0] = createDebug.coerce(args[0]); - onResponse = callback.bind(this, null); + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } - request.on('error', callback); - request.on('response', onResponse); - } - }.bind(this)); + // 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); - return request; -}; + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); -FormData.prototype._error = function (err) { - if (!this.error) { - this.error = err; - this.pause(); - this.emit('error', err); - } -}; + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); -FormData.prototype.toString = function () { - return '[object FormData]'; -}; -setToStringTag(FormData.prototype, 'FormData'); + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } -// Public API -module.exports = FormData; + 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); + } -/***/ }), + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); -/***/ 47027: -/***/ ((module) => { + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } -"use strict"; + return debug; + } + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } -// populates missing values -module.exports = function (dst, src) { - Object.keys(src).forEach(function (prop) { - dst[prop] = dst[prop] || src[prop]; // eslint-disable-line no-param-reassign - }); + /** + * 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; - return dst; -}; + 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; + } -/***/ 9417: -/***/ ((module) => { + 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 + '$')); + } + } + } -module.exports = balanced; -function balanced(a, b, str) { - if (a instanceof RegExp) a = maybeMatch(a, str); - if (b instanceof RegExp) b = maybeMatch(b, str); + /** + * 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 r = range(a, b, str); + /** + * 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; + } - 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) - }; -} + let i; + let len; -function maybeMatch(reg, str) { - var m = str.match(reg); - return m ? m[0] : null; -} + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } -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; + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } - if (ai >= 0 && bi > 0) { - if(a===b) { - return [ai, bi]; - } - begs = []; - left = str.length; + return false; + } - 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; - } + /** + * 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(/\.\*\?$/, '*'); + } - bi = str.indexOf(b, i + 1); - } + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } - i = ai < bi && ai >= 0 ? ai : bi; - } + /** + * 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`.'); + } - if (begs.length) { - result = [ left, right ]; - } - } + createDebug.enable(createDebug.load()); - return result; + return createDebug; } +module.exports = setup; + /***/ }), -/***/ 85848: -/***/ (function(module, exports, __nccwpck_require__) { +/***/ 38237: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/* module decorator */ module = __nccwpck_require__.nmd(module); -/*! https://mths.be/base64 v1.0.0 by @mathias | MIT license */ -;(function(root) { +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ - // Detect free variables `exports`. - var freeExports = true && exports; +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = __nccwpck_require__(28222); +} else { + module.exports = __nccwpck_require__(35332); +} - // Detect free variable `module`. - var freeModule = true && module && - module.exports == freeExports && module; - // Detect free variable `global`, from Node.js or Browserified code, and use - // it as `root`. - var freeGlobal = typeof global == 'object' && global; - if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { - root = freeGlobal; - } +/***/ }), - /*--------------------------------------------------------------------------*/ +/***/ 35332: +/***/ ((module, exports, __nccwpck_require__) => { - var InvalidCharacterError = function(message) { - this.message = message; - }; - InvalidCharacterError.prototype = new Error; - InvalidCharacterError.prototype.name = 'InvalidCharacterError'; +/** + * Module dependencies. + */ - var error = function(message) { - // Note: the error messages used throughout this file match those used by - // the native `atob`/`btoa` implementation in Chromium. - throw new InvalidCharacterError(message); - }; +const tty = __nccwpck_require__(76224); +const util = __nccwpck_require__(73837); - var TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - // http://whatwg.org/html/common-microsyntaxes.html#space-character - var REGEX_SPACE_CHARACTERS = /[\t\n\f\r ]/g; +/** + * This is the Node.js implementation of `debug()`. + */ - // `decode` is designed to be fully compatible with `atob` as described in the - // HTML Standard. http://whatwg.org/html/webappapis.html#dom-windowbase64-atob - // The optimized base64-decoding algorithm used is based on @atk’s excellent - // implementation. https://gist.github.com/atk/1020396 - var decode = function(input) { - input = String(input) - .replace(REGEX_SPACE_CHARACTERS, ''); - var length = input.length; - if (length % 4 == 0) { - input = input.replace(/==?$/, ''); - length = input.length; - } - if ( - length % 4 == 1 || - // http://whatwg.org/C#alphanumeric-ascii-characters - /[^+a-zA-Z0-9/]/.test(input) - ) { - error( - 'Invalid character: the string to be decoded is not correctly encoded.' - ); - } - var bitCounter = 0; - var bitStorage; - var buffer; - var output = ''; - var position = -1; - while (++position < length) { - buffer = TABLE.indexOf(input.charAt(position)); - bitStorage = bitCounter % 4 ? bitStorage * 64 + buffer : buffer; - // Unless this is the first of a group of 4 characters… - if (bitCounter++ % 4) { - // …convert the first 8 bits to a single ASCII character. - output += String.fromCharCode( - 0xFF & bitStorage >> (-2 * bitCounter & 6) - ); - } - } - return output; - }; +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`.' +); - // `encode` is designed to be fully compatible with `btoa` as described in the - // HTML Standard: http://whatwg.org/html/webappapis.html#dom-windowbase64-btoa - var encode = function(input) { - input = String(input); - if (/[^\0-\xFF]/.test(input)) { - // Note: no need to special-case astral symbols here, as surrogates are - // matched, and the input is supposed to only contain ASCII anyway. - error( - 'The string to be encoded contains characters outside of the ' + - 'Latin1 range.' - ); - } - var padding = input.length % 3; - var output = ''; - var position = -1; - var a; - var b; - var c; - var buffer; - // Make sure any padding is handled outside of the loop. - var length = input.length - padding; +/** + * Colors. + */ - while (++position < length) { - // Read three bytes, i.e. 24 bits. - a = input.charCodeAt(position) << 16; - b = input.charCodeAt(++position) << 8; - c = input.charCodeAt(++position); - buffer = a + b + c; - // Turn the 24 bits into four chunks of 6 bits each, and append the - // matching character for each of them to the output. - output += ( - TABLE.charAt(buffer >> 18 & 0x3F) + - TABLE.charAt(buffer >> 12 & 0x3F) + - TABLE.charAt(buffer >> 6 & 0x3F) + - TABLE.charAt(buffer & 0x3F) - ); - } +exports.colors = [6, 2, 3, 4, 5, 1]; - if (padding == 2) { - a = input.charCodeAt(position) << 8; - b = input.charCodeAt(++position); - buffer = a + b; - output += ( - TABLE.charAt(buffer >> 10) + - TABLE.charAt((buffer >> 4) & 0x3F) + - TABLE.charAt((buffer << 2) & 0x3F) + - '=' - ); - } else if (padding == 1) { - buffer = input.charCodeAt(position); - output += ( - TABLE.charAt(buffer >> 2) + - TABLE.charAt((buffer << 4) & 0x3F) + - '==' - ); - } +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__(59318); - return output; - }; + 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. +} - var base64 = { - 'encode': encode, - 'decode': decode, - 'version': '1.0.0' - }; +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ - // Some AMD build optimizers, like r.js, check for specific condition patterns - // like the following: - if ( - typeof define == 'function' && - typeof define.amd == 'object' && - define.amd - ) { - define(function() { - return base64; +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(); }); - } else if (freeExports && !freeExports.nodeType) { - if (freeModule) { // in Node.js or RingoJS v0.8.0+ - freeModule.exports = base64; - } else { // in Narwhal or RingoJS v0.7.0- - for (var key in base64) { - base64.hasOwnProperty(key) && (freeExports[key] = base64[key]); - } - } - } else { // in Rhino or a web browser - root.base64 = base64; + + // 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); } -}(this)); + 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); +} -/***/ 45447: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * 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 crypto_hash_sha512 = (__nccwpck_require__(68729).lowlevel.crypto_hash); + 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]; + } +} -/* - * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a - * result, it retains the original copyright and license. The two files are - * under slightly different (but compatible) licenses, and are here combined in - * one file. - * - * Credit for the actual porting work goes to: - * Devi Mandiri - */ +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; +} -/* - * The Blowfish portions are under the following license: - * - * Blowfish block cipher for OpenBSD - * Copyright 1997 Niels Provos - * All rights reserved. - * - * Implementation advice by David Mazieres . - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +/** + * Invokes `util.format()` with the specified arguments and writes to stderr. */ -/* - * The bcrypt_pbkdf portions are under the following license: - * - * Copyright (c) 2013 Ted Unangst - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. +function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); +} + +/** + * Save `namespaces`. * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * @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; + } +} -/* - * Performance improvements (Javascript-specific): - * - * Copyright 2016, Joyent Inc - * Author: Alex Wilson - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. +/** + * Load `namespaces`. * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * @return {String} returns the previously persisted debug modes + * @api private */ -// Ported from OpenBSD bcrypt_pbkdf.c v1.9 +function load() { + return process.env.DEBUG; +} -var BLF_J = 0; +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ -var Blowfish = function() { - this.S = [ - new Uint32Array([ - 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, - 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, - 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, - 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, - 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, - 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, - 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, - 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, - 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, - 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, - 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, - 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, - 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, - 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, - 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, - 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, - 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, - 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, - 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, - 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, - 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, - 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, - 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, - 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, - 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, - 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, - 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, - 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, - 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, - 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, - 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, - 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, - 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, - 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, - 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, - 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, - 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, - 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, - 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, - 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, - 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, - 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, - 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, - 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, - 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, - 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, - 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, - 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, - 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, - 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, - 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, - 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, - 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, - 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, - 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, - 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, - 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, - 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, - 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, - 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, - 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, - 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, - 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, - 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a]), - new Uint32Array([ - 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, - 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, - 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, - 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, - 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, - 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, - 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, - 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, - 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, - 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, - 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, - 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, - 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, - 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, - 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, - 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, - 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, - 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, - 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, - 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, - 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, - 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, - 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, - 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, - 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, - 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, - 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, - 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, - 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, - 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, - 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, - 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, - 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, - 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, - 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, - 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, - 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, - 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, - 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, - 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, - 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, - 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, - 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, - 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, - 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, - 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, - 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, - 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, - 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, - 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, - 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, - 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, - 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, - 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, - 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, - 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, - 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, - 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, - 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, - 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, - 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, - 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, - 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, - 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7]), - new Uint32Array([ - 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, - 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, - 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, - 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, - 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, - 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, - 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, - 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, - 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, - 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, - 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, - 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, - 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, - 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, - 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, - 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, - 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, - 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, - 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, - 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, - 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, - 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, - 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, - 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, - 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, - 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, - 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, - 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, - 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, - 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, - 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, - 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, - 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, - 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, - 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, - 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, - 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, - 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, - 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, - 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, - 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, - 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, - 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, - 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, - 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, - 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, - 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, - 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, - 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, - 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, - 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, - 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, - 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, - 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, - 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, - 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, - 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, - 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, - 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, - 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, - 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, - 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, - 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, - 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0]), - new Uint32Array([ - 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, - 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, - 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, - 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, - 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, - 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, - 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, - 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, - 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, - 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, - 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, - 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, - 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, - 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, - 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, - 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, - 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, - 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, - 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, - 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, - 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, - 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, - 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, - 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, - 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, - 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, - 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, - 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, - 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, - 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, - 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, - 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, - 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, - 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, - 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, - 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, - 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, - 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, - 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, - 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, - 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, - 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, - 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, - 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, - 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, - 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, - 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, - 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, - 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, - 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, - 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, - 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, - 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, - 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, - 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, - 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, - 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, - 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, - 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, - 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, - 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, - 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, - 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, - 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6]) - ]; - this.P = new Uint32Array([ - 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, - 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, - 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, - 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, - 0x9216d5d9, 0x8979fb1b]); -}; +function init(debug) { + debug.inspectOpts = {}; -function F(S, x8, i) { - return (((S[0][x8[i+3]] + - S[1][x8[i+2]]) ^ - S[2][x8[i+1]]) + - S[3][x8[i]]); -}; + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} -Blowfish.prototype.encipher = function(x, x8) { - if (x8 === undefined) { - x8 = new Uint8Array(x.buffer); - if (x.byteOffset !== 0) - x8 = x8.subarray(x.byteOffset); - } - x[0] ^= this.P[0]; - for (var i = 1; i < 16; i += 2) { - x[1] ^= F(this.S, x8, 0) ^ this.P[i]; - x[0] ^= F(this.S, x8, 4) ^ this.P[i+1]; - } - var t = x[0]; - x[0] = x[1] ^ this.P[17]; - x[1] = t; -}; +module.exports = __nccwpck_require__(46243)(exports); -Blowfish.prototype.decipher = function(x) { - var x8 = new Uint8Array(x.buffer); - if (x.byteOffset !== 0) - x8 = x8.subarray(x.byteOffset); - x[0] ^= this.P[17]; - for (var i = 16; i > 0; i -= 2) { - x[1] ^= F(this.S, x8, 0) ^ this.P[i]; - x[0] ^= F(this.S, x8, 4) ^ this.P[i-1]; - } - var t = x[0]; - x[0] = x[1] ^ this.P[0]; - x[1] = t; -}; +const {formatters} = module.exports; -function stream2word(data, databytes){ - var i, temp = 0; - for (i = 0; i < 4; i++, BLF_J++) { - if (BLF_J >= databytes) BLF_J = 0; - temp = (temp << 8) | data[BLF_J]; - } - return temp; +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); }; -Blowfish.prototype.expand0state = function(key, keybytes) { - var d = new Uint32Array(2), i, k; - var d8 = new Uint8Array(d.buffer); +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ - for (i = 0, BLF_J = 0; i < 18; i++) { - this.P[i] ^= stream2word(key, keybytes); - } - BLF_J = 0; +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; - for (i = 0; i < 18; i += 2) { - this.encipher(d, d8); - this.P[i] = d[0]; - this.P[i+1] = d[1]; - } - for (i = 0; i < 4; i++) { - for (k = 0; k < 256; k += 2) { - this.encipher(d, d8); - this.S[i][k] = d[0]; - this.S[i][k+1] = d[1]; - } - } -}; +/***/ }), -Blowfish.prototype.expandstate = function(data, databytes, key, keybytes) { - var d = new Uint32Array(2), i, k; +/***/ 82391: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - for (i = 0, BLF_J = 0; i < 18; i++) { - this.P[i] ^= stream2word(key, keybytes); - } +"use strict"; - for (i = 0, BLF_J = 0; i < 18; i += 2) { - d[0] ^= stream2word(data, databytes); - d[1] ^= stream2word(data, databytes); - this.encipher(d); - this.P[i] = d[0]; - this.P[i+1] = d[1]; - } +const {Transform, PassThrough} = __nccwpck_require__(12781); +const zlib = __nccwpck_require__(59796); +const mimicResponse = __nccwpck_require__(42610); - for (i = 0; i < 4; i++) { - for (k = 0; k < 256; k += 2) { - d[0] ^= stream2word(data, databytes); - d[1] ^= stream2word(data, databytes); - this.encipher(d); - this.S[i][k] = d[0]; - this.S[i][k+1] = d[1]; - } - } - BLF_J = 0; -}; +module.exports = response => { + const contentEncoding = (response.headers['content-encoding'] || '').toLowerCase(); -Blowfish.prototype.enc = function(data, blocks) { - for (var i = 0; i < blocks; i++) { - this.encipher(data.subarray(i*2)); - } -}; + if (!['gzip', 'deflate', 'br'].includes(contentEncoding)) { + return response; + } -Blowfish.prototype.dec = function(data, blocks) { - for (var i = 0; i < blocks; i++) { - this.decipher(data.subarray(i*2)); - } -}; + // TODO: Remove this when targeting Node.js 12. + const isBrotli = contentEncoding === 'br'; + if (isBrotli && typeof zlib.createBrotliDecompress !== 'function') { + response.destroy(new Error('Brotli is not supported on Node.js < 12')); + return response; + } -var BCRYPT_BLOCKS = 8, - BCRYPT_HASHSIZE = 32; + let isEmpty = true; -function bcrypt_hash(sha2pass, sha2salt, out) { - var state = new Blowfish(), - cdata = new Uint32Array(BCRYPT_BLOCKS), i, - ciphertext = new Uint8Array([79,120,121,99,104,114,111,109,97,116,105, - 99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109, - 105,116,101]); //"OxychromaticBlowfishSwatDynamite" + const checker = new Transform({ + transform(data, _encoding, callback) { + isEmpty = false; - state.expandstate(sha2salt, 64, sha2pass, 64); - for (i = 0; i < 64; i++) { - state.expand0state(sha2salt, 64); - state.expand0state(sha2pass, 64); - } + callback(null, data); + }, - for (i = 0; i < BCRYPT_BLOCKS; i++) - cdata[i] = stream2word(ciphertext, ciphertext.byteLength); - for (i = 0; i < 64; i++) - state.enc(cdata, cdata.byteLength / 8); + flush(callback) { + callback(); + } + }); - for (i = 0; i < BCRYPT_BLOCKS; i++) { - out[4*i+3] = cdata[i] >>> 24; - out[4*i+2] = cdata[i] >>> 16; - out[4*i+1] = cdata[i] >>> 8; - out[4*i+0] = cdata[i]; - } -}; + const finalStream = new PassThrough({ + autoDestroy: false, + destroy(error, callback) { + response.destroy(); -function bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) { - var sha2pass = new Uint8Array(64), - sha2salt = new Uint8Array(64), - out = new Uint8Array(BCRYPT_HASHSIZE), - tmpout = new Uint8Array(BCRYPT_HASHSIZE), - countsalt = new Uint8Array(saltlen+4), - i, j, amt, stride, dest, count, - origkeylen = keylen; + callback(error); + } + }); - if (rounds < 1) - return -1; - if (passlen === 0 || saltlen === 0 || keylen === 0 || - keylen > (out.byteLength * out.byteLength) || saltlen > (1<<20)) - return -1; + const decompressStream = isBrotli ? zlib.createBrotliDecompress() : zlib.createUnzip(); - stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength); - amt = Math.floor((keylen + stride - 1) / stride); + decompressStream.once('error', error => { + if (isEmpty && !response.readable) { + finalStream.end(); + return; + } - for (i = 0; i < saltlen; i++) - countsalt[i] = salt[i]; + finalStream.destroy(error); + }); - crypto_hash_sha512(sha2pass, pass, passlen); + mimicResponse(response, finalStream); + response.pipe(checker).pipe(decompressStream).pipe(finalStream); - for (count = 1; keylen > 0; count++) { - countsalt[saltlen+0] = count >>> 24; - countsalt[saltlen+1] = count >>> 16; - countsalt[saltlen+2] = count >>> 8; - countsalt[saltlen+3] = count; + return finalStream; +}; - crypto_hash_sha512(sha2salt, countsalt, saltlen + 4); - bcrypt_hash(sha2pass, sha2salt, tmpout); - for (i = out.byteLength; i--;) - out[i] = tmpout[i]; - for (i = 1; i < rounds; i++) { - crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength); - bcrypt_hash(sha2pass, sha2salt, tmpout); - for (j = 0; j < out.byteLength; j++) - out[j] ^= tmpout[j]; - } +/***/ }), - amt = Math.min(amt, keylen); - for (i = 0; i < amt; i++) { - dest = i * stride + (count - 1); - if (dest >= origkeylen) - break; - key[dest] = out[i]; - } - keylen -= i; - } +/***/ 96214: +/***/ ((module, exports) => { - return 0; -}; +"use strict"; -module.exports = { - BLOCKS: BCRYPT_BLOCKS, - HASHSIZE: BCRYPT_HASHSIZE, - hash: bcrypt_hash, - pbkdf: bcrypt_pbkdf +Object.defineProperty(exports, "__esModule", ({ value: true })); +function isTLSSocket(socket) { + return socket.encrypted; +} +const deferToConnect = (socket, fn) => { + let listeners; + if (typeof fn === 'function') { + const connect = fn; + listeners = { connect }; + } + else { + listeners = fn; + } + const hasConnectListener = typeof listeners.connect === 'function'; + const hasSecureConnectListener = typeof listeners.secureConnect === 'function'; + const hasCloseListener = typeof listeners.close === 'function'; + const onConnect = () => { + if (hasConnectListener) { + listeners.connect(); + } + if (isTLSSocket(socket) && hasSecureConnectListener) { + if (socket.authorized) { + listeners.secureConnect(); + } + else if (!socket.authorizationError) { + socket.once('secureConnect', listeners.secureConnect); + } + } + if (hasCloseListener) { + socket.once('close', listeners.close); + } + }; + if (socket.writable && !socket.connecting) { + onConnect(); + } + else if (socket.connecting) { + socket.once('connect', onConnect); + } + else if (socket.destroyed && hasCloseListener) { + listeners.close(socket._hadError); + } }; +exports["default"] = deferToConnect; +// For CommonJS default export support +module.exports = deferToConnect; +module.exports["default"] = deferToConnect; /***/ }), -/***/ 83682: +/***/ 18611: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var register = __nccwpck_require__(44670); -var addHook = __nccwpck_require__(5549); -var removeHook = __nccwpck_require__(6819); +var Stream = (__nccwpck_require__(12781).Stream); +var util = __nccwpck_require__(73837); -// bind with array of arguments: https://stackoverflow.com/a/21792913 -var bind = Function.bind; -var bindable = bind.bind(bind); +module.exports = DelayedStream; +function DelayedStream() { + this.source = null; + this.dataSize = 0; + this.maxDataSize = 1024 * 1024; + this.pauseStream = 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); - }); + this._maxDataSizeExceeded = false; + this._released = false; + this._bufferedEvents = []; } +util.inherits(DelayedStream, Stream); -function HookSingular() { - var singularHookName = "h"; - var singularHookState = { - registry: {}, - }; - var singularHook = register.bind(null, singularHookState, singularHookName); - bindApi(singularHook, singularHookState, singularHookName); - return singularHook; -} +DelayedStream.create = function(source, options) { + var delayedStream = new this(); -function HookCollection() { - var state = { - registry: {}, + options = options || {}; + for (var option in options) { + delayedStream[option] = options[option]; + } + + delayedStream.source = source; + + var realEmit = source.emit; + source.emit = function() { + delayedStream._handleEmit(arguments); + return realEmit.apply(source, arguments); }; - var hook = register.bind(null, state); - bindApi(hook, state); + source.on('error', function() {}); + if (delayedStream.pauseStream) { + source.pause(); + } - return hook; -} + return delayedStream; +}; -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; +Object.defineProperty(DelayedStream.prototype, 'readable', { + configurable: true, + enumerable: true, + get: function() { + return this.source.readable; } - return HookCollection(); -} +}); -Hook.Singular = HookSingular.bind(); -Hook.Collection = HookCollection.bind(); +DelayedStream.prototype.setEncoding = function() { + return this.source.setEncoding.apply(this.source, arguments); +}; -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; +DelayedStream.prototype.resume = function() { + if (!this._released) { + this.release(); + } + this.source.resume(); +}; -/***/ }), +DelayedStream.prototype.pause = function() { + this.source.pause(); +}; -/***/ 5549: -/***/ ((module) => { +DelayedStream.prototype.release = function() { + this._released = true; -module.exports = addHook; + this._bufferedEvents.forEach(function(args) { + this.emit.apply(this, args); + }.bind(this)); + this._bufferedEvents = []; +}; -function addHook(state, kind, name, hook) { - var orig = hook; - if (!state.registry[name]) { - state.registry[name] = []; +DelayedStream.prototype.pipe = function() { + var r = Stream.prototype.pipe.apply(this, arguments); + this.resume(); + return r; +}; + +DelayedStream.prototype._handleEmit = function(args) { + if (this._released) { + this.emit.apply(this, args); + return; } - if (kind === "before") { - hook = function (method, options) { - return Promise.resolve() - .then(orig.bind(null, options)) - .then(method.bind(null, options)); - }; + if (args[0] === 'data') { + this.dataSize += args[1].length; + this._checkIfMaxDataSizeExceeded(); } - 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; - }); - }; + this._bufferedEvents.push(args); +}; + +DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { + if (this._maxDataSizeExceeded) { + return; } - if (kind === "error") { - hook = function (method, options) { - return Promise.resolve() - .then(method.bind(null, options)) - .catch(function (error) { - return orig(error, options); - }); - }; + if (this.dataSize <= this.maxDataSize) { + return; } - state.registry[name].push({ - hook: hook, - orig: orig, - }); -} + this._maxDataSizeExceeded = true; + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' + this.emit('error', new Error(message)); +}; /***/ }), -/***/ 44670: -/***/ ((module) => { +/***/ 58932: +/***/ ((__unused_webpack_module, exports) => { -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"); - } - if (!options) { - options = {}; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - if (Array.isArray(name)) { - return name.reverse().reduce(function (callback, name) { - return register.bind(null, state, name, callback, options); - }, method)(); - } +class Deprecation extends Error { + constructor(message) { + super(message); // Maintains proper stack trace (only available on V8) - return Promise.resolve().then(function () { - if (!state.registry[name]) { - return method(options); + /* istanbul ignore next */ + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); } - return state.registry[name].reduce(function (method, registered) { - return registered.hook.bind(null, method, options); - }, method)(); - }); + this.name = 'Deprecation'; + } + } +exports.Deprecation = Deprecation; + /***/ }), -/***/ 6819: +/***/ 13598: /***/ ((module) => { -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); +function _process (v, mod) { + var i + var r - if (index === -1) { - return; + if (typeof mod === 'function') { + r = mod(v) + if (r !== undefined) { + v = r + } + } else if (Array.isArray(mod)) { + for (i = 0; i < mod.length; i++) { + r = mod[i](v) + if (r !== undefined) { + v = r + } + } } - state.registry[name].splice(index, 1); + return v } +function parseKey (key, val) { + // detect negative index notation + if (key[0] === '-' && Array.isArray(val) && /^-\d+$/.test(key)) { + return val.length + parseInt(key, 10) + } + return key +} -/***/ }), - -/***/ 33717: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var concatMap = __nccwpck_require__(86891); -var balanced = __nccwpck_require__(9417); - -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); +function isIndex (k) { + return /^\d+$/.test(k) } -function escapeBraces(str) { - return str.split('\\\\').join(escSlash) - .split('\\{').join(escOpen) - .split('\\}').join(escClose) - .split('\\,').join(escComma) - .split('\\.').join(escPeriod); +function isObject (val) { + return Object.prototype.toString.call(val) === '[object Object]' } -function unescapeBraces(str) { - return str.split(escSlash).join('\\') - .split(escOpen).join('{') - .split(escClose).join('}') - .split(escComma).join(',') - .split(escPeriod).join('.'); +function isArrayOrObject (val) { + return Object(val) === val } +function isEmptyObject (val) { + return Object.keys(val).length === 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 ['']; +var blacklist = ['__proto__', 'prototype', 'constructor'] +var blacklistFilter = function (part) { return blacklist.indexOf(part) === -1 } - var parts = []; - var m = balanced('{', '}', str); +function parsePath (path, sep) { + if (path.indexOf('[') >= 0) { + path = path.replace(/\[/g, sep).replace(/]/g, '') + } - if (!m) - return str.split(','); + var parts = path.split(sep) - var pre = m.pre; - var body = m.body; - var post = m.post; - var p = pre.split(','); + var check = parts.filter(blacklistFilter) - p[p.length-1] += '{' + body + '}'; - var postParts = parseCommaParts(post); - if (post.length) { - p[p.length-1] += postParts.shift(); - p.push.apply(p, postParts); + if (check.length !== parts.length) { + throw Error('Refusing to update blacklisted property ' + path) } - parts.push.apply(parts, p); - - return parts; + return parts } -function expandTop(str) { - if (!str) - return []; +var hasOwnProperty = Object.prototype.hasOwnProperty - // 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); +function DotObject (separator, override, useArray, useBrackets) { + if (!(this instanceof DotObject)) { + return new DotObject(separator, override, useArray, useBrackets) } - return expand(escapeBraces(str), true).map(unescapeBraces); -} + if (typeof override === 'undefined') override = false + if (typeof useArray === 'undefined') useArray = true + if (typeof useBrackets === 'undefined') useBrackets = true + this.separator = separator || '.' + this.override = override + this.useArray = useArray + this.useBrackets = useBrackets + this.keepArray = false -function identity(e) { - return e; + // contains touched arrays + this.cleanup = [] } -function embrace(str) { - return '{' + str + '}'; -} -function isPadded(el) { - return /^-?0\d/.test(el); +var dotDefault = new DotObject('.', false, true, true) +function wrap (method) { + return function () { + return dotDefault[method].apply(dotDefault, arguments) + } } -function lte(i, y) { - return i <= y; -} -function gte(i, y) { - return i >= y; -} +DotObject.prototype._fill = function (a, obj, v, mod) { + var k = a.shift() -function expand(str, isTop) { - var expansions = []; + if (a.length > 0) { + obj[k] = obj[k] || (this.useArray && isIndex(a[0]) ? [] : {}) - var m = balanced('{', '}', str); - if (!m || /\$$/.test(m.pre)) return [str]; + if (!isArrayOrObject(obj[k])) { + if (this.override) { + obj[k] = {} + } else { + if (!(isArrayOrObject(v) && isEmptyObject(v))) { + throw new Error( + 'Trying to redefine `' + k + '` which is a ' + typeof obj[k] + ) + } - 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 + } } - return [str]; - } - var n; - if (isSequence) { - n = m.body.split(/\.\./); + this._fill(a, obj[k], v, mod) } 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; - }); + if (!this.override && isArrayOrObject(obj[k]) && !isEmptyObject(obj[k])) { + if (!(isArrayOrObject(v) && isEmptyObject(v))) { + throw new Error("Trying to redefine non-empty obj['" + k + "']") } + + return } - } - // at this point, n is the parts, and we know it's not a comma set - // with a single entry. + obj[k] = _process(v, mod) + } +} - // 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) - : ['']; +/** + * + * Converts an object with dotted-key/value pairs to it's expanded version + * + * Optionally transformed by a set of modifiers. + * + * Usage: + * + * var row = { + * 'nr': 200, + * 'doc.name': ' My Document ' + * } + * + * var mods = { + * 'doc.name': [_s.trim, _s.underscored] + * } + * + * dot.object(row, mods) + * + * @param {Object} obj + * @param {Object} mods + */ +DotObject.prototype.object = function (obj, mods) { + var self = this - var N; + Object.keys(obj).forEach(function (k) { + var mod = mods === undefined ? null : mods[k] + // normalize array notation. + var ok = parsePath(k, self.separator).join(self.separator) - 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; + if (ok.indexOf(self.separator) !== -1) { + self._fill(ok.split(self.separator), obj, obj[k], mod) + delete obj[k] + } else { + obj[k] = _process(obj[k], mod) } - var pad = n.some(isPadded); + }) - N = []; + return obj +} - 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; +/** + * @param {String} path dotted path + * @param {String} v value to be set + * @param {Object} obj object to be modified + * @param {Function|Array} mod optional modifier + */ +DotObject.prototype.str = function (path, v, obj, mod) { + var ok = parsePath(path, this.separator).join(this.separator) + + if (path.indexOf(this.separator) !== -1) { + this._fill(ok.split(this.separator), obj, v, mod) + } else { + obj[path] = _process(v, mod) + } + + return obj +} + +/** + * + * Pick a value from an object using dot notation. + * + * Optionally remove the value + * + * @param {String} path + * @param {Object} obj + * @param {Boolean} remove + */ +DotObject.prototype.pick = function (path, obj, remove, reindexArray) { + var i + var keys + var val + var key + var cp + + keys = parsePath(path, this.separator) + for (i = 0; i < keys.length; i++) { + key = parseKey(keys[i], obj) + if (obj && typeof obj === 'object' && key in obj) { + if (i === keys.length - 1) { + if (remove) { + val = obj[key] + if (reindexArray && Array.isArray(obj)) { + obj.splice(key, 1) + } else { + delete obj[key] + } + if (Array.isArray(obj)) { + cp = keys.slice(0, -1).join('.') + if (this.cleanup.indexOf(cp) === -1) { + this.cleanup.push(cp) + } } + return val + } else { + return obj[key] } + } else { + obj = obj[key] } - N.push(c); + } else { + return undefined } - } 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); - } + if (remove && Array.isArray(obj)) { + obj = obj.filter(function (n) { + return n !== undefined + }) } - - return expansions; + return obj +} +/** + * + * Delete value from an object using dot notation. + * + * @param {String} path + * @param {Object} obj + * @return {any} The removed value + */ +DotObject.prototype.delete = function (path, obj) { + return this.remove(path, obj, true) } +/** + * + * Remove value from an object using dot notation. + * + * Will remove multiple items if path is an array. + * In this case array indexes will be retained until all + * removals have been processed. + * + * Use dot.delete() to automatically re-index arrays. + * + * @param {String|Array} path + * @param {Object} obj + * @param {Boolean} reindexArray + * @return {any} The removed value + */ +DotObject.prototype.remove = function (path, obj, reindexArray) { + var i + this.cleanup = [] + if (Array.isArray(path)) { + for (i = 0; i < path.length; i++) { + this.pick(path[i], obj, true, reindexArray) + } + if (!reindexArray) { + this._cleanup(obj) + } + return obj + } else { + return this.pick(path, obj, true, reindexArray) + } +} -/***/ }), - -/***/ 29700: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -// Copyright (C) 2011-2015 John Hewson -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to -// deal in the Software without restriction, including without limitation the -// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -// sell copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -// IN THE SOFTWARE. - -var stream = __nccwpck_require__(12781), - util = __nccwpck_require__(73837), - timers = __nccwpck_require__(39512); +DotObject.prototype._cleanup = function (obj) { + var ret + var i + var keys + var root + if (this.cleanup.length) { + for (i = 0; i < this.cleanup.length; i++) { + keys = this.cleanup[i].split('.') + root = keys.splice(0, -1).join('.') + ret = root ? this.pick(root, obj) : obj + ret = ret[keys[0]].filter(function (v) { + return v !== undefined + }) + this.set(this.cleanup[i], ret, obj) + } + this.cleanup = [] + } +} -// convinience API -module.exports = function(readStream, options) { - return module.exports.createStream(readStream, options); -}; +/** + * Alias method for `dot.remove` + * + * Note: this is not an alias for dot.delete() + * + * @param {String|Array} path + * @param {Object} obj + * @param {Boolean} reindexArray + * @return {any} The removed value + */ +DotObject.prototype.del = DotObject.prototype.remove -// basic API -module.exports.createStream = function(readStream, options) { - if (readStream) { - return createLineStream(readStream, options); +/** + * + * Move a property from one place to the other. + * + * If the source path does not exist (undefined) + * the target property will not be set. + * + * @param {String} source + * @param {String} target + * @param {Object} obj + * @param {Function|Array} mods + * @param {Boolean} merge + */ +DotObject.prototype.move = function (source, target, obj, mods, merge) { + if (typeof mods === 'function' || Array.isArray(mods)) { + this.set(target, _process(this.pick(source, obj, true), mods), obj, merge) } else { - return new LineStream(options); + merge = mods + this.set(target, this.pick(source, obj, true), obj, merge) } -}; -// deprecated API -module.exports.createLineStream = function(readStream) { - console.log('WARNING: byline#createLineStream is deprecated and will be removed soon'); - return createLineStream(readStream); -}; + return obj +} -function createLineStream(readStream, options) { - if (!readStream) { - throw new Error('expected readStream'); - } - if (!readStream.readable) { - throw new Error('readStream must be readable'); +/** + * + * Transfer a property from one object to another object. + * + * If the source path does not exist (undefined) + * the property on the other object will not be set. + * + * @param {String} source + * @param {String} target + * @param {Object} obj1 + * @param {Object} obj2 + * @param {Function|Array} mods + * @param {Boolean} merge + */ +DotObject.prototype.transfer = function ( + source, + target, + obj1, + obj2, + mods, + merge +) { + if (typeof mods === 'function' || Array.isArray(mods)) { + this.set( + target, + _process(this.pick(source, obj1, true), mods), + obj2, + merge + ) + } else { + merge = mods + this.set(target, this.pick(source, obj1, true), obj2, merge) } - var ls = new LineStream(options); - readStream.pipe(ls); - return ls; + + return obj2 } -// -// using the new node v0.10 "streams2" API -// +/** + * + * Copy a property from one object to another object. + * + * If the source path does not exist (undefined) + * the property on the other object will not be set. + * + * @param {String} source + * @param {String} target + * @param {Object} obj1 + * @param {Object} obj2 + * @param {Function|Array} mods + * @param {Boolean} merge + */ +DotObject.prototype.copy = function (source, target, obj1, obj2, mods, merge) { + if (typeof mods === 'function' || Array.isArray(mods)) { + this.set( + target, + _process( + // clone what is picked + JSON.parse(JSON.stringify(this.pick(source, obj1, false))), + mods + ), + obj2, + merge + ) + } else { + merge = mods + this.set(target, this.pick(source, obj1, false), obj2, merge) + } -module.exports.LineStream = LineStream; + return obj2 +} -function LineStream(options) { - stream.Transform.call(this, options); - options = options || {}; +/** + * + * Set a property on an object using dot notation. + * + * @param {String} path + * @param {any} val + * @param {Object} obj + * @param {Boolean} merge + */ +DotObject.prototype.set = function (path, val, obj, merge) { + var i + var k + var keys + var key - // use objectMode to stop the output from being buffered - // which re-concatanates the lines, just without newlines. - this._readableState.objectMode = true; - this._lineBuffer = []; - this._keepEmptyLines = options.keepEmptyLines || false; - this._lastChunkEndedWithCR = false; + // Do not operate if the value is undefined. + if (typeof val === 'undefined') { + return obj + } + keys = parsePath(path, this.separator) - // take the source's encoding if we don't have one - var self = this; - this.on('pipe', function(src) { - if (!self.encoding) { - // but we can't do this for old-style streams - if (src instanceof stream.Readable) { - self.encoding = src._readableState.encoding; + for (i = 0; i < keys.length; i++) { + key = keys[i] + if (i === keys.length - 1) { + if (merge && isObject(val) && isObject(obj[key])) { + for (k in val) { + if (hasOwnProperty.call(val, k)) { + obj[key][k] = val[k] + } + } + } else if (merge && Array.isArray(obj[key]) && Array.isArray(val)) { + for (var j = 0; j < val.length; j++) { + obj[keys[i]].push(val[j]) + } + } else { + obj[key] = val + } + } else if ( + // force the value to be an object + !hasOwnProperty.call(obj, key) || + (!isObject(obj[key]) && !Array.isArray(obj[key])) + ) { + // initialize as array if next key is numeric + if (/^\d+$/.test(keys[i + 1])) { + obj[key] = [] + } else { + obj[key] = {} } } - }); + obj = obj[key] + } + return obj } -util.inherits(LineStream, stream.Transform); -LineStream.prototype._transform = function(chunk, encoding, done) { - // decode binary chunks as UTF-8 - encoding = encoding || 'utf8'; - - if (Buffer.isBuffer(chunk)) { - if (encoding == 'buffer') { - chunk = chunk.toString(); // utf8 - encoding = 'utf8'; - } - else { - chunk = chunk.toString(encoding); - } - } - this._chunkEncoding = encoding; - - // see: http://www.unicode.org/reports/tr18/#Line_Boundaries - var lines = chunk.split(/\r\n|[\n\v\f\r\x85\u2028\u2029]/g); - - // don't split CRLF which spans chunks - if (this._lastChunkEndedWithCR && chunk[0] == '\n') { - lines.shift(); - } - - if (this._lineBuffer.length > 0) { - this._lineBuffer[this._lineBuffer.length - 1] += lines[0]; - lines.shift(); - } +/** + * + * Transform an object + * + * Usage: + * + * var obj = { + * "id": 1, + * "some": { + * "thing": "else" + * } + * } + * + * var transform = { + * "id": "nr", + * "some.thing": "name" + * } + * + * var tgt = dot.transform(transform, obj) + * + * @param {Object} recipe Transform recipe + * @param {Object} obj Object to be transformed + * @param {Array} mods modifiers for the target + */ +DotObject.prototype.transform = function (recipe, obj, tgt) { + obj = obj || {} + tgt = tgt || {} + Object.keys(recipe).forEach( + function (key) { + this.set(recipe[key], this.pick(key, obj), tgt) + }.bind(this) + ) + return tgt +} - this._lastChunkEndedWithCR = chunk[chunk.length - 1] == '\r'; - this._lineBuffer = this._lineBuffer.concat(lines); - this._pushBuffer(encoding, 1, done); -}; +/** + * + * Convert object to dotted-key/value pair + * + * Usage: + * + * var tgt = dot.dot(obj) + * + * or + * + * var tgt = {} + * dot.dot(obj, tgt) + * + * @param {Object} obj source object + * @param {Object} tgt target object + * @param {Array} path path array (internal) + */ +DotObject.prototype.dot = function (obj, tgt, path) { + tgt = tgt || {} + path = path || [] + var isArray = Array.isArray(obj) -LineStream.prototype._pushBuffer = function(encoding, keep, done) { - // always buffer the last (possibly partial) line - while (this._lineBuffer.length > keep) { - var line = this._lineBuffer.shift(); - // skip empty lines - if (this._keepEmptyLines || line.length > 0 ) { - if (!this.push(this._reencode(line, encoding))) { - // when the high-water mark is reached, defer pushes until the next tick - var self = this; - timers.setImmediate(function() { - self._pushBuffer(encoding, keep, done); - }); - return; + Object.keys(obj).forEach( + function (key) { + var index = isArray && this.useBrackets ? '[' + key + ']' : key + if ( + isArrayOrObject(obj[key]) && + ((isObject(obj[key]) && !isEmptyObject(obj[key])) || + (Array.isArray(obj[key]) && !this.keepArray && obj[key].length !== 0)) + ) { + if (isArray && this.useBrackets) { + var previousKey = path[path.length - 1] || '' + return this.dot( + obj[key], + tgt, + path.slice(0, -1).concat(previousKey + index) + ) + } else { + return this.dot(obj[key], tgt, path.concat(index)) + } + } else { + if (isArray && this.useBrackets) { + tgt[path.join(this.separator).concat('[' + key + ']')] = obj[key] + } else { + tgt[path.concat(index).join(this.separator)] = obj[key] + } } + }.bind(this) + ) + return tgt +} + +DotObject.pick = wrap('pick') +DotObject.move = wrap('move') +DotObject.transfer = wrap('transfer') +DotObject.transform = wrap('transform') +DotObject.copy = wrap('copy') +DotObject.object = wrap('object') +DotObject.str = wrap('str') +DotObject.set = wrap('set') +DotObject.delete = wrap('delete') +DotObject.del = DotObject.remove = wrap('remove') +DotObject.dot = wrap('dot'); +['override', 'overwrite'].forEach(function (prop) { + Object.defineProperty(DotObject, prop, { + get: function () { + return dotDefault.override + }, + set: function (val) { + dotDefault.override = !!val } - } - done(); -}; + }) +}); +['useArray', 'keepArray', 'useBrackets'].forEach(function (prop) { + Object.defineProperty(DotObject, prop, { + get: function () { + return dotDefault[prop] + }, + set: function (val) { + dotDefault[prop] = val + } + }) +}) -LineStream.prototype._flush = function(done) { - this._pushBuffer(this._chunkEncoding, 0, done); -}; +DotObject._process = _process -// see Readable::push -LineStream.prototype._reencode = function(line, chunkEncoding) { - if (this.encoding && this.encoding != chunkEncoding) { - return new Buffer(line, chunkEncoding).toString(this.encoding); - } - else if (this.encoding) { - // this should be the most common case, i.e. we're using an encoded source stream - return line; - } - else { - return new Buffer(line, chunkEncoding); - } -}; +module.exports = DotObject /***/ }), -/***/ 2286: +/***/ 62693: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { - V4MAPPED, - ADDRCONFIG, - ALL, - promises: { - Resolver: AsyncResolver - }, - lookup: dnsLookup -} = __nccwpck_require__(17578); -const {promisify} = __nccwpck_require__(73837); -const os = __nccwpck_require__(22037); - -const kCacheableLookupCreateConnection = Symbol('cacheableLookupCreateConnection'); -const kCacheableLookupInstance = Symbol('cacheableLookupInstance'); -const kExpires = Symbol('expires'); - -const supportsALL = typeof ALL === 'number'; - -const verifyAgent = agent => { - if (!(agent && typeof agent.createConnection === 'function')) { - throw new Error('Expected an Agent instance as the first argument'); - } -}; - -const map4to6 = entries => { - for (const entry of entries) { - if (entry.family === 6) { - continue; - } - - entry.address = `::ffff:${entry.address}`; - entry.family = 6; - } -}; - -const getIfaceInfo = () => { - let has4 = false; - let has6 = false; - - for (const device of Object.values(os.networkInterfaces())) { - for (const iface of device) { - if (iface.internal) { - continue; - } - if (iface.family === 'IPv6') { - has6 = true; - } else { - has4 = true; - } +var callBind = __nccwpck_require__(86815); +var gOPD = __nccwpck_require__(34709); - if (has4 && has6) { - return {has4, has6}; - } - } +var hasProtoAccessor; +try { + // eslint-disable-next-line no-extra-parens, no-proto + hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */ ([]).__proto__ === Array.prototype; +} catch (e) { + if (!e || typeof e !== 'object' || !('code' in e) || e.code !== 'ERR_PROTO_ACCESS') { + throw e; } +} - return {has4, has6}; -}; - -const isIterable = map => { - return Symbol.iterator in map; -}; - -const ttl = {ttl: true}; -const all = {all: true}; - -class CacheableLookup { - constructor({ - cache = new Map(), - maxTtl = Infinity, - fallbackDuration = 3600, - errorTtl = 0.15, - resolver = new AsyncResolver(), - lookup = dnsLookup - } = {}) { - this.maxTtl = maxTtl; - this.errorTtl = errorTtl; - - this._cache = cache; - this._resolver = resolver; - this._dnsLookup = promisify(lookup); - - if (this._resolver instanceof AsyncResolver) { - this._resolve4 = this._resolver.resolve4.bind(this._resolver); - this._resolve6 = this._resolver.resolve6.bind(this._resolver); - } else { - this._resolve4 = promisify(this._resolver.resolve4.bind(this._resolver)); - this._resolve6 = promisify(this._resolver.resolve6.bind(this._resolver)); - } - - this._iface = getIfaceInfo(); - - this._pending = {}; - this._nextRemovalTime = false; - this._hostnamesToFallback = new Set(); - - if (fallbackDuration < 1) { - this._fallback = false; - } else { - this._fallback = true; +// eslint-disable-next-line no-extra-parens +var desc = !!hasProtoAccessor && gOPD && gOPD(Object.prototype, /** @type {keyof typeof Object.prototype} */ ('__proto__')); - const interval = setInterval(() => { - this._hostnamesToFallback.clear(); - }, fallbackDuration * 1000); +var $Object = Object; +var $getPrototypeOf = $Object.getPrototypeOf; - /* istanbul ignore next: There is no `interval.unref()` when running inside an Electron renderer */ - if (interval.unref) { - interval.unref(); - } +/** @type {import('./get')} */ +module.exports = desc && typeof desc.get === 'function' + ? callBind([desc.get]) + : typeof $getPrototypeOf === 'function' + ? /** @type {import('./get')} */ function getDunder(value) { + // eslint-disable-next-line eqeqeq + return $getPrototypeOf(value == null ? value : $Object(value)); } + : false; - this.lookup = this.lookup.bind(this); - this.lookupAsync = this.lookupAsync.bind(this); - } - - set servers(servers) { - this.clear(); - - this._resolver.setServers(servers); - } - - get servers() { - return this._resolver.getServers(); - } - lookup(hostname, options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } else if (typeof options === 'number') { - options = { - family: options - }; - } +/***/ }), - if (!callback) { - throw new Error('Callback must be a function.'); - } +/***/ 19185: +/***/ ((module) => { - // eslint-disable-next-line promise/prefer-await-to-then - this.lookupAsync(hostname, options).then(result => { - if (options.all) { - callback(null, result); - } else { - callback(null, result.address, result.family, result.expires, result.ttl); - } - }, callback); - } +"use strict"; - async lookupAsync(hostname, options = {}) { - if (typeof options === 'number') { - options = { - family: options - }; - } - let cached = await this.query(hostname); +/** @type {import('./gOPD')} */ +module.exports = Object.getOwnPropertyDescriptor; - if (options.family === 6) { - const filtered = cached.filter(entry => entry.family === 6); - if (options.hints & V4MAPPED) { - if ((supportsALL && options.hints & ALL) || filtered.length === 0) { - map4to6(cached); - } else { - cached = filtered; - } - } else { - cached = filtered; - } - } else if (options.family === 4) { - cached = cached.filter(entry => entry.family === 4); - } +/***/ }), - if (options.hints & ADDRCONFIG) { - const {_iface} = this; - cached = cached.filter(entry => entry.family === 6 ? _iface.has6 : _iface.has4); - } +/***/ 34709: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (cached.length === 0) { - const error = new Error(`cacheableLookup ENOTFOUND ${hostname}`); - error.code = 'ENOTFOUND'; - error.hostname = hostname; +"use strict"; - throw error; - } - if (options.all) { - return cached; - } +/** @type {import('.')} */ +var $gOPD = __nccwpck_require__(19185); - return cached[0]; +if ($gOPD) { + try { + $gOPD([], 'length'); + } catch (e) { + // IE 8 has a broken gOPD + $gOPD = null; } +} - async query(hostname) { - let cached = await this._cache.get(hostname); - - if (!cached) { - const pending = this._pending[hostname]; +module.exports = $gOPD; - if (pending) { - cached = await pending; - } else { - const newPromise = this.queryAndCache(hostname); - this._pending[hostname] = newPromise; - try { - cached = await newPromise; - } finally { - delete this._pending[hostname]; - } - } - } +/***/ }), - cached = cached.map(entry => { - return {...entry}; - }); +/***/ 49865: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return cached; - } +var crypto = __nccwpck_require__(6113); +var BigInteger = (__nccwpck_require__(85587).BigInteger); +var ECPointFp = (__nccwpck_require__(3943).ECPointFp); +var Buffer = (__nccwpck_require__(15118).Buffer); +exports.ECCurves = __nccwpck_require__(41452); - async _resolve(hostname) { - const wrap = async promise => { - try { - return await promise; - } catch (error) { - if (error.code === 'ENODATA' || error.code === 'ENOTFOUND') { - return []; - } +// zero prepad +function unstupid(hex,len) +{ + return (hex.length >= len) ? hex : unstupid("0"+hex,len); +} - throw error; - } - }; +exports.ECKey = function(curve, key, isPublic) +{ + var priv; + var c = curve(); + var n = c.getN(); + var bytes = Math.floor(n.bitLength()/8); - // ANY is unsafe as it doesn't trigger new queries in the underlying server. - const [A, AAAA] = await Promise.all([ - this._resolve4(hostname, ttl), - this._resolve6(hostname, ttl) - ].map(promise => wrap(promise))); + if(key) + { + if(isPublic) + { + var curve = c.getCurve(); +// var x = key.slice(1,bytes+1); // skip the 04 for uncompressed format +// var y = key.slice(bytes+1); +// this.P = new ECPointFp(curve, +// curve.fromBigInteger(new BigInteger(x.toString("hex"), 16)), +// curve.fromBigInteger(new BigInteger(y.toString("hex"), 16))); + this.P = curve.decodePointHex(key.toString("hex")); + }else{ + if(key.length != bytes) return false; + priv = new BigInteger(key.toString("hex"), 16); + } + }else{ + var n1 = n.subtract(BigInteger.ONE); + var r = new BigInteger(crypto.randomBytes(n.bitLength())); + priv = r.mod(n1).add(BigInteger.ONE); + this.P = c.getG().multiply(priv); + } + if(this.P) + { +// var pubhex = unstupid(this.P.getX().toBigInteger().toString(16),bytes*2)+unstupid(this.P.getY().toBigInteger().toString(16),bytes*2); +// this.PublicKey = Buffer.from("04"+pubhex,"hex"); + this.PublicKey = Buffer.from(c.getCurve().encodeCompressedPointHex(this.P),"hex"); + } + if(priv) + { + this.PrivateKey = Buffer.from(unstupid(priv.toString(16),bytes*2),"hex"); + this.deriveSharedSecret = function(key) + { + if(!key || !key.P) return false; + var S = key.P.multiply(priv); + return Buffer.from(unstupid(S.getX().toBigInteger().toString(16),bytes*2),"hex"); + } + } +} - let aTtl = 0; - let aaaaTtl = 0; - let cacheTtl = 0; - const now = Date.now(); - for (const entry of A) { - entry.family = 4; - entry.expires = now + (entry.ttl * 1000); +/***/ }), - aTtl = Math.max(aTtl, entry.ttl); - } +/***/ 3943: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - for (const entry of AAAA) { - entry.family = 6; - entry.expires = now + (entry.ttl * 1000); +// Basic Javascript Elliptic Curve implementation +// Ported loosely from BouncyCastle's Java EC code +// Only Fp curves implemented for now - aaaaTtl = Math.max(aaaaTtl, entry.ttl); - } +// Requires jsbn.js and jsbn2.js +var BigInteger = (__nccwpck_require__(85587).BigInteger) +var Barrett = BigInteger.prototype.Barrett - if (A.length > 0) { - if (AAAA.length > 0) { - cacheTtl = Math.min(aTtl, aaaaTtl); - } else { - cacheTtl = aTtl; - } - } else { - cacheTtl = aaaaTtl; - } +// ---------------- +// ECFieldElementFp - return { - entries: [ - ...A, - ...AAAA - ], - cacheTtl - }; - } +// constructor +function ECFieldElementFp(q,x) { + this.x = x; + // TODO if(x.compareTo(q) >= 0) error + this.q = q; +} - async _lookup(hostname) { - try { - const entries = await this._dnsLookup(hostname, { - all: true - }); +function feFpEquals(other) { + if(other == this) return true; + return (this.q.equals(other.q) && this.x.equals(other.x)); +} - return { - entries, - cacheTtl: 0 - }; - } catch (_) { - return { - entries: [], - cacheTtl: 0 - }; - } - } +function feFpToBigInteger() { + return this.x; +} - async _set(hostname, data, cacheTtl) { - if (this.maxTtl > 0 && cacheTtl > 0) { - cacheTtl = Math.min(cacheTtl, this.maxTtl) * 1000; - data[kExpires] = Date.now() + cacheTtl; +function feFpNegate() { + return new ECFieldElementFp(this.q, this.x.negate().mod(this.q)); +} - try { - await this._cache.set(hostname, data, cacheTtl); - } catch (error) { - this.lookupAsync = async () => { - const cacheError = new Error('Cache Error. Please recreate the CacheableLookup instance.'); - cacheError.cause = error; +function feFpAdd(b) { + return new ECFieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q)); +} - throw cacheError; - }; - } +function feFpSubtract(b) { + return new ECFieldElementFp(this.q, this.x.subtract(b.toBigInteger()).mod(this.q)); +} - if (isIterable(this._cache)) { - this._tick(cacheTtl); - } - } - } +function feFpMultiply(b) { + return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger()).mod(this.q)); +} - async queryAndCache(hostname) { - if (this._hostnamesToFallback.has(hostname)) { - return this._dnsLookup(hostname, all); - } +function feFpSquare() { + return new ECFieldElementFp(this.q, this.x.square().mod(this.q)); +} - let query = await this._resolve(hostname); +function feFpDivide(b) { + return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger().modInverse(this.q)).mod(this.q)); +} - if (query.entries.length === 0 && this._fallback) { - query = await this._lookup(hostname); +ECFieldElementFp.prototype.equals = feFpEquals; +ECFieldElementFp.prototype.toBigInteger = feFpToBigInteger; +ECFieldElementFp.prototype.negate = feFpNegate; +ECFieldElementFp.prototype.add = feFpAdd; +ECFieldElementFp.prototype.subtract = feFpSubtract; +ECFieldElementFp.prototype.multiply = feFpMultiply; +ECFieldElementFp.prototype.square = feFpSquare; +ECFieldElementFp.prototype.divide = feFpDivide; - if (query.entries.length !== 0) { - // Use `dns.lookup(...)` for that particular hostname - this._hostnamesToFallback.add(hostname); - } - } +// ---------------- +// ECPointFp - const cacheTtl = query.entries.length === 0 ? this.errorTtl : query.cacheTtl; - await this._set(hostname, query.entries, cacheTtl); +// constructor +function ECPointFp(curve,x,y,z) { + this.curve = curve; + this.x = x; + this.y = y; + // Projective coordinates: either zinv == null or z * zinv == 1 + // z and zinv are just BigIntegers, not fieldElements + if(z == null) { + this.z = BigInteger.ONE; + } + else { + this.z = z; + } + this.zinv = null; + //TODO: compression flag +} - return query.entries; - } +function pointFpGetX() { + if(this.zinv == null) { + this.zinv = this.z.modInverse(this.curve.q); + } + var r = this.x.toBigInteger().multiply(this.zinv); + this.curve.reduce(r); + return this.curve.fromBigInteger(r); +} - _tick(ms) { - const nextRemovalTime = this._nextRemovalTime; +function pointFpGetY() { + if(this.zinv == null) { + this.zinv = this.z.modInverse(this.curve.q); + } + var r = this.y.toBigInteger().multiply(this.zinv); + this.curve.reduce(r); + return this.curve.fromBigInteger(r); +} - if (!nextRemovalTime || ms < nextRemovalTime) { - clearTimeout(this._removalTimeout); +function pointFpEquals(other) { + if(other == this) return true; + if(this.isInfinity()) return other.isInfinity(); + if(other.isInfinity()) return this.isInfinity(); + var u, v; + // u = Y2 * Z1 - Y1 * Z2 + u = other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod(this.curve.q); + if(!u.equals(BigInteger.ZERO)) return false; + // v = X2 * Z1 - X1 * Z2 + v = other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod(this.curve.q); + return v.equals(BigInteger.ZERO); +} - this._nextRemovalTime = ms; +function pointFpIsInfinity() { + if((this.x == null) && (this.y == null)) return true; + return this.z.equals(BigInteger.ZERO) && !this.y.toBigInteger().equals(BigInteger.ZERO); +} - this._removalTimeout = setTimeout(() => { - this._nextRemovalTime = false; +function pointFpNegate() { + return new ECPointFp(this.curve, this.x, this.y.negate(), this.z); +} - let nextExpiry = Infinity; +function pointFpAdd(b) { + if(this.isInfinity()) return b; + if(b.isInfinity()) return this; - const now = Date.now(); + // u = Y2 * Z1 - Y1 * Z2 + var u = b.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(b.z)).mod(this.curve.q); + // v = X2 * Z1 - X1 * Z2 + var v = b.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(b.z)).mod(this.curve.q); - for (const [hostname, entries] of this._cache) { - const expires = entries[kExpires]; + if(BigInteger.ZERO.equals(v)) { + if(BigInteger.ZERO.equals(u)) { + return this.twice(); // this == b, so double + } + return this.curve.getInfinity(); // this = -b, so infinity + } - if (now >= expires) { - this._cache.delete(hostname); - } else if (expires < nextExpiry) { - nextExpiry = expires; - } - } + var THREE = new BigInteger("3"); + var x1 = this.x.toBigInteger(); + var y1 = this.y.toBigInteger(); + var x2 = b.x.toBigInteger(); + var y2 = b.y.toBigInteger(); - if (nextExpiry !== Infinity) { - this._tick(nextExpiry - now); - } - }, ms); + var v2 = v.square(); + var v3 = v2.multiply(v); + var x1v2 = x1.multiply(v2); + var zu2 = u.square().multiply(this.z); - /* istanbul ignore next: There is no `timeout.unref()` when running inside an Electron renderer */ - if (this._removalTimeout.unref) { - this._removalTimeout.unref(); - } - } - } + // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3) + var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.q); + // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3 + var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.q); + // z3 = v^3 * z1 * z2 + var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.q); - install(agent) { - verifyAgent(agent); + return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3); +} - if (kCacheableLookupCreateConnection in agent) { - throw new Error('CacheableLookup has been already installed'); - } +function pointFpTwice() { + if(this.isInfinity()) return this; + if(this.y.toBigInteger().signum() == 0) return this.curve.getInfinity(); - agent[kCacheableLookupCreateConnection] = agent.createConnection; - agent[kCacheableLookupInstance] = this; + // TODO: optimized handling of constants + var THREE = new BigInteger("3"); + var x1 = this.x.toBigInteger(); + var y1 = this.y.toBigInteger(); - agent.createConnection = (options, callback) => { - if (!('lookup' in options)) { - options.lookup = this.lookup; - } + var y1z1 = y1.multiply(this.z); + var y1sqz1 = y1z1.multiply(y1).mod(this.curve.q); + var a = this.curve.a.toBigInteger(); - return agent[kCacheableLookupCreateConnection](options, callback); - }; - } + // w = 3 * x1^2 + a * z1^2 + var w = x1.square().multiply(THREE); + if(!BigInteger.ZERO.equals(a)) { + w = w.add(this.z.square().multiply(a)); + } + w = w.mod(this.curve.q); + //this.curve.reduce(w); + // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1) + var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.q); + // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3 + var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.square().multiply(w)).mod(this.curve.q); + // z3 = 8 * (y1 * z1)^3 + var z3 = y1z1.square().multiply(y1z1).shiftLeft(3).mod(this.curve.q); - uninstall(agent) { - verifyAgent(agent); + return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3); +} - if (agent[kCacheableLookupCreateConnection]) { - if (agent[kCacheableLookupInstance] !== this) { - throw new Error('The agent is not owned by this CacheableLookup instance'); - } +// Simple NAF (Non-Adjacent Form) multiplication algorithm +// TODO: modularize the multiplication algorithm +function pointFpMultiply(k) { + if(this.isInfinity()) return this; + if(k.signum() == 0) return this.curve.getInfinity(); - agent.createConnection = agent[kCacheableLookupCreateConnection]; + var e = k; + var h = e.multiply(new BigInteger("3")); - delete agent[kCacheableLookupCreateConnection]; - delete agent[kCacheableLookupInstance]; - } - } + var neg = this.negate(); + var R = this; - updateInterfaceInfo() { - const {_iface} = this; + var i; + for(i = h.bitLength() - 2; i > 0; --i) { + R = R.twice(); - this._iface = getIfaceInfo(); + var hBit = h.testBit(i); + var eBit = e.testBit(i); - if ((_iface.has4 && !this._iface.has4) || (_iface.has6 && !this._iface.has6)) { - this._cache.clear(); - } + if (hBit != eBit) { + R = R.add(hBit ? this : neg); } + } - clear(hostname) { - if (hostname) { - this._cache.delete(hostname); - return; - } - - this._cache.clear(); - } + return R; } -module.exports = CacheableLookup; -module.exports["default"] = CacheableLookup; - - -/***/ }), - -/***/ 19227: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var bind = __nccwpck_require__(69839); - -var $apply = __nccwpck_require__(54177); -var $call = __nccwpck_require__(2808); -var $reflectApply = __nccwpck_require__(48309); - -/** @type {import('./actualApply')} */ -module.exports = $reflectApply || bind.call($call, $apply); - - -/***/ }), - -/***/ 54177: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./functionApply')} */ -module.exports = Function.prototype.apply; - +// Compute this*j + x*k (simultaneous multiplication) +function pointFpMultiplyTwo(j,x,k) { + var i; + if(j.bitLength() > k.bitLength()) + i = j.bitLength() - 1; + else + i = k.bitLength() - 1; -/***/ }), + var R = this.curve.getInfinity(); + var both = this.add(x); + while(i >= 0) { + R = R.twice(); + if(j.testBit(i)) { + if(k.testBit(i)) { + R = R.add(both); + } + else { + R = R.add(this); + } + } + else { + if(k.testBit(i)) { + R = R.add(x); + } + } + --i; + } -/***/ 2808: -/***/ ((module) => { + return R; +} -"use strict"; +ECPointFp.prototype.getX = pointFpGetX; +ECPointFp.prototype.getY = pointFpGetY; +ECPointFp.prototype.equals = pointFpEquals; +ECPointFp.prototype.isInfinity = pointFpIsInfinity; +ECPointFp.prototype.negate = pointFpNegate; +ECPointFp.prototype.add = pointFpAdd; +ECPointFp.prototype.twice = pointFpTwice; +ECPointFp.prototype.multiply = pointFpMultiply; +ECPointFp.prototype.multiplyTwo = pointFpMultiplyTwo; +// ---------------- +// ECCurveFp -/** @type {import('./functionCall')} */ -module.exports = Function.prototype.call; +// constructor +function ECCurveFp(q,a,b) { + this.q = q; + this.a = this.fromBigInteger(a); + this.b = this.fromBigInteger(b); + this.infinity = new ECPointFp(this, null, null); + this.reducer = new Barrett(this.q); +} +function curveFpGetQ() { + return this.q; +} -/***/ }), +function curveFpGetA() { + return this.a; +} -/***/ 86815: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function curveFpGetB() { + return this.b; +} -"use strict"; +function curveFpEquals(other) { + if(other == this) return true; + return(this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b)); +} +function curveFpGetInfinity() { + return this.infinity; +} -var bind = __nccwpck_require__(69839); -var $TypeError = __nccwpck_require__(6361); +function curveFpFromBigInteger(x) { + return new ECFieldElementFp(this.q, x); +} -var $call = __nccwpck_require__(2808); -var $actualApply = __nccwpck_require__(19227); +function curveReduce(x) { + this.reducer.reduce(x); +} -/** @type {(args: [Function, thisArg?: unknown, ...args: unknown[]]) => Function} TODO FIXME, find a way to use import('.') */ -module.exports = function callBindBasic(args) { - if (args.length < 1 || typeof args[0] !== 'function') { - throw new $TypeError('a function is required'); - } - return $actualApply(bind, $call, args); -}; +// for now, work with hex strings because they're easier in JS +function curveFpDecodePointHex(s) { + switch(parseInt(s.substr(0,2), 16)) { // first byte + case 0: + return this.infinity; + case 2: + case 3: + // point compression not supported yet + return null; + case 4: + case 6: + case 7: + var len = (s.length - 2) / 2; + var xHex = s.substr(2, len); + var yHex = s.substr(len+2, len); + return new ECPointFp(this, + this.fromBigInteger(new BigInteger(xHex, 16)), + this.fromBigInteger(new BigInteger(yHex, 16))); -/***/ }), + default: // unsupported + return null; + } +} -/***/ 85316: -/***/ ((module) => { +function curveFpEncodePointHex(p) { + if (p.isInfinity()) return "00"; + var xHex = p.getX().toBigInteger().toString(16); + var yHex = p.getY().toBigInteger().toString(16); + var oLen = this.getQ().toString(16).length; + if ((oLen % 2) != 0) oLen++; + while (xHex.length < oLen) { + xHex = "0" + xHex; + } + while (yHex.length < oLen) { + yHex = "0" + yHex; + } + return "04" + xHex + yHex; +} -"use strict"; +ECCurveFp.prototype.getQ = curveFpGetQ; +ECCurveFp.prototype.getA = curveFpGetA; +ECCurveFp.prototype.getB = curveFpGetB; +ECCurveFp.prototype.equals = curveFpEquals; +ECCurveFp.prototype.getInfinity = curveFpGetInfinity; +ECCurveFp.prototype.fromBigInteger = curveFpFromBigInteger; +ECCurveFp.prototype.reduce = curveReduce; +//ECCurveFp.prototype.decodePointHex = curveFpDecodePointHex; +ECCurveFp.prototype.encodePointHex = curveFpEncodePointHex; +// from: https://github.com/kaielvin/jsbn-ec-point-compression +ECCurveFp.prototype.decodePointHex = function(s) +{ + var yIsEven; + switch(parseInt(s.substr(0,2), 16)) { // first byte + case 0: + return this.infinity; + case 2: + yIsEven = false; + case 3: + if(yIsEven == undefined) yIsEven = true; + var len = s.length - 2; + var xHex = s.substr(2, len); + var x = this.fromBigInteger(new BigInteger(xHex,16)); + var alpha = x.multiply(x.square().add(this.getA())).add(this.getB()); + var beta = alpha.sqrt(); -/* eslint no-invalid-this: 1 */ + if (beta == null) throw "Invalid point compression"; -var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; -var toStr = Object.prototype.toString; -var max = Math.max; -var funcType = '[object Function]'; + var betaValue = beta.toBigInteger(); + if (betaValue.testBit(0) != yIsEven) + { + // Use the other root + beta = this.fromBigInteger(this.getQ().subtract(betaValue)); + } + return new ECPointFp(this,x,beta); + case 4: + case 6: + case 7: + var len = (s.length - 2) / 2; + var xHex = s.substr(2, len); + var yHex = s.substr(len+2, len); -var concatty = function concatty(a, b) { - var arr = []; + return new ECPointFp(this, + this.fromBigInteger(new BigInteger(xHex, 16)), + this.fromBigInteger(new BigInteger(yHex, 16))); - for (var i = 0; i < a.length; i += 1) { - arr[i] = a[i]; - } - for (var j = 0; j < b.length; j += 1) { - arr[j + a.length] = b[j]; + default: // unsupported + return null; } +} +ECCurveFp.prototype.encodeCompressedPointHex = function(p) +{ + if (p.isInfinity()) return "00"; + var xHex = p.getX().toBigInteger().toString(16); + var oLen = this.getQ().toString(16).length; + if ((oLen % 2) != 0) oLen++; + while (xHex.length < oLen) + xHex = "0" + xHex; + var yPrefix; + if(p.getY().toBigInteger().isEven()) yPrefix = "02"; + else yPrefix = "03"; - return arr; -}; + return yPrefix + xHex; +} -var slicy = function slicy(arrLike, offset) { - var arr = []; - for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { - arr[j] = arrLike[i]; - } - return arr; -}; -var joiny = function (arr, joiner) { - var str = ''; - for (var i = 0; i < arr.length; i += 1) { - str += arr[i]; - if (i + 1 < arr.length) { - str += joiner; - } - } - return str; -}; +ECFieldElementFp.prototype.getR = function() +{ + if(this.r != undefined) return this.r; -module.exports = function bind(that) { - var target = this; - if (typeof target !== 'function' || toStr.apply(target) !== funcType) { - throw new TypeError(ERROR_MESSAGE + target); + this.r = null; + var bitLength = this.q.bitLength(); + if (bitLength > 128) + { + var firstWord = this.q.shiftRight(bitLength - 64); + if (firstWord.intValue() == -1) + { + this.r = BigInteger.ONE.shiftLeft(bitLength).subtract(this.q); + } } - var args = slicy(arguments, 1); - - var bound; - var binder = function () { - if (this instanceof bound) { - var result = target.apply( - this, - concatty(args, arguments) - ); - if (Object(result) === result) { - return result; + return this.r; +} +ECFieldElementFp.prototype.modMult = function(x1,x2) +{ + return this.modReduce(x1.multiply(x2)); +} +ECFieldElementFp.prototype.modReduce = function(x) +{ + if (this.getR() != null) + { + var qLen = q.bitLength(); + while (x.bitLength() > (qLen + 1)) + { + var u = x.shiftRight(qLen); + var v = x.subtract(u.shiftLeft(qLen)); + if (!this.getR().equals(BigInteger.ONE)) + { + u = u.multiply(this.getR()); } - return this; + x = u.add(v); + } + while (x.compareTo(q) >= 0) + { + x = x.subtract(q); } - return target.apply( - that, - concatty(args, arguments) - ); - - }; - - var boundLength = max(0, target.length - args.length); - var boundArgs = []; - for (var i = 0; i < boundLength; i++) { - boundArgs[i] = '$' + i; } - - bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); - - if (target.prototype) { - var Empty = function Empty() {}; - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - Empty.prototype = null; + else + { + x = x.mod(q); } + return x; +} +ECFieldElementFp.prototype.sqrt = function() +{ + if (!this.q.testBit(0)) throw "unsupported"; - return bound; -}; - - -/***/ }), + // p mod 4 == 3 + if (this.q.testBit(1)) + { + var z = new ECFieldElementFp(this.q,this.x.modPow(this.q.shiftRight(2).add(BigInteger.ONE),this.q)); + return z.square().equals(this) ? z : null; + } -/***/ 69839: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // p mod 4 == 1 + var qMinusOne = this.q.subtract(BigInteger.ONE); -"use strict"; + var legendreExponent = qMinusOne.shiftRight(1); + if (!(this.x.modPow(legendreExponent, this.q).equals(BigInteger.ONE))) + { + return null; + } + var u = qMinusOne.shiftRight(2); + var k = u.shiftLeft(1).add(BigInteger.ONE); -var implementation = __nccwpck_require__(85316); + var Q = this.x; + var fourQ = modDouble(modDouble(Q)); -module.exports = Function.prototype.bind || implementation; + var U, V; + do + { + var P; + do + { + P = new BigInteger(this.q.bitLength(), new SecureRandom()); + } + while (P.compareTo(this.q) >= 0 + || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, this.q).equals(qMinusOne))); + var result = this.lucasSequence(P, Q, k); + U = result[0]; + V = result[1]; -/***/ }), + if (this.modMult(V, V).equals(fourQ)) + { + // Integer division by 2, mod q + if (V.testBit(0)) + { + V = V.add(q); + } -/***/ 48309: -/***/ ((module) => { + V = V.shiftRight(1); -"use strict"; + return new ECFieldElementFp(q,V); + } + } + while (U.equals(BigInteger.ONE) || U.equals(qMinusOne)); + return null; +} +ECFieldElementFp.prototype.lucasSequence = function(P,Q,k) +{ + var n = k.bitLength(); + var s = k.getLowestSetBit(); -/** @type {import('./reflectApply')} */ -module.exports = typeof Reflect !== 'undefined' && Reflect && Reflect.apply; + var Uh = BigInteger.ONE; + var Vl = BigInteger.TWO; + var Vh = P; + var Ql = BigInteger.ONE; + var Qh = BigInteger.ONE; + for (var j = n - 1; j >= s + 1; --j) + { + Ql = this.modMult(Ql, Qh); -/***/ }), + if (k.testBit(j)) + { + Qh = this.modMult(Ql, Q); + Uh = this.modMult(Uh, Vh); + Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); + Vh = this.modReduce(Vh.multiply(Vh).subtract(Qh.shiftLeft(1))); + } + else + { + Qh = Ql; + Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql)); + Vh = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); + Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1))); + } + } -/***/ 35684: -/***/ ((module) => { + Ql = this.modMult(Ql, Qh); + Qh = this.modMult(Ql, Q); + Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql)); + Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); + Ql = this.modMult(Ql, Qh); -function Caseless (dict) { - this.dict = dict || {} -} -Caseless.prototype.set = function (name, value, clobber) { - if (typeof name === 'object') { - for (var i in name) { - this.set(i, name[i], value) + for (var j = 1; j <= s; ++j) + { + Uh = this.modMult(Uh, Vl); + Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1))); + Ql = this.modMult(Ql, Ql); } - } else { - if (typeof clobber === 'undefined') clobber = true - var has = this.has(name) - if (!clobber && has) this.dict[has] = this.dict[has] + ',' + value - else this.dict[has || name] = value - return has - } -} -Caseless.prototype.has = function (name) { - var keys = Object.keys(this.dict) - , name = name.toLowerCase() - ; - for (var i=0;i { -"use strict"; +// Named EC curves -const fs = __nccwpck_require__(57147) -const path = __nccwpck_require__(71017) +// Requires ec.js, jsbn.js, and jsbn2.js +var BigInteger = (__nccwpck_require__(85587).BigInteger) +var ECCurveFp = (__nccwpck_require__(3943).ECCurveFp) -/* istanbul ignore next */ -const LCHOWN = fs.lchown ? 'lchown' : 'chown' -/* istanbul ignore next */ -const LCHOWNSYNC = fs.lchownSync ? 'lchownSync' : 'chownSync' -/* istanbul ignore next */ -const needEISDIRHandled = fs.lchown && - !process.version.match(/v1[1-9]+\./) && - !process.version.match(/v10\.[6-9]/) +// ---------------- +// X9ECParameters -const lchownSync = (path, uid, gid) => { - try { - return fs[LCHOWNSYNC](path, uid, gid) - } catch (er) { - if (er.code !== 'ENOENT') - throw er - } +// constructor +function X9ECParameters(curve,g,n,h) { + this.curve = curve; + this.g = g; + this.n = n; + this.h = h; } -/* istanbul ignore next */ -const chownSync = (path, uid, gid) => { - try { - return fs.chownSync(path, uid, gid) - } catch (er) { - if (er.code !== 'ENOENT') - throw er - } +function x9getCurve() { + return this.curve; } -/* istanbul ignore next */ -const handleEISDIR = - needEISDIRHandled ? (path, uid, gid, cb) => er => { - // Node prior to v10 had a very questionable implementation of - // fs.lchown, which would always try to call fs.open on a directory - // Fall back to fs.chown in those cases. - if (!er || er.code !== 'EISDIR') - cb(er) - else - fs.chown(path, uid, gid, cb) - } - : (_, __, ___, cb) => cb - -/* istanbul ignore next */ -const handleEISDirSync = - needEISDIRHandled ? (path, uid, gid) => { - try { - return lchownSync(path, uid, gid) - } catch (er) { - if (er.code !== 'EISDIR') - throw er - chownSync(path, uid, gid) - } - } - : (path, uid, gid) => lchownSync(path, uid, gid) - -// fs.readdir could only accept an options object as of node v6 -const nodeVersion = process.version -let readdir = (path, options, cb) => fs.readdir(path, options, cb) -let readdirSync = (path, options) => fs.readdirSync(path, options) -/* istanbul ignore next */ -if (/^v4\./.test(nodeVersion)) - readdir = (path, options, cb) => fs.readdir(path, cb) - -const chown = (cpath, uid, gid, cb) => { - fs[LCHOWN](cpath, uid, gid, handleEISDIR(cpath, uid, gid, er => { - // Skip ENOENT error - cb(er && er.code !== 'ENOENT' ? er : null) - })) +function x9getG() { + return this.g; } -const chownrKid = (p, child, uid, gid, cb) => { - if (typeof child === 'string') - return fs.lstat(path.resolve(p, child), (er, stats) => { - // Skip ENOENT error - if (er) - return cb(er.code !== 'ENOENT' ? er : null) - stats.name = child - chownrKid(p, stats, uid, gid, cb) - }) +function x9getN() { + return this.n; +} - if (child.isDirectory()) { - chownr(path.resolve(p, child.name), uid, gid, er => { - if (er) - return cb(er) - const cpath = path.resolve(p, child.name) - chown(cpath, uid, gid, cb) - }) - } else { - const cpath = path.resolve(p, child.name) - chown(cpath, uid, gid, cb) - } +function x9getH() { + return this.h; } +X9ECParameters.prototype.getCurve = x9getCurve; +X9ECParameters.prototype.getG = x9getG; +X9ECParameters.prototype.getN = x9getN; +X9ECParameters.prototype.getH = x9getH; + +// ---------------- +// SECNamedCurves -const chownr = (p, uid, gid, cb) => { - readdir(p, { withFileTypes: true }, (er, children) => { - // any error other than ENOTDIR or ENOTSUP means it's not readable, - // or doesn't exist. give up. - if (er) { - if (er.code === 'ENOENT') - return cb() - else if (er.code !== 'ENOTDIR' && er.code !== 'ENOTSUP') - return cb(er) - } - if (er || !children.length) - return chown(p, uid, gid, cb) +function fromHex(s) { return new BigInteger(s, 16); } - let len = children.length - let errState = null - const then = er => { - if (errState) - return - if (er) - return cb(errState = er) - if (-- len === 0) - return chown(p, uid, gid, cb) - } +function secp128r1() { + // p = 2^128 - 2^97 - 1 + var p = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF"); + var a = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC"); + var b = fromHex("E87579C11079F43DD824993C2CEE5ED3"); + //byte[] S = Hex.decode("000E0D4D696E6768756151750CC03A4473D03679"); + var n = fromHex("FFFFFFFE0000000075A30D1B9038A115"); + var h = BigInteger.ONE; + var curve = new ECCurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "161FF7528B899B2D0C28607CA52C5B86" + + "CF5AC8395BAFEB13C02DA292DDED7A83"); + return new X9ECParameters(curve, G, n, h); +} - children.forEach(child => chownrKid(p, child, uid, gid, then)) - }) +function secp160k1() { + // p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1 + var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73"); + var a = BigInteger.ZERO; + var b = fromHex("7"); + //byte[] S = null; + var n = fromHex("0100000000000000000001B8FA16DFAB9ACA16B6B3"); + var h = BigInteger.ONE; + var curve = new ECCurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB" + + "938CF935318FDCED6BC28286531733C3F03C4FEE"); + return new X9ECParameters(curve, G, n, h); } -const chownrKidSync = (p, child, uid, gid) => { - if (typeof child === 'string') { - try { - const stats = fs.lstatSync(path.resolve(p, child)) - stats.name = child - child = stats - } catch (er) { - if (er.code === 'ENOENT') - return - else - throw er - } - } +function secp160r1() { + // p = 2^160 - 2^31 - 1 + var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF"); + var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC"); + var b = fromHex("1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45"); + //byte[] S = Hex.decode("1053CDE42C14D696E67687561517533BF3F83345"); + var n = fromHex("0100000000000000000001F4C8F927AED3CA752257"); + var h = BigInteger.ONE; + var curve = new ECCurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "4A96B5688EF573284664698968C38BB913CBFC82" + + "23A628553168947D59DCC912042351377AC5FB32"); + return new X9ECParameters(curve, G, n, h); +} - if (child.isDirectory()) - chownrSync(path.resolve(p, child.name), uid, gid) +function secp192k1() { + // p = 2^192 - 2^32 - 2^12 - 2^8 - 2^7 - 2^6 - 2^3 - 1 + var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37"); + var a = BigInteger.ZERO; + var b = fromHex("3"); + //byte[] S = null; + var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D"); + var h = BigInteger.ONE; + var curve = new ECCurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D" + + "9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D"); + return new X9ECParameters(curve, G, n, h); +} - handleEISDirSync(path.resolve(p, child.name), uid, gid) +function secp192r1() { + // p = 2^192 - 2^64 - 1 + var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF"); + var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC"); + var b = fromHex("64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1"); + //byte[] S = Hex.decode("3045AE6FC8422F64ED579528D38120EAE12196D5"); + var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831"); + var h = BigInteger.ONE; + var curve = new ECCurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012" + + "07192B95FFC8DA78631011ED6B24CDD573F977A11E794811"); + return new X9ECParameters(curve, G, n, h); } -const chownrSync = (p, uid, gid) => { - let children - try { - children = readdirSync(p, { withFileTypes: true }) - } catch (er) { - if (er.code === 'ENOENT') - return - else if (er.code === 'ENOTDIR' || er.code === 'ENOTSUP') - return handleEISDirSync(p, uid, gid) - else - throw er - } +function secp224r1() { + // p = 2^224 - 2^96 + 1 + var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001"); + var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE"); + var b = fromHex("B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4"); + //byte[] S = Hex.decode("BD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5"); + var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D"); + var h = BigInteger.ONE; + var curve = new ECCurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21" + + "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34"); + return new X9ECParameters(curve, G, n, h); +} - if (children && children.length) - children.forEach(child => chownrKidSync(p, child, uid, gid)) +function secp256r1() { + // p = 2^224 (2^32 - 1) + 2^192 + 2^96 - 1 + var p = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF"); + var a = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC"); + var b = fromHex("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B"); + //byte[] S = Hex.decode("C49D360886E704936A6678E1139D26B7819F7E90"); + var n = fromHex("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551"); + var h = BigInteger.ONE; + var curve = new ECCurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296" + + "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5"); + return new X9ECParameters(curve, G, n, h); +} - return handleEISDirSync(p, uid, gid) +// TODO: make this into a proper hashtable +function getSECCurveByName(name) { + if(name == "secp128r1") return secp128r1(); + if(name == "secp160k1") return secp160k1(); + if(name == "secp160r1") return secp160r1(); + if(name == "secp192k1") return secp192k1(); + if(name == "secp192r1") return secp192r1(); + if(name == "secp224r1") return secp224r1(); + if(name == "secp256r1") return secp256r1(); + return null; } -module.exports = chownr -chownr.sync = chownrSync +module.exports = { + "secp128r1":secp128r1, + "secp160k1":secp160k1, + "secp160r1":secp160r1, + "secp192k1":secp192k1, + "secp192r1":secp192r1, + "secp224r1":secp224r1, + "secp256r1":secp256r1 +} /***/ }), -/***/ 27972: +/***/ 81205: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +var once = __nccwpck_require__(1223); -const os = __nccwpck_require__(22037); +var noop = function() {}; -const extractPathRegex = /\s+at.*(?:\(|\s)(.*)\)?/; -const pathRegex = /^(?:(?:(?:node|(?:internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)\.js:\d+:\d+)|native)/; -const homeDir = typeof os.homedir === 'undefined' ? '' : os.homedir(); +var isRequest = function(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +}; -module.exports = (stack, options) => { - options = Object.assign({pretty: false}, options); +var isChildProcess = function(stream) { + return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 +}; - return stack.replace(/\\/g, '/') - .split('\n') - .filter(line => { - const pathMatches = line.match(extractPathRegex); - if (pathMatches === null || !pathMatches[1]) { - return true; - } +var eos = function(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; - const match = pathMatches[1]; + callback = once(callback || noop); - // Electron - if ( - match.includes('.app/Contents/Resources/electron.asar') || - match.includes('.app/Contents/Resources/default_app.asar') - ) { - return false; - } + var ws = stream._writableState; + var rs = stream._readableState; + var readable = opts.readable || (opts.readable !== false && stream.readable); + var writable = opts.writable || (opts.writable !== false && stream.writable); + var cancelled = false; - return !pathRegex.test(match); - }) - .filter(line => line.trim() !== '') - .map(line => { - if (options.pretty) { - return line.replace(extractPathRegex, (m, p1) => m.replace(p1, p1.replace(homeDir, '~'))); - } + var onlegacyfinish = function() { + if (!stream.writable) onfinish(); + }; - return line; - }) - .join('\n'); -}; + var onfinish = function() { + writable = false; + if (!readable) callback.call(stream); + }; + var onend = function() { + readable = false; + if (!writable) callback.call(stream); + }; -/***/ }), + var onexit = function(exitCode) { + callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); + }; -/***/ 81312: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var onerror = function(err) { + callback.call(stream, err); + }; -"use strict"; + var onclose = function() { + process.nextTick(onclosenexttick); + }; + var onclosenexttick = function() { + if (cancelled) return; + if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close')); + if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close')); + }; -const PassThrough = (__nccwpck_require__(12781).PassThrough); -const mimicResponse = __nccwpck_require__(42610); + var onrequest = function() { + stream.req.on('finish', onfinish); + }; -const cloneResponse = response => { - if (!(response && response.pipe)) { - throw new TypeError('Parameter `response` must be a response stream.'); + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest(); + else stream.on('request', onrequest); + } else if (writable && !ws) { // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); } - const clone = new PassThrough(); - mimicResponse(response, clone); + if (isChildProcess(stream)) stream.on('exit', onexit); - return response.pipe(clone); + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + + return function() { + cancelled = true; + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('exit', onexit); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; }; -module.exports = cloneResponse; +module.exports = eos; /***/ }), -/***/ 85443: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 6123: +/***/ ((module) => { -var util = __nccwpck_require__(73837); -var Stream = (__nccwpck_require__(12781).Stream); -var DelayedStream = __nccwpck_require__(18611); +"use strict"; -module.exports = CombinedStream; -function CombinedStream() { - this.writable = false; - this.readable = true; - this.dataSize = 0; - this.maxDataSize = 2 * 1024 * 1024; - this.pauseStreams = true; - this._released = false; - this._streams = []; - this._currentStream = null; - this._insideLoop = false; - this._pendingNext = false; +/** @type {import('.')} */ +var $defineProperty = Object.defineProperty || false; +if ($defineProperty) { + try { + $defineProperty({}, 'a', { value: 1 }); + } catch (e) { + // IE 8 has a broken defineProperty + $defineProperty = false; + } } -util.inherits(CombinedStream, Stream); - -CombinedStream.create = function(options) { - var combinedStream = new this(); - - options = options || {}; - for (var option in options) { - combinedStream[option] = options[option]; - } - - return combinedStream; -}; - -CombinedStream.isStreamLike = function(stream) { - return (typeof stream !== 'function') - && (typeof stream !== 'string') - && (typeof stream !== 'boolean') - && (typeof stream !== 'number') - && (!Buffer.isBuffer(stream)); -}; - -CombinedStream.prototype.append = function(stream) { - var isStreamLike = CombinedStream.isStreamLike(stream); - - if (isStreamLike) { - if (!(stream instanceof DelayedStream)) { - var newStream = DelayedStream.create(stream, { - maxDataSize: Infinity, - pauseStream: this.pauseStreams, - }); - stream.on('data', this._checkDataSize.bind(this)); - stream = newStream; - } - - this._handleErrors(stream); - if (this.pauseStreams) { - stream.pause(); - } - } +module.exports = $defineProperty; - this._streams.push(stream); - return this; -}; -CombinedStream.prototype.pipe = function(dest, options) { - Stream.prototype.pipe.call(this, dest, options); - this.resume(); - return dest; -}; +/***/ }), -CombinedStream.prototype._getNext = function() { - this._currentStream = null; +/***/ 91933: +/***/ ((module) => { - if (this._insideLoop) { - this._pendingNext = true; - return; // defer call - } +"use strict"; - this._insideLoop = true; - try { - do { - this._pendingNext = false; - this._realGetNext(); - } while (this._pendingNext); - } finally { - this._insideLoop = false; - } -}; -CombinedStream.prototype._realGetNext = function() { - var stream = this._streams.shift(); +/** @type {import('./eval')} */ +module.exports = EvalError; - if (typeof stream == 'undefined') { - this.end(); - return; - } +/***/ }), - if (typeof stream !== 'function') { - this._pipeNext(stream); - return; - } +/***/ 28015: +/***/ ((module) => { - var getStream = stream; - getStream(function(stream) { - var isStreamLike = CombinedStream.isStreamLike(stream); - if (isStreamLike) { - stream.on('data', this._checkDataSize.bind(this)); - this._handleErrors(stream); - } +"use strict"; - this._pipeNext(stream); - }.bind(this)); -}; -CombinedStream.prototype._pipeNext = function(stream) { - this._currentStream = stream; +/** @type {import('.')} */ +module.exports = Error; - var isStreamLike = CombinedStream.isStreamLike(stream); - if (isStreamLike) { - stream.on('end', this._getNext.bind(this)); - stream.pipe(this, {end: false}); - return; - } - var value = stream; - this.write(value); - this._getNext(); -}; +/***/ }), -CombinedStream.prototype._handleErrors = function(stream) { - var self = this; - stream.on('error', function(err) { - self._emitError(err); - }); -}; +/***/ 54415: +/***/ ((module) => { -CombinedStream.prototype.write = function(data) { - this.emit('data', data); -}; +"use strict"; -CombinedStream.prototype.pause = function() { - if (!this.pauseStreams) { - return; - } - if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause(); - this.emit('pause'); -}; +/** @type {import('./range')} */ +module.exports = RangeError; -CombinedStream.prototype.resume = function() { - if (!this._released) { - this._released = true; - this.writable = true; - this._getNext(); - } - if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume(); - this.emit('resume'); -}; +/***/ }), -CombinedStream.prototype.end = function() { - this._reset(); - this.emit('end'); -}; +/***/ 46279: +/***/ ((module) => { -CombinedStream.prototype.destroy = function() { - this._reset(); - this.emit('close'); -}; +"use strict"; -CombinedStream.prototype._reset = function() { - this.writable = false; - this._streams = []; - this._currentStream = null; -}; -CombinedStream.prototype._checkDataSize = function() { - this._updateDataSize(); - if (this.dataSize <= this.maxDataSize) { - return; - } +/** @type {import('./ref')} */ +module.exports = ReferenceError; - var message = - 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'; - this._emitError(new Error(message)); -}; -CombinedStream.prototype._updateDataSize = function() { - this.dataSize = 0; +/***/ }), - var self = this; - this._streams.forEach(function(stream) { - if (!stream.dataSize) { - return; - } +/***/ 75474: +/***/ ((module) => { - self.dataSize += stream.dataSize; - }); +"use strict"; - if (this._currentStream && this._currentStream.dataSize) { - this.dataSize += this._currentStream.dataSize; - } -}; -CombinedStream.prototype._emitError = function(err) { - this._reset(); - this.emit('error', err); -}; +/** @type {import('./syntax')} */ +module.exports = SyntaxError; /***/ }), -/***/ 17044: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 6361: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.action = void 0; -const commander = __nccwpck_require__(86987); -function action() { - return (target, propertyKey, descriptor) => { - commander.action(target[propertyKey]); - }; -} -exports.action = action; -//# sourceMappingURL=action.decorator.js.map + +/** @type {import('./type')} */ +module.exports = TypeError; + /***/ }), -/***/ 71303: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 5065: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.alias = void 0; -const program = __nccwpck_require__(86987); -function alias(text) { - return (target) => { - program.usage(text); - }; -} -exports.alias = alias; -//# sourceMappingURL=alias.decorator.js.map + +/** @type {import('./uri')} */ +module.exports = URIError; + /***/ }), -/***/ 55508: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 78308: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.variadicArg = exports.requiredArg = exports.optionalArg = void 0; -const metadata_1 = __nccwpck_require__(104); -const models_1 = __nccwpck_require__(84908); -const utils_1 = __nccwpck_require__(66725); -/** - * Parameter decorator used in subcommand function to denote an optional argument. - */ -function optionalArg(name) { - return (target, propertyKey, parameterIndex) => { - const args = (0, utils_1.decorateIfNot)(metadata_1.ArgsMetadata, [], target, propertyKey); - args.unshift(new models_1.OptionalArg(name, parameterIndex)); - }; -} -exports.optionalArg = optionalArg; -/** - * Parameter decorator used in subcommand function to denote a required argument. - */ -function requiredArg(name) { - return (target, propertyKey, parameterIndex) => { - const args = (0, utils_1.decorateIfNot)(metadata_1.ArgsMetadata, [], target, propertyKey); - args.unshift(new models_1.RequiredArg(name, parameterIndex)); - }; -} -exports.requiredArg = requiredArg; -/** - * Parameter decorator used in subcommand function to denote variadic arguments. - */ -function variadicArg(name) { - return (target, propertyKey, parameterIndex) => { - const args = (0, utils_1.decorateIfNot)(metadata_1.ArgsMetadata, [], target, propertyKey); - args.unshift(new models_1.VariadicArg(name, parameterIndex)); - }; -} -exports.variadicArg = variadicArg; -//# sourceMappingURL=arg.decorator.js.map + +/** @type {import('.')} */ +module.exports = Object; + /***/ }), -/***/ 71196: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 11770: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.args = void 0; -const commander = __nccwpck_require__(86987); -function args() { - return (target, propertyKey, parameterIndex) => { - commander - .option(propertyKey) - .action(target[propertyKey]); - }; -} -exports.args = args; -//# sourceMappingURL=arguments.decorator.js.map -/***/ }), +var GetIntrinsic = __nccwpck_require__(99276); -/***/ 69904: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); -"use strict"; +var hasToStringTag = __nccwpck_require__(50499)(); +var hasOwn = __nccwpck_require__(62157); +var $TypeError = __nccwpck_require__(6361); + +var toStringTag = hasToStringTag ? Symbol.toStringTag : null; + +/** @type {import('.')} */ +module.exports = function setToStringTag(object, value) { + var overrideIfSet = arguments.length > 2 && !!arguments[2] && arguments[2].force; + var nonConfigurable = arguments.length > 2 && !!arguments[2] && arguments[2].nonConfigurable; + if ( + (typeof overrideIfSet !== 'undefined' && typeof overrideIfSet !== 'boolean') + || (typeof nonConfigurable !== 'undefined' && typeof nonConfigurable !== 'boolean') + ) { + throw new $TypeError('if provided, the `overrideIfSet` and `nonConfigurable` options must be booleans'); + } + if (toStringTag && (overrideIfSet || !hasOwn(object, toStringTag))) { + if ($defineProperty) { + $defineProperty(object, toStringTag, { + configurable: !nonConfigurable, + enumerable: false, + value: value, + writable: false + }); + } else { + object[toStringTag] = value; // eslint-disable-line no-param-reassign + } + } +}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.commandOption = void 0; -const metadata_1 = __nccwpck_require__(104); -const utils_1 = __nccwpck_require__(66725); -function commandOption(...args) { - return ((target, propertyKey, descriptor) => { - args[0] = args[0] || `--${String(propertyKey)}`; - (0, utils_1.decorateIfNot)(metadata_1.CommandOptionsMetadata, [], target, propertyKey); - const options = Reflect.getMetadata(metadata_1.CommandOptionsMetadata, target, propertyKey); - options.push(args); - }); -} -exports.commandOption = commandOption; -//# sourceMappingURL=command-option.decorator.js.map /***/ }), -/***/ 1442: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 53325: +/***/ ((module) => { "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + +/* eslint no-invalid-this: 1 */ + +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var toStr = Object.prototype.toString; +var max = Math.max; +var funcType = '[object Function]'; + +var concatty = function concatty(a, b) { + var arr = []; + + for (var i = 0; i < a.length; i += 1) { + arr[i] = a[i]; + } + for (var j = 0; j < b.length; j += 1) { + arr[j + a.length] = b[j]; + } + + return arr; }; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.command = void 0; -const commander = __nccwpck_require__(86987); -const helpers_1 = __nccwpck_require__(69882); -const metadata_1 = __nccwpck_require__(104); -function command() { - return (target, propertyKey, descriptor) => { - try { - const cmd = (0, helpers_1.prepareSubcommand)(target, propertyKey); - let chain = commander.command(cmd); - if (Reflect.hasMetadata(metadata_1.CommandOptionsMetadata, target, propertyKey)) { - const options = Reflect.getMetadata(metadata_1.CommandOptionsMetadata, target, propertyKey); - chain = options.reduce((prev, opt) => { - const [arg1, arg2, arg3, arg4] = opt; - return chain.option(arg1, arg2, arg3, arg4); - }, chain); - } - chain.action((...args) => __awaiter(this, void 0, void 0, function* () { - const context = args[args.length - 1]; - const cmdArgs = args.slice(0, args.length - 1); - try { - const result = target[propertyKey].apply(context, cmdArgs); - if (result instanceof Promise) { - yield result; - } - } - catch (_a) { - process.exit(1); - } - finally { - process.exit(0); - } - })); + +var slicy = function slicy(arrLike, offset) { + var arr = []; + for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { + arr[j] = arrLike[i]; + } + return arr; +}; + +var joiny = function (arr, joiner) { + var str = ''; + for (var i = 0; i < arr.length; i += 1) { + str += arr[i]; + if (i + 1 < arr.length) { + str += joiner; } - catch (e) { - console.error(e.message); - process.exit(1); + } + return str; +}; + +module.exports = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.apply(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slicy(arguments, 1); + + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + concatty(args, arguments) + ); + if (Object(result) === result) { + return result; + } + return this; } + return target.apply( + that, + concatty(args, arguments) + ); + }; -} -exports.command = command; -//# sourceMappingURL=command.decorator.js.map -/***/ }), + var boundLength = max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs[i] = '$' + i; + } -/***/ 14432: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); -"use strict"; + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + + return bound; +}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.description = void 0; -const program = __nccwpck_require__(86987); -function description(text) { - return (target) => { - program.description(text); - }; -} -exports.description = description; -//# sourceMappingURL=description.decorator.js.map /***/ }), -/***/ 90154: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 97257: +/***/ ((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; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (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 })); -__exportStar(__nccwpck_require__(104), exports); -__exportStar(__nccwpck_require__(17044), exports); -__exportStar(__nccwpck_require__(71303), exports); -__exportStar(__nccwpck_require__(55508), exports); -__exportStar(__nccwpck_require__(71196), exports); -__exportStar(__nccwpck_require__(69904), exports); -__exportStar(__nccwpck_require__(1442), exports); -__exportStar(__nccwpck_require__(14432), exports); -__exportStar(__nccwpck_require__(98166), exports); -__exportStar(__nccwpck_require__(42991), exports); -__exportStar(__nccwpck_require__(3813), exports); -__exportStar(__nccwpck_require__(84768), exports); -__exportStar(__nccwpck_require__(98162), exports); -//# sourceMappingURL=index.js.map + +var implementation = __nccwpck_require__(53325); + +module.exports = Function.prototype.bind || implementation; + /***/ }), -/***/ 98166: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 99276: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.on = void 0; -const commander = __nccwpck_require__(86987); -function on(event, handler) { - return (target, propertyKey, descriptor) => { - commander.on(event, handler); - }; -} -exports.on = on; -//# sourceMappingURL=on.decorator.js.map -/***/ }), +var undefined; -/***/ 42991: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +var $Object = __nccwpck_require__(78308); -"use strict"; +var $Error = __nccwpck_require__(28015); +var $EvalError = __nccwpck_require__(91933); +var $RangeError = __nccwpck_require__(54415); +var $ReferenceError = __nccwpck_require__(46279); +var $SyntaxError = __nccwpck_require__(75474); +var $TypeError = __nccwpck_require__(6361); +var $URIError = __nccwpck_require__(5065); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.option = void 0; -const metadata_1 = __nccwpck_require__(104); -const models_1 = __nccwpck_require__(84908); -const utils_1 = __nccwpck_require__(66725); -function option(...args) { - return ((target, propertyKey) => { - args[0] = args[0] || `--${String(propertyKey)}`; - (0, utils_1.decorateIfNot)(metadata_1.OptionsMetadata, [], target, propertyKey); - const options = Reflect.getMetadata(metadata_1.OptionsMetadata, target, propertyKey); - options.push(new models_1.Option(propertyKey, args)); - }); -} -exports.option = option; -//# sourceMappingURL=option.decorator.js.map +var abs = __nccwpck_require__(19775); +var floor = __nccwpck_require__(60924); +var max = __nccwpck_require__(52419); +var min = __nccwpck_require__(73373); +var pow = __nccwpck_require__(78029); +var round = __nccwpck_require__(59396); +var sign = __nccwpck_require__(39091); -/***/ }), +var $Function = Function; -/***/ 3813: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// eslint-disable-next-line consistent-return +var getEvalledConstructor = function (expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); + } catch (e) {} +}; -"use strict"; +var $gOPD = __nccwpck_require__(64868); +var $defineProperty = __nccwpck_require__(6123); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.program = void 0; -const commander = __nccwpck_require__(86987); -const helpers_1 = __nccwpck_require__(69882); -const metadata_1 = __nccwpck_require__(104); -let instances = 0; -function program() { - instances += 1; - if (instances > 1) { - throw new Error('Only one instance of @program is permitted.'); - } - return function (constructor) { - const mixin = class extends constructor { - constructor(...args) { - super(...args); - if (!this.run) { - console.error('Program class must define a run() method.'); - process.exit(1); - } - const cmd = (0, helpers_1.prepareCommand)(this, 'run'); - if (cmd) { - commander.command(cmd); - } - const options = Object.keys(this).reduce((list, prop) => { - if (Reflect.hasMetadata(metadata_1.OptionsMetadata, this, prop)) { - const metadata = Reflect.getMetadata(metadata_1.OptionsMetadata, this, prop); - list.push(metadata); - } - return list; - }, []); - const chainAfterOptions = options - .reduce((prev, option) => { - return prev.option.apply(prev, option[0].args); - }, commander); - commander.parse(process.argv); - if (this.run) { - this.run.apply(commander, (0, helpers_1.injectArgs)(commander, this, 'run')); - } - } - }; - (0, helpers_1.initCommander)(constructor); - return mixin; - }; -} -exports.program = program; -function prepareProgram(target) { - let argList = ''; - if (Reflect.hasMetadata(metadata_1.OptionsMetadata, target)) { - const args = Reflect.getMetadata(metadata_1.OptionsMetadata, target); - argList = args - .map((arg) => { - return arg.toString(); - }) - .join(' ') - .replace(/^(.)/, ' $1'); - } - return `${argList}`; -} -//# sourceMappingURL=program.decorator.js.map +var throwTypeError = function () { + throw new $TypeError(); +}; +var ThrowTypeError = $gOPD + ? (function () { + try { + // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties + arguments.callee; // IE 8 does not throw here + return throwTypeError; + } catch (calleeThrows) { + try { + // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') + return $gOPD(arguments, 'callee').get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }()) + : throwTypeError; -/***/ }), +var hasSymbols = __nccwpck_require__(36546)(); -/***/ 84768: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +var getProto = __nccwpck_require__(13592); +var $ObjectGPO = __nccwpck_require__(5045); +var $ReflectGPO = __nccwpck_require__(78859); -"use strict"; +var $apply = __nccwpck_require__(54177); +var $call = __nccwpck_require__(2808); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.usage = void 0; -const commander = __nccwpck_require__(86987); -function usage(text) { - return (target) => { - commander.usage(text); - }; -} -exports.usage = usage; -//# sourceMappingURL=usage.decorator.js.map +var needsEval = {}; -/***/ }), +var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array); -/***/ 98162: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +var INTRINSICS = { + __proto__: null, + '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, + '%Array%': Array, + '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, + '%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined, + '%AsyncFromSyncIteratorPrototype%': undefined, + '%AsyncFunction%': needsEval, + '%AsyncGenerator%': needsEval, + '%AsyncGeneratorFunction%': needsEval, + '%AsyncIteratorPrototype%': needsEval, + '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, + '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, + '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array, + '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array, + '%Boolean%': Boolean, + '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, + '%Date%': Date, + '%decodeURI%': decodeURI, + '%decodeURIComponent%': decodeURIComponent, + '%encodeURI%': encodeURI, + '%encodeURIComponent%': encodeURIComponent, + '%Error%': $Error, + '%eval%': eval, // eslint-disable-line no-eval + '%EvalError%': $EvalError, + '%Float16Array%': typeof Float16Array === 'undefined' ? undefined : Float16Array, + '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, + '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, + '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, + '%Function%': $Function, + '%GeneratorFunction%': needsEval, + '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, + '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, + '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, + '%isFinite%': isFinite, + '%isNaN%': isNaN, + '%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined, + '%JSON%': typeof JSON === 'object' ? JSON : undefined, + '%Map%': typeof Map === 'undefined' ? undefined : Map, + '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()), + '%Math%': Math, + '%Number%': Number, + '%Object%': $Object, + '%Object.getOwnPropertyDescriptor%': $gOPD, + '%parseFloat%': parseFloat, + '%parseInt%': parseInt, + '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, + '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, + '%RangeError%': $RangeError, + '%ReferenceError%': $ReferenceError, + '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, + '%RegExp%': RegExp, + '%Set%': typeof Set === 'undefined' ? undefined : Set, + '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()), + '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, + '%String%': String, + '%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined, + '%Symbol%': hasSymbols ? Symbol : undefined, + '%SyntaxError%': $SyntaxError, + '%ThrowTypeError%': ThrowTypeError, + '%TypedArray%': TypedArray, + '%TypeError%': $TypeError, + '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, + '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, + '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, + '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, + '%URIError%': $URIError, + '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, + '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, + '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet, -"use strict"; + '%Function.prototype.call%': $call, + '%Function.prototype.apply%': $apply, + '%Object.defineProperty%': $defineProperty, + '%Object.getPrototypeOf%': $ObjectGPO, + '%Math.abs%': abs, + '%Math.floor%': floor, + '%Math.max%': max, + '%Math.min%': min, + '%Math.pow%': pow, + '%Math.round%': round, + '%Math.sign%': sign, + '%Reflect.getPrototypeOf%': $ReflectGPO +}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.version = void 0; -const helpers_1 = __nccwpck_require__(69882); -const metadata_1 = __nccwpck_require__(104); -function version(text) { - return (target) => { - (0, helpers_1.initCommander)(target); - const program = Reflect.getMetadata(metadata_1.ProgramMetadata, target); - program.version(text); - }; +if (getProto) { + try { + null.error; // eslint-disable-line no-unused-expressions + } catch (e) { + // https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229 + var errorProto = getProto(getProto(e)); + INTRINSICS['%Error.prototype%'] = errorProto; + } } -exports.version = version; -//# sourceMappingURL=version.decorator.js.map -/***/ }), +var doEval = function doEval(name) { + var value; + if (name === '%AsyncFunction%') { + value = getEvalledConstructor('async function () {}'); + } else if (name === '%GeneratorFunction%') { + value = getEvalledConstructor('function* () {}'); + } else if (name === '%AsyncGeneratorFunction%') { + value = getEvalledConstructor('async function* () {}'); + } else if (name === '%AsyncGenerator%') { + var fn = doEval('%AsyncGeneratorFunction%'); + if (fn) { + value = fn.prototype; + } + } else if (name === '%AsyncIteratorPrototype%') { + var gen = doEval('%AsyncGenerator%'); + if (gen && getProto) { + value = getProto(gen.prototype); + } + } -/***/ 69882: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + INTRINSICS[name] = value; -"use strict"; + return value; +}; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (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); +var LEGACY_ALIASES = { + __proto__: null, + '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], + '%ArrayPrototype%': ['Array', 'prototype'], + '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], + '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], + '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], + '%ArrayProto_values%': ['Array', 'prototype', 'values'], + '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], + '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], + '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], + '%BooleanPrototype%': ['Boolean', 'prototype'], + '%DataViewPrototype%': ['DataView', 'prototype'], + '%DatePrototype%': ['Date', 'prototype'], + '%ErrorPrototype%': ['Error', 'prototype'], + '%EvalErrorPrototype%': ['EvalError', 'prototype'], + '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], + '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], + '%FunctionPrototype%': ['Function', 'prototype'], + '%Generator%': ['GeneratorFunction', 'prototype'], + '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], + '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], + '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], + '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], + '%JSONParse%': ['JSON', 'parse'], + '%JSONStringify%': ['JSON', 'stringify'], + '%MapPrototype%': ['Map', 'prototype'], + '%NumberPrototype%': ['Number', 'prototype'], + '%ObjectPrototype%': ['Object', 'prototype'], + '%ObjProto_toString%': ['Object', 'prototype', 'toString'], + '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], + '%PromisePrototype%': ['Promise', 'prototype'], + '%PromiseProto_then%': ['Promise', 'prototype', 'then'], + '%Promise_all%': ['Promise', 'all'], + '%Promise_reject%': ['Promise', 'reject'], + '%Promise_resolve%': ['Promise', 'resolve'], + '%RangeErrorPrototype%': ['RangeError', 'prototype'], + '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], + '%RegExpPrototype%': ['RegExp', 'prototype'], + '%SetPrototype%': ['Set', 'prototype'], + '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], + '%StringPrototype%': ['String', 'prototype'], + '%SymbolPrototype%': ['Symbol', 'prototype'], + '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], + '%TypedArrayPrototype%': ['TypedArray', 'prototype'], + '%TypeErrorPrototype%': ['TypeError', 'prototype'], + '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], + '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], + '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], + '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], + '%URIErrorPrototype%': ['URIError', 'prototype'], + '%WeakMapPrototype%': ['WeakMap', 'prototype'], + '%WeakSetPrototype%': ['WeakSet', 'prototype'] }; -Object.defineProperty(exports, "__esModule", ({ value: true })); -__exportStar(__nccwpck_require__(65339), exports); -__exportStar(__nccwpck_require__(70), exports); -__exportStar(__nccwpck_require__(11413), exports); -//# sourceMappingURL=index.js.map -/***/ }), +var bind = __nccwpck_require__(97257); +var hasOwn = __nccwpck_require__(62157); +var $concat = bind.call($call, Array.prototype.concat); +var $spliceApply = bind.call($apply, Array.prototype.splice); +var $replace = bind.call($call, String.prototype.replace); +var $strSlice = bind.call($call, String.prototype.slice); +var $exec = bind.call($call, RegExp.prototype.exec); -/***/ 65339: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ +var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; +var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ +var stringToPath = function stringToPath(string) { + var first = $strSlice(string, 0, 1); + var last = $strSlice(string, -1); + if (first === '%' && last !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); + } else if (last === '%' && first !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); + } + var result = []; + $replace(string, rePropName, function (match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; + }); + return result; +}; +/* end adaptation */ -"use strict"; +var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = '%' + alias[0] + '%'; + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.initCommander = void 0; -const commander = __nccwpck_require__(86987); -const metadata_1 = __nccwpck_require__(104); -function initCommander(target) { - if (!Reflect.hasMetadata(metadata_1.ProgramMetadata, target)) { - const decorator = Reflect.metadata(metadata_1.ProgramMetadata, commander); - Reflect.decorate([decorator], target); - } -} -exports.initCommander = initCommander; -//# sourceMappingURL=init-commander.js.map + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === 'undefined' && !allowMissing) { + throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); + } -/***/ }), + return { + alias: alias, + name: intrinsicName, + value: value + }; + } -/***/ 70: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); +}; -"use strict"; +module.exports = function GetIntrinsic(name, allowMissing) { + if (typeof name !== 'string' || name.length === 0) { + throw new $TypeError('intrinsic name must be a non-empty string'); + } + if (arguments.length > 1 && typeof allowMissing !== 'boolean') { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.injectArgs = void 0; -const metadata_1 = __nccwpck_require__(104); -const index_1 = __nccwpck_require__(84908); -function injectArgs(program, target, propertyKey) { - if (Reflect.hasMetadata(metadata_1.ArgsMetadata, target, propertyKey)) { - const args = Reflect.getMetadata(metadata_1.ArgsMetadata, target, propertyKey); - const predicate = (arg) => arg instanceof index_1.VariadicArg; - const variadic = args.find(predicate); - if (variadic && (args.findIndex(predicate) !== (args.length - 1))) { - throw new TypeError(`Variadic argument must be specified last the argument list of the ${String(propertyKey)}() function.`); - } - const argv = []; - let index = 0; - for (let i = 0; i < args.length; i += 1) { - if (args.find(arg => arg.index === i)) { - argv.push(program.args[index]); - index += 1; - } - else { - argv.push(undefined); - } - } - return argv; - } -} -exports.injectArgs = injectArgs; -//# sourceMappingURL=inject-args.js.map + if ($exec(/^%?[^%]*%?$/, name) === null) { + throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); + } + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; -/***/ }), + var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; -/***/ 11413: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } -"use strict"; + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ( + ( + (first === '"' || first === "'" || first === '`') + || (last === '"' || last === "'" || last === '`') + ) + && first !== last + ) { + throw new $SyntaxError('property names with quotes must have matching quotes'); + } + if (part === 'constructor' || !isOwn) { + skipFurtherCaching = true; + } + + intrinsicBaseName += '.' + part; + intrinsicRealName = '%' + intrinsicBaseName + '%'; + + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); + } + return void undefined; + } + if ($gOPD && (i + 1) >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + + // By convention, when a data property is converted to an accessor + // property to emulate a data property that does not suffer from + // the override mistake, that accessor's getter is marked with + // an `originalValue` property. Here, when we detect this, we + // uphold the illusion by pretending to see that original data + // property, i.e., returning the value rather than the getter + // itself. + if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn(value, part); + value = value[part]; + } + + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; +}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.prepareSubcommand = exports.prepareCommand = void 0; -const metadata_1 = __nccwpck_require__(104); -const index_1 = __nccwpck_require__(84908); -function prepareCommand(target, propertyKey) { - let argList = ''; - if (Reflect.hasMetadata(metadata_1.ArgsMetadata, target, propertyKey)) { - const args = Reflect.getMetadata(metadata_1.ArgsMetadata, target, propertyKey); - const predicate = (arg) => arg instanceof index_1.VariadicArg; - const variadic = args.find(predicate); - if (variadic && (args.findIndex(predicate) !== (args.length - 1))) { - throw new TypeError(`Variadic argument must be specified last the argument list of the ${String(propertyKey)}() function.`); - } - argList = args - .map((arg) => { - return arg.toString(); - }) - .join(' ') - .replace(/^(.)/, '$1'); - } - return `${argList}`; -} -exports.prepareCommand = prepareCommand; -function prepareSubcommand(target, propertyKey) { - const argList = prepareCommand(target, propertyKey); - return `${String(propertyKey)} ${argList}`; -} -exports.prepareSubcommand = prepareSubcommand; -//# sourceMappingURL=prepare-command.js.map /***/ }), -/***/ 40451: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 36546: +/***/ ((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; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (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); + +var origSymbol = typeof Symbol !== 'undefined' && Symbol; +var hasSymbolSham = __nccwpck_require__(85968); + +/** @type {import('.')} */ +module.exports = function hasNativeSymbols() { + if (typeof origSymbol !== 'function') { return false; } + if (typeof Symbol !== 'function') { return false; } + if (typeof origSymbol('foo') !== 'symbol') { return false; } + if (typeof Symbol('bar') !== 'symbol') { return false; } + + return hasSymbolSham(); }; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Option = exports.Command = void 0; -__nccwpck_require__(29977); -var commander_1 = __nccwpck_require__(86987); -Object.defineProperty(exports, "Command", ({ enumerable: true, get: function () { return commander_1.Command; } })); -Object.defineProperty(exports, "Option", ({ enumerable: true, get: function () { return commander_1.Option; } })); -__exportStar(__nccwpck_require__(90154), exports); -//# sourceMappingURL=index.js.map + /***/ }), -/***/ 104: -/***/ ((__unused_webpack_module, exports) => { +/***/ 85968: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SubcommandMetadata = exports.ProgramMetadata = exports.OptionsMetadata = exports.CommandOptionsMetadata = exports.ArgsMetadata = void 0; -exports.ArgsMetadata = Symbol('ArgsMetadata'); -exports.CommandOptionsMetadata = Symbol('CommandOptionsMetadata'); -exports.OptionsMetadata = Symbol('OptionsMetadata'); -exports.ProgramMetadata = Symbol('ProgramMetadata'); -exports.SubcommandMetadata = Symbol('SubcommandMetadata'); -//# sourceMappingURL=metadata.js.map -/***/ }), +/** @type {import('./shams')} */ +/* eslint complexity: [2, 18], max-statements: [2, 33] */ +module.exports = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } -/***/ 6312: -/***/ ((__unused_webpack_module, exports) => { + /** @type {{ [k in symbol]?: unknown }} */ + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } -"use strict"; + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.VariadicArg = exports.RequiredArg = exports.OptionalArg = exports.CommandArg = void 0; -class CommandArg { - constructor(name, index) { - this.name = name; - this.index = index; - if (typeof name === 'symbol') { - throw new TypeError('Symbols are not supported as argument names.'); - } - } -} -exports.CommandArg = CommandArg; -class OptionalArg extends CommandArg { - toString() { - return `[${String(this.name)}]`; - } -} -exports.OptionalArg = OptionalArg; -class RequiredArg extends CommandArg { - toString() { - return `<${String(this.name)}>`; - } -} -exports.RequiredArg = RequiredArg; -class VariadicArg extends CommandArg { - toString() { - return `[${String(this.name)}...]`; - } -} -exports.VariadicArg = VariadicArg; -//# sourceMappingURL=arg.model.js.map + // temp disabled per https://github.com/ljharb/object.assign/issues/17 + // if (sym instanceof Symbol) { return false; } + // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + // if (!(symObj instanceof Symbol)) { return false; } -/***/ }), + // if (typeof Symbol.prototype.toString !== 'function') { return false; } + // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } -/***/ 84908: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + var symVal = 42; + obj[sym] = symVal; + for (var _ in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } -"use strict"; + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (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); + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } + + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } + + if (typeof Object.getOwnPropertyDescriptor === 'function') { + // eslint-disable-next-line no-extra-parens + var descriptor = /** @type {PropertyDescriptor} */ (Object.getOwnPropertyDescriptor(obj, sym)); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } + + return true; }; -Object.defineProperty(exports, "__esModule", ({ value: true })); -__exportStar(__nccwpck_require__(6312), exports); -__exportStar(__nccwpck_require__(4860), exports); -//# sourceMappingURL=index.js.map + /***/ }), -/***/ 4860: -/***/ ((__unused_webpack_module, exports) => { +/***/ 13752: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Option = void 0; -class Option { - constructor(name, args) { - this.name = name; - this.args = args; - } -} -exports.Option = Option; -//# sourceMappingURL=option.model.js.map + +/** @type {import('./gOPD')} */ +module.exports = Object.getOwnPropertyDescriptor; + /***/ }), -/***/ 65058: -/***/ ((__unused_webpack_module, exports) => { +/***/ 64868: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.decorateIfNot = void 0; -function decorateIfNot(metadataKey, value, target, propertyKey) { - if (!Reflect.hasMetadata(metadataKey, target, propertyKey)) { - const decorator = Reflect.metadata(metadataKey, value); - Reflect.decorate([decorator], target, propertyKey); - } - return Reflect.getMetadata(metadataKey, target, propertyKey); + +/** @type {import('.')} */ +var $gOPD = __nccwpck_require__(13752); + +if ($gOPD) { + try { + $gOPD([], 'length'); + } catch (e) { + // IE 8 has a broken gOPD + $gOPD = null; + } } -exports.decorateIfNot = decorateIfNot; -//# sourceMappingURL=decorateIfNot.js.map + +module.exports = $gOPD; + /***/ }), -/***/ 66725: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 50499: +/***/ ((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; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (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); + +var hasSymbols = __nccwpck_require__(57747); + +/** @type {import('.')} */ +module.exports = function hasToStringTagShams() { + return hasSymbols() && !!Symbol.toStringTag; }; -Object.defineProperty(exports, "__esModule", ({ value: true })); -__exportStar(__nccwpck_require__(65058), exports); -//# sourceMappingURL=index.js.map + /***/ }), -/***/ 86891: +/***/ 38171: /***/ ((module) => { -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 hasOwn = Object.prototype.hasOwnProperty; +var toStr = Object.prototype.toString; +var defineProperty = Object.defineProperty; +var gOPD = Object.getOwnPropertyDescriptor; + +var isArray = function isArray(arr) { + if (typeof Array.isArray === 'function') { + return Array.isArray(arr); + } + + return toStr.call(arr) === '[object Array]'; }; -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; +var isPlainObject = function isPlainObject(obj) { + if (!obj || toStr.call(obj) !== '[object Object]') { + return false; + } + + var hasOwnConstructor = hasOwn.call(obj, 'constructor'); + var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); + // Not own constructor property must be Object + if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { + return false; + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + var key; + for (key in obj) { /**/ } + + return typeof key === 'undefined' || hasOwn.call(obj, key); +}; + +// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target +var setProperty = function setProperty(target, options) { + if (defineProperty && options.name === '__proto__') { + defineProperty(target, options.name, { + enumerable: true, + configurable: true, + value: options.newValue, + writable: true + }); + } else { + target[options.name] = options.newValue; + } +}; + +// Return undefined instead of __proto__ if '__proto__' is not an own property +var getProperty = function getProperty(obj, name) { + if (name === '__proto__') { + if (!hasOwn.call(obj, name)) { + return void 0; + } else if (gOPD) { + // In early versions of node, obj['__proto__'] is buggy when obj has + // __proto__ as an own property. Object.getOwnPropertyDescriptor() works. + return gOPD(obj, name).value; + } + } + + return obj[name]; +}; + +module.exports = function extend() { + var options, name, src, copy, copyIsArray, clone; + var target = arguments[0]; + var i = 1; + var length = arguments.length; + var deep = false; + + // Handle a deep copy situation + if (typeof target === 'boolean') { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + if (target == null || (typeof target !== 'object' && typeof target !== 'function')) { + target = {}; + } + + for (; i < length; ++i) { + options = arguments[i]; + // Only deal with non-null/undefined values + if (options != null) { + // Extend the base object + for (name in options) { + src = getProperty(target, name); + copy = getProperty(options, name); + + // Prevent never-ending loop + if (target !== copy) { + // Recurse if we're merging plain objects or arrays + if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { + if (copyIsArray) { + copyIsArray = false; + clone = src && isArray(src) ? src : []; + } else { + clone = src && isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + setProperty(target, { name: name, newValue: extend(deep, clone, copy) }); + + // Don't bring in undefined values + } else if (typeof copy !== 'undefined') { + setProperty(target, { name: name, newValue: copy }); + } + } + } + } + } + + // Return the modified object + return target; }; /***/ }), -/***/ 95898: -/***/ ((__unused_webpack_module, exports) => { +/***/ 87264: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var __webpack_unused_export__; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. +/* + * extsprintf.js: extended POSIX-style sprintf + */ -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. +var mod_assert = __nccwpck_require__(39491); +var mod_util = __nccwpck_require__(73837); -function isArray(arg) { - if (Array.isArray) { - return Array.isArray(arg); - } - return objectToString(arg) === '[object Array]'; -} -__webpack_unused_export__ = isArray; +/* + * Public interface + */ +exports.sprintf = jsSprintf; +exports.printf = jsPrintf; +exports.fprintf = jsFprintf; -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -__webpack_unused_export__ = isBoolean; +/* + * Stripped down version of s[n]printf(3c). We make a best effort to throw an + * exception when given a format string we don't understand, rather than + * ignoring it, so that we won't break existing programs if/when we go implement + * the rest of this. + * + * This implementation currently supports specifying + * - field alignment ('-' flag), + * - zero-pad ('0' flag) + * - always show numeric sign ('+' flag), + * - field width + * - conversions for strings, decimal integers, and floats (numbers). + * - argument size specifiers. These are all accepted but ignored, since + * Javascript has no notion of the physical size of an argument. + * + * Everything else is currently unsupported, most notably precision, unsigned + * numbers, non-decimal numbers, and characters. + */ +function jsSprintf(fmt) +{ + var regex = [ + '([^%]*)', /* normal text */ + '%', /* start of format */ + '([\'\\-+ #0]*?)', /* flags (optional) */ + '([1-9]\\d*)?', /* width (optional) */ + '(\\.([1-9]\\d*))?', /* precision (optional) */ + '[lhjztL]*?', /* length mods (ignored) */ + '([diouxXfFeEgGaAcCsSp%jr])' /* conversion */ + ].join(''); -function isNull(arg) { - return arg === null; -} -__webpack_unused_export__ = isNull; + var re = new RegExp(regex); + var args = Array.prototype.slice.call(arguments, 1); + var flags, width, precision, conversion; + var left, pad, sign, arg, match; + var ret = ''; + var argn = 1; -function isNullOrUndefined(arg) { - return arg == null; -} -__webpack_unused_export__ = isNullOrUndefined; + mod_assert.equal('string', typeof (fmt)); -function isNumber(arg) { - return typeof arg === 'number'; -} -__webpack_unused_export__ = isNumber; + while ((match = re.exec(fmt)) !== null) { + ret += match[1]; + fmt = fmt.substring(match[0].length); -function isString(arg) { - return typeof arg === 'string'; -} -__webpack_unused_export__ = isString; + flags = match[2] || ''; + width = match[3] || 0; + precision = match[4] || ''; + conversion = match[6]; + left = false; + sign = false; + pad = ' '; -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -__webpack_unused_export__ = isSymbol; + if (conversion == '%') { + ret += '%'; + continue; + } -function isUndefined(arg) { - return arg === void 0; -} -__webpack_unused_export__ = isUndefined; + if (args.length === 0) + throw (new Error('too few args to sprintf')); -function isRegExp(re) { - return objectToString(re) === '[object RegExp]'; -} -__webpack_unused_export__ = isRegExp; + arg = args.shift(); + argn++; -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -__webpack_unused_export__ = isObject; + if (flags.match(/[\' #]/)) + throw (new Error( + 'unsupported flags: ' + flags)); -function isDate(d) { - return objectToString(d) === '[object Date]'; -} -__webpack_unused_export__ = isDate; + if (precision.length > 0) + throw (new Error( + 'non-zero precision not supported')); -function isError(e) { - return (objectToString(e) === '[object Error]' || e instanceof Error); + if (flags.match(/-/)) + left = true; + + if (flags.match(/0/)) + pad = '0'; + + if (flags.match(/\+/)) + sign = true; + + switch (conversion) { + case 's': + if (arg === undefined || arg === null) + throw (new Error('argument ' + argn + + ': attempted to print undefined or null ' + + 'as a string')); + ret += doPad(pad, width, left, arg.toString()); + break; + + case 'd': + arg = Math.floor(arg); + /*jsl:fallthru*/ + case 'f': + sign = sign && arg > 0 ? '+' : ''; + ret += sign + doPad(pad, width, left, + arg.toString()); + break; + + case 'x': + ret += doPad(pad, width, left, arg.toString(16)); + break; + + case 'j': /* non-standard */ + if (width === 0) + width = 10; + ret += mod_util.inspect(arg, false, width); + break; + + case 'r': /* non-standard */ + ret += dumpException(arg); + break; + + default: + throw (new Error('unsupported conversion: ' + + conversion)); + } + } + + ret += fmt; + return (ret); } -exports.VZ = isError; -function isFunction(arg) { - return typeof arg === 'function'; +function jsPrintf() { + var args = Array.prototype.slice.call(arguments); + args.unshift(process.stdout); + jsFprintf.apply(null, args); } -__webpack_unused_export__ = isFunction; -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; +function jsFprintf(stream) { + var args = Array.prototype.slice.call(arguments, 1); + return (stream.write(jsSprintf.apply(this, args))); } -__webpack_unused_export__ = isPrimitive; -__webpack_unused_export__ = Buffer.isBuffer; +function doPad(chr, width, left, str) +{ + var ret = str; -function objectToString(o) { - return Object.prototype.toString.call(o); + while (ret.length < width) { + if (left) + ret += chr; + else + ret = chr + ret; + } + + return (ret); } +/* + * This function dumps long stack traces for exceptions having a cause() method. + * See node-verror for an example. + */ +function dumpException(ex) +{ + var ret; -/***/ }), + if (!(ex instanceof Error)) + throw (new Error(jsSprintf('invalid type for %%r: %j', ex))); -/***/ 19805: -/***/ ((module, exports, __nccwpck_require__) => { + /* Note that V8 prepends "ex.stack" with ex.toString(). */ + ret = 'EXCEPTION: ' + ex.constructor.name + ': ' + ex.stack; -const nodeFetch = __nccwpck_require__(80467) -const realFetch = nodeFetch.default || nodeFetch + if (ex.cause && typeof (ex.cause) === 'function') { + var cex = ex.cause(); + if (cex) { + ret += '\nCaused by: ' + dumpException(cex); + } + } -const fetch = function (url, options) { - // Support schemaless URIs on the server for parity with the browser. - // Ex: //github.com/ -> https://github.com/ - if (/^\/\//.test(url)) { - url = 'https:' + url - } - return realFetch.call(this, url, options) + return (ret); } -fetch.ponyfill = true -module.exports = exports = fetch -exports.fetch = fetch -exports.Headers = nodeFetch.Headers -exports.Request = nodeFetch.Request -exports.Response = nodeFetch.Response +/***/ }), -// Needed for TypeScript consumers without esModuleInterop. -exports["default"] = fetch +/***/ 28206: +/***/ ((module) => { +"use strict"; -/***/ }), -/***/ 72746: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// do not edit .js files directly - edit src/index.jst -"use strict"; -const cp = __nccwpck_require__(32081); -const parse = __nccwpck_require__(66855); -const enoent = __nccwpck_require__(44101); +module.exports = function equal(a, b) { + if (a === b) return true; -function spawn(command, args, options) { - // Parse the arguments - const parsed = parse(command, args, options); + if (a && b && typeof a == 'object' && typeof b == 'object') { + if (a.constructor !== b.constructor) return false; - // Spawn the child process - const spawned = cp.spawn(parsed.command, parsed.args, parsed.options); + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) + if (!equal(a[i], b[i])) return false; + return true; + } - // Hook into child process "exit" event to emit an error if the command - // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 - enoent.hookChildProcess(spawned, parsed); - return spawned; -} -function spawnSync(command, args, options) { - // Parse the arguments - const parsed = parse(command, args, options); + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); - // Spawn the child process - const result = cp.spawnSync(parsed.command, parsed.args, parsed.options); + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; - // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 - result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); + for (i = length; i-- !== 0;) + if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; - return result; -} + for (i = length; i-- !== 0;) { + var key = keys[i]; -module.exports = spawn; -module.exports.spawn = spawn; -module.exports.sync = spawnSync; + if (!equal(a[key], b[key])) return false; + } -module.exports._parse = parse; -module.exports._enoent = enoent; + return true; + } + + // true if both NaN, false otherwise + return a!==a && b!==b; +}; /***/ }), -/***/ 44101: +/***/ 30969: /***/ ((module) => { "use strict"; -const isWin = process.platform === 'win32'; - -function notFoundError(original, syscall) { - return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), { - code: 'ENOENT', - errno: 'ENOENT', - syscall: `${syscall} ${original.command}`, - path: original.command, - spawnargs: original.args, - }); -} +module.exports = function (data, opts) { + if (!opts) opts = {}; + if (typeof opts === 'function') opts = { cmp: opts }; + var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false; -function hookChildProcess(cp, parsed) { - if (!isWin) { - return; - } + var cmp = opts.cmp && (function (f) { + return function (node) { + return function (a, b) { + var aobj = { key: a, value: node[a] }; + var bobj = { key: b, value: node[b] }; + return f(aobj, bobj); + }; + }; + })(opts.cmp); - const originalEmit = cp.emit; + var seen = []; + return (function stringify (node) { + if (node && node.toJSON && typeof node.toJSON === 'function') { + node = node.toJSON(); + } - cp.emit = function (name, arg1) { - // If emitting "exit" event and exit code is 1, we need to check if - // the command exists and emit an "error" instead - // See https://github.com/IndigoUnited/node-cross-spawn/issues/16 - if (name === 'exit') { - const err = verifyENOENT(arg1, parsed, 'spawn'); + if (node === undefined) return; + if (typeof node == 'number') return isFinite(node) ? '' + node : 'null'; + if (typeof node !== 'object') return JSON.stringify(node); - if (err) { - return originalEmit.call(cp, 'error', err); + var i, out; + if (Array.isArray(node)) { + out = '['; + for (i = 0; i < node.length; i++) { + if (i) out += ','; + out += stringify(node[i]) || 'null'; } + return out + ']'; } - return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params - }; -} - -function verifyENOENT(status, parsed) { - if (isWin && status === 1 && !parsed.file) { - return notFoundError(parsed.original, 'spawn'); - } - - return null; -} + if (node === null) return 'null'; -function verifyENOENTSync(status, parsed) { - if (isWin && status === 1 && !parsed.file) { - return notFoundError(parsed.original, 'spawnSync'); - } + if (seen.indexOf(node) !== -1) { + if (cycles) return JSON.stringify('__cycle__'); + throw new TypeError('Converting circular structure to JSON'); + } - return null; -} + var seenIndex = seen.push(node) - 1; + var keys = Object.keys(node).sort(cmp && cmp(node)); + out = ''; + for (i = 0; i < keys.length; i++) { + var key = keys[i]; + var value = stringify(node[key]); -module.exports = { - hookChildProcess, - verifyENOENT, - verifyENOENTSync, - notFoundError, + if (!value) continue; + if (out) out += ','; + out += JSON.stringify(key) + ':' + value; + } + seen.splice(seenIndex, 1); + return '{' + out + '}'; + })(data); }; /***/ }), -/***/ 66855: +/***/ 12603: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const path = __nccwpck_require__(71017); -const resolveCommand = __nccwpck_require__(87274); -const escape = __nccwpck_require__(34274); -const readShebang = __nccwpck_require__(41252); +const validator = __nccwpck_require__(61739); +const XMLParser = __nccwpck_require__(42380); +const XMLBuilder = __nccwpck_require__(80660); -const isWin = process.platform === 'win32'; -const isExecutableRegExp = /\.(?:com|exe)$/i; -const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; +module.exports = { + XMLParser: XMLParser, + XMLValidator: validator, + XMLBuilder: XMLBuilder +} -function detectShebang(parsed) { - parsed.file = resolveCommand(parsed); +/***/ }), - const shebang = parsed.file && readShebang(parsed.file); +/***/ 38280: +/***/ ((__unused_webpack_module, exports) => { - if (shebang) { - parsed.args.unshift(parsed.file); - parsed.command = shebang; +"use strict"; - return resolveCommand(parsed); + +const nameStartChar = ':A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD'; +const nameChar = nameStartChar + '\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040'; +const nameRegexp = '[' + nameStartChar + '][' + nameChar + ']*' +const regexName = new RegExp('^' + nameRegexp + '$'); + +const getAllMatches = function(string, regex) { + const matches = []; + let match = regex.exec(string); + while (match) { + const allmatches = []; + allmatches.startIndex = regex.lastIndex - match[0].length; + const len = match.length; + for (let index = 0; index < len; index++) { + allmatches.push(match[index]); } + matches.push(allmatches); + match = regex.exec(string); + } + return matches; +}; - return parsed.file; -} +const isName = function(string) { + const match = regexName.exec(string); + return !(match === null || typeof match === 'undefined'); +}; -function parseNonShell(parsed) { - if (!isWin) { - return parsed; +exports.isExist = function(v) { + return typeof v !== 'undefined'; +}; + +exports.isEmptyObject = function(obj) { + return Object.keys(obj).length === 0; +}; + +/** + * Copy all the properties of a into b. + * @param {*} target + * @param {*} a + */ +exports.merge = function(target, a, arrayMode) { + if (a) { + const keys = Object.keys(a); // will return an array of own properties + const len = keys.length; //don't make it inline + for (let i = 0; i < len; i++) { + if (arrayMode === 'strict') { + target[keys[i]] = [ a[keys[i]] ]; + } else { + target[keys[i]] = a[keys[i]]; + } } + } +}; +/* exports.merge =function (b,a){ + return Object.assign(b,a); +} */ - // Detect & add support for shebangs - const commandFile = detectShebang(parsed); +exports.getValue = function(v) { + if (exports.isExist(v)) { + return v; + } else { + return ''; + } +}; - // We don't need a shell if the command filename is an executable - const needsShell = !isExecutableRegExp.test(commandFile); +// const fakeCall = function(a) {return a;}; +// const fakeCallNoReturn = function() {}; - // If a shell is required, use cmd.exe and take care of escaping everything correctly - // Note that `forceShell` is an hidden option used only in tests - if (parsed.options.forceShell || needsShell) { - // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/` - // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument - // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called, - // we need to double escape them - const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); +exports.isName = isName; +exports.getAllMatches = getAllMatches; +exports.nameRegexp = nameRegexp; - // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar) - // This is necessary otherwise it will always fail with ENOENT in those cases - parsed.command = path.normalize(parsed.command); - // Escape command & arguments - parsed.command = escape.command(parsed.command); - parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars)); +/***/ }), - const shellCommand = [parsed.command].concat(parsed.args).join(' '); +/***/ 61739: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; - parsed.command = process.env.comspec || 'cmd.exe'; - parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped - } +"use strict"; - return parsed; -} -function parse(command, args, options) { - // Normalize arguments, similar to nodejs - if (args && !Array.isArray(args)) { - options = args; - args = null; +const util = __nccwpck_require__(38280); + +const defaultOptions = { + allowBooleanAttributes: false, //A tag can have attributes without any value + unpairedTags: [] +}; + +//const tagsPattern = new RegExp("<\\/?([\\w:\\-_\.]+)\\s*\/?>","g"); +exports.validate = function (xmlData, options) { + options = Object.assign({}, defaultOptions, options); + + //xmlData = xmlData.replace(/(\r\n|\n|\r)/gm,"");//make it single line + //xmlData = xmlData.replace(/(^\s*<\?xml.*?\?>)/g,"");//Remove XML starting tag + //xmlData = xmlData.replace(/()/g,"");//Remove DOCTYPE + const tags = []; + let tagFound = false; + + //indicates that the root tag has been closed (aka. depth 0 has been reached) + let reachedRoot = false; + + if (xmlData[0] === '\ufeff') { + // check for byte order mark (BOM) + xmlData = xmlData.substr(1); + } + + for (let i = 0; i < xmlData.length; i++) { + + if (xmlData[i] === '<' && xmlData[i+1] === '?') { + i+=2; + i = readPI(xmlData,i); + if (i.err) return i; + }else if (xmlData[i] === '<') { + //starting of tag + //read until you reach to '>' avoiding any '>' in attribute value + let tagStartPos = i; + i++; + + if (xmlData[i] === '!') { + i = readCommentAndCDATA(xmlData, i); + continue; + } else { + let closingTag = false; + if (xmlData[i] === '/') { + //closing tag + closingTag = true; + i++; + } + //read tagname + let tagName = ''; + for (; i < xmlData.length && + xmlData[i] !== '>' && + xmlData[i] !== ' ' && + xmlData[i] !== '\t' && + xmlData[i] !== '\n' && + xmlData[i] !== '\r'; i++ + ) { + tagName += xmlData[i]; + } + tagName = tagName.trim(); + //console.log(tagName); + + if (tagName[tagName.length - 1] === '/') { + //self closing tag without attributes + tagName = tagName.substring(0, tagName.length - 1); + //continue; + i--; + } + if (!validateTagName(tagName)) { + let msg; + if (tagName.trim().length === 0) { + msg = "Invalid space after '<'."; + } else { + msg = "Tag '"+tagName+"' is an invalid name."; + } + return getErrorObject('InvalidTag', msg, getLineNumberForPosition(xmlData, i)); + } + + const result = readAttributeStr(xmlData, i); + if (result === false) { + return getErrorObject('InvalidAttr', "Attributes for '"+tagName+"' have open quote.", getLineNumberForPosition(xmlData, i)); + } + let attrStr = result.value; + i = result.index; + + if (attrStr[attrStr.length - 1] === '/') { + //self closing tag + const attrStrStart = i - attrStr.length; + attrStr = attrStr.substring(0, attrStr.length - 1); + const isValid = validateAttributeString(attrStr, options); + if (isValid === true) { + tagFound = true; + //continue; //text may presents after self closing tag + } else { + //the result from the nested function returns the position of the error within the attribute + //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute + //this gives us the absolute index in the entire xml, which we can use to find the line at last + return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line)); + } + } else if (closingTag) { + if (!result.tagClosed) { + return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' doesn't have proper closing.", getLineNumberForPosition(xmlData, i)); + } else if (attrStr.trim().length > 0) { + return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos)); + } else if (tags.length === 0) { + return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos)); + } else { + const otg = tags.pop(); + if (tagName !== otg.tagName) { + let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos); + return getErrorObject('InvalidTag', + "Expected closing tag '"+otg.tagName+"' (opened in line "+openPos.line+", col "+openPos.col+") instead of closing tag '"+tagName+"'.", + getLineNumberForPosition(xmlData, tagStartPos)); + } + + //when there are no more tags, we reached the root level. + if (tags.length == 0) { + reachedRoot = true; + } + } + } else { + const isValid = validateAttributeString(attrStr, options); + if (isValid !== true) { + //the result from the nested function returns the position of the error within the attribute + //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute + //this gives us the absolute index in the entire xml, which we can use to find the line at last + return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line)); + } + + //if the root level has been reached before ... + if (reachedRoot === true) { + return getErrorObject('InvalidXml', 'Multiple possible root nodes found.', getLineNumberForPosition(xmlData, i)); + } else if(options.unpairedTags.indexOf(tagName) !== -1){ + //don't push into stack + } else { + tags.push({tagName, tagStartPos}); + } + tagFound = true; + } + + //skip tag text value + //It may include comments and CDATA value + for (i++; i < xmlData.length; i++) { + if (xmlData[i] === '<') { + if (xmlData[i + 1] === '!') { + //comment or CADATA + i++; + i = readCommentAndCDATA(xmlData, i); + continue; + } else if (xmlData[i+1] === '?') { + i = readPI(xmlData, ++i); + if (i.err) return i; + } else{ + break; + } + } else if (xmlData[i] === '&') { + const afterAmp = validateAmpersand(xmlData, i); + if (afterAmp == -1) + return getErrorObject('InvalidChar', "char '&' is not expected.", getLineNumberForPosition(xmlData, i)); + i = afterAmp; + }else{ + if (reachedRoot === true && !isWhiteSpace(xmlData[i])) { + return getErrorObject('InvalidXml', "Extra text at the end", getLineNumberForPosition(xmlData, i)); + } + } + } //end of reading tag text value + if (xmlData[i] === '<') { + i--; + } + } + } else { + if ( isWhiteSpace(xmlData[i])) { + continue; + } + return getErrorObject('InvalidChar', "char '"+xmlData[i]+"' is not expected.", getLineNumberForPosition(xmlData, i)); } + } - args = args ? args.slice(0) : []; // Clone array to avoid changing the original - options = Object.assign({}, options); // Clone object to avoid changing the original + if (!tagFound) { + return getErrorObject('InvalidXml', 'Start tag expected.', 1); + }else if (tags.length == 1) { + return getErrorObject('InvalidTag', "Unclosed tag '"+tags[0].tagName+"'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos)); + }else if (tags.length > 0) { + return getErrorObject('InvalidXml', "Invalid '"+ + JSON.stringify(tags.map(t => t.tagName), null, 4).replace(/\r?\n/g, '')+ + "' found.", {line: 1, col: 1}); + } - // Build our parsed object - const parsed = { - command, - args, - options, - file: undefined, - original: { - command, - args, - }, - }; + return true; +}; + +function isWhiteSpace(char){ + return char === ' ' || char === '\t' || char === '\n' || char === '\r'; +} +/** + * Read Processing insstructions and skip + * @param {*} xmlData + * @param {*} i + */ +function readPI(xmlData, i) { + const start = i; + for (; i < xmlData.length; i++) { + if (xmlData[i] == '?' || xmlData[i] == ' ') { + //tagname + const tagname = xmlData.substr(start, i - start); + if (i > 5 && tagname === 'xml') { + return getErrorObject('InvalidXml', 'XML declaration allowed only at the start of the document.', getLineNumberForPosition(xmlData, i)); + } else if (xmlData[i] == '?' && xmlData[i + 1] == '>') { + //check if valid attribut string + i++; + break; + } else { + continue; + } + } + } + return i; +} + +function readCommentAndCDATA(xmlData, i) { + if (xmlData.length > i + 5 && xmlData[i + 1] === '-' && xmlData[i + 2] === '-') { + //comment + for (i += 3; i < xmlData.length; i++) { + if (xmlData[i] === '-' && xmlData[i + 1] === '-' && xmlData[i + 2] === '>') { + i += 2; + break; + } + } + } else if ( + xmlData.length > i + 8 && + xmlData[i + 1] === 'D' && + xmlData[i + 2] === 'O' && + xmlData[i + 3] === 'C' && + xmlData[i + 4] === 'T' && + xmlData[i + 5] === 'Y' && + xmlData[i + 6] === 'P' && + xmlData[i + 7] === 'E' + ) { + let angleBracketsCount = 1; + for (i += 8; i < xmlData.length; i++) { + if (xmlData[i] === '<') { + angleBracketsCount++; + } else if (xmlData[i] === '>') { + angleBracketsCount--; + if (angleBracketsCount === 0) { + break; + } + } + } + } else if ( + xmlData.length > i + 9 && + xmlData[i + 1] === '[' && + xmlData[i + 2] === 'C' && + xmlData[i + 3] === 'D' && + xmlData[i + 4] === 'A' && + xmlData[i + 5] === 'T' && + xmlData[i + 6] === 'A' && + xmlData[i + 7] === '[' + ) { + for (i += 8; i < xmlData.length; i++) { + if (xmlData[i] === ']' && xmlData[i + 1] === ']' && xmlData[i + 2] === '>') { + i += 2; + break; + } + } + } - // Delegate further parsing to shell or non-shell - return options.shell ? parsed : parseNonShell(parsed); + return i; } -module.exports = parse; - - -/***/ }), - -/***/ 34274: -/***/ ((module) => { - -"use strict"; - - -// See http://www.robvanderwoude.com/escapechars.php -const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; +const doubleQuote = '"'; +const singleQuote = "'"; -function escapeCommand(arg) { - // Escape meta chars - arg = arg.replace(metaCharsRegExp, '^$1'); +/** + * Keep reading xmlData until '<' is found outside the attribute value. + * @param {string} xmlData + * @param {number} i + */ +function readAttributeStr(xmlData, i) { + let attrStr = ''; + let startChar = ''; + let tagClosed = false; + for (; i < xmlData.length; i++) { + if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) { + if (startChar === '') { + startChar = xmlData[i]; + } else if (startChar !== xmlData[i]) { + //if vaue is enclosed with double quote then single quotes are allowed inside the value and vice versa + } else { + startChar = ''; + } + } else if (xmlData[i] === '>') { + if (startChar === '') { + tagClosed = true; + break; + } + } + attrStr += xmlData[i]; + } + if (startChar !== '') { + return false; + } - return arg; + return { + value: attrStr, + index: i, + tagClosed: tagClosed + }; } -function escapeArgument(arg, doubleEscapeMetaChars) { - // Convert to string - arg = `${arg}`; - - // Algorithm below is based on https://qntm.org/cmd - - // Sequence of backslashes followed by a double quote: - // double up all the backslashes and escape the double quote - arg = arg.replace(/(\\*)"/g, '$1$1\\"'); +/** + * Select all the attributes whether valid or invalid. + */ +const validAttrStrRegxp = new RegExp('(\\s*)([^\\s=]+)(\\s*=)?(\\s*([\'"])(([\\s\\S])*?)\\5)?', 'g'); - // Sequence of backslashes followed by the end of the string - // (which will become a double quote later): - // double up all the backslashes - arg = arg.replace(/(\\*)$/, '$1$1'); +//attr, ="sd", a="amit's", a="sd"b="saf", ab cd="" - // All other backslashes occur literally +function validateAttributeString(attrStr, options) { + //console.log("start:"+attrStr+":end"); - // Quote the whole thing: - arg = `"${arg}"`; + //if(attrStr.trim().length === 0) return true; //empty string - // Escape meta chars - arg = arg.replace(metaCharsRegExp, '^$1'); + const matches = util.getAllMatches(attrStr, validAttrStrRegxp); + const attrNames = {}; - // Double escape meta chars if necessary - if (doubleEscapeMetaChars) { - arg = arg.replace(metaCharsRegExp, '^$1'); + for (let i = 0; i < matches.length; i++) { + if (matches[i][1].length === 0) { + //nospace before attribute name: a="sd"b="saf" + return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' has no space in starting.", getPositionFromMatch(matches[i])) + } else if (matches[i][3] !== undefined && matches[i][4] === undefined) { + return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' is without value.", getPositionFromMatch(matches[i])); + } else if (matches[i][3] === undefined && !options.allowBooleanAttributes) { + //independent attribute: ab + return getErrorObject('InvalidAttr', "boolean attribute '"+matches[i][2]+"' is not allowed.", getPositionFromMatch(matches[i])); + } + /* else if(matches[i][6] === undefined){//attribute without value: ab= + return { err: { code:"InvalidAttr",msg:"attribute " + matches[i][2] + " has no value assigned."}}; + } */ + const attrName = matches[i][2]; + if (!validateAttrName(attrName)) { + return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is an invalid name.", getPositionFromMatch(matches[i])); + } + if (!attrNames.hasOwnProperty(attrName)) { + //check for duplicate attribute. + attrNames[attrName] = 1; + } else { + return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is repeated.", getPositionFromMatch(matches[i])); } + } - return arg; + return true; } -module.exports.command = escapeCommand; -module.exports.argument = escapeArgument; - - -/***/ }), - -/***/ 41252: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function validateNumberAmpersand(xmlData, i) { + let re = /\d/; + if (xmlData[i] === 'x') { + i++; + re = /[\da-fA-F]/; + } + for (; i < xmlData.length; i++) { + if (xmlData[i] === ';') + return i; + if (!xmlData[i].match(re)) + break; + } + return -1; +} -"use strict"; +function validateAmpersand(xmlData, i) { + // https://www.w3.org/TR/xml/#dt-charref + i++; + if (xmlData[i] === ';') + return -1; + if (xmlData[i] === '#') { + i++; + return validateNumberAmpersand(xmlData, i); + } + let count = 0; + for (; i < xmlData.length; i++, count++) { + if (xmlData[i].match(/\w/) && count < 20) + continue; + if (xmlData[i] === ';') + break; + return -1; + } + return i; +} +function getErrorObject(code, message, lineNumber) { + return { + err: { + code: code, + msg: message, + line: lineNumber.line || lineNumber, + col: lineNumber.col, + }, + }; +} -const fs = __nccwpck_require__(57147); -const shebangCommand = __nccwpck_require__(67032); +function validateAttrName(attrName) { + return util.isName(attrName); +} -function readShebang(command) { - // Read the first 150 bytes from the file - const size = 150; - const buffer = Buffer.alloc(size); +// const startsWithXML = /^xml/i; - let fd; +function validateTagName(tagname) { + return util.isName(tagname) /* && !tagname.match(startsWithXML) */; +} - try { - fd = fs.openSync(command, 'r'); - fs.readSync(fd, buffer, 0, size, 0); - fs.closeSync(fd); - } catch (e) { /* Empty */ } +//this function returns the line number for the character at the given index +function getLineNumberForPosition(xmlData, index) { + const lines = xmlData.substring(0, index).split(/\r?\n/); + return { + line: lines.length, - // Attempt to extract shebang (null is returned if not a shebang) - return shebangCommand(buffer.toString()); + // column number is last line's length + 1, because column numbering starts at 1: + col: lines[lines.length - 1].length + 1 + }; } -module.exports = readShebang; +//this function returns the position of the first character of match within attrStr +function getPositionFromMatch(match) { + return match.startIndex + match[1].length; +} /***/ }), -/***/ 87274: +/***/ 80660: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +//parse Empty Node as self closing node +const buildFromOrderedJs = __nccwpck_require__(72462); -const path = __nccwpck_require__(71017); -const which = __nccwpck_require__(34207); -const getPathKey = __nccwpck_require__(20539); +const defaultOptions = { + attributeNamePrefix: '@_', + attributesGroupName: false, + textNodeName: '#text', + ignoreAttributes: true, + cdataPropName: false, + format: false, + indentBy: ' ', + suppressEmptyNode: false, + suppressUnpairedNode: true, + suppressBooleanAttributes: true, + tagValueProcessor: function(key, a) { + return a; + }, + attributeValueProcessor: function(attrName, a) { + return a; + }, + preserveOrder: false, + commentPropName: false, + unpairedTags: [], + entities: [ + { regex: new RegExp("&", "g"), val: "&" },//it must be on top + { regex: new RegExp(">", "g"), val: ">" }, + { regex: new RegExp("<", "g"), val: "<" }, + { regex: new RegExp("\'", "g"), val: "'" }, + { regex: new RegExp("\"", "g"), val: """ } + ], + processEntities: true, + stopNodes: [], + // transformTagName: false, + // transformAttributeName: false, + oneListGroup: false +}; -function resolveCommandAttempt(parsed, withoutPathExt) { - const env = parsed.options.env || process.env; - const cwd = process.cwd(); - const hasCustomCwd = parsed.options.cwd != null; - // Worker threads do not have process.chdir() - const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled; +function Builder(options) { + this.options = Object.assign({}, defaultOptions, options); + if (this.options.ignoreAttributes || this.options.attributesGroupName) { + this.isAttribute = function(/*a*/) { + return false; + }; + } else { + this.attrPrefixLen = this.options.attributeNamePrefix.length; + this.isAttribute = isAttribute; + } - // If a custom `cwd` was specified, we need to change the process cwd - // because `which` will do stat calls but does not support a custom cwd - if (shouldSwitchCwd) { - try { - process.chdir(parsed.options.cwd); - } catch (err) { - /* Empty */ - } - } + this.processTextOrObjNode = processTextOrObjNode - let resolved; + if (this.options.format) { + this.indentate = indentate; + this.tagEndChar = '>\n'; + this.newLine = '\n'; + } else { + this.indentate = function() { + return ''; + }; + this.tagEndChar = '>'; + this.newLine = ''; + } +} - try { - resolved = which.sync(parsed.command, { - path: env[getPathKey({ env })], - pathExt: withoutPathExt ? path.delimiter : undefined, - }); - } catch (e) { - /* Empty */ - } finally { - if (shouldSwitchCwd) { - process.chdir(cwd); - } +Builder.prototype.build = function(jObj) { + if(this.options.preserveOrder){ + return buildFromOrderedJs(jObj, this.options); + }else { + if(Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1){ + jObj = { + [this.options.arrayNodeName] : jObj + } } + return this.j2x(jObj, 0).val; + } +}; - // If we successfully resolved, ensure that an absolute path is returned - // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it - if (resolved) { - resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved); +Builder.prototype.j2x = function(jObj, level) { + let attrStr = ''; + let val = ''; + for (let key in jObj) { + if(!Object.prototype.hasOwnProperty.call(jObj, key)) continue; + if (typeof jObj[key] === 'undefined') { + // supress undefined node only if it is not an attribute + if (this.isAttribute(key)) { + val += ''; + } + } else if (jObj[key] === null) { + // null attribute should be ignored by the attribute list, but should not cause the tag closing + if (this.isAttribute(key)) { + val += ''; + } else if (key[0] === '?') { + val += this.indentate(level) + '<' + key + '?' + this.tagEndChar; + } else { + val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; + } + // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; + } else if (jObj[key] instanceof Date) { + val += this.buildTextValNode(jObj[key], key, '', level); + } else if (typeof jObj[key] !== 'object') { + //premitive type + const attr = this.isAttribute(key); + if (attr) { + attrStr += this.buildAttrPairStr(attr, '' + jObj[key]); + }else { + //tag value + if (key === this.options.textNodeName) { + let newval = this.options.tagValueProcessor(key, '' + jObj[key]); + val += this.replaceEntitiesValue(newval); + } else { + val += this.buildTextValNode(jObj[key], key, '', level); + } + } + } else if (Array.isArray(jObj[key])) { + //repeated nodes + const arrLen = jObj[key].length; + let listTagVal = ""; + let listTagAttr = ""; + for (let j = 0; j < arrLen; j++) { + const item = jObj[key][j]; + if (typeof item === 'undefined') { + // supress undefined node + } else if (item === null) { + if(key[0] === "?") val += this.indentate(level) + '<' + key + '?' + this.tagEndChar; + else val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; + // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; + } else if (typeof item === 'object') { + if(this.options.oneListGroup){ + const result = this.j2x(item, level + 1); + listTagVal += result.val; + if (this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName)) { + listTagAttr += result.attrStr + } + }else{ + listTagVal += this.processTextOrObjNode(item, key, level) + } + } else { + if (this.options.oneListGroup) { + let textValue = this.options.tagValueProcessor(key, item); + textValue = this.replaceEntitiesValue(textValue); + listTagVal += textValue; + } else { + listTagVal += this.buildTextValNode(item, key, '', level); + } + } + } + if(this.options.oneListGroup){ + listTagVal = this.buildObjectNode(listTagVal, key, listTagAttr, level); + } + val += listTagVal; + } else { + //nested node + if (this.options.attributesGroupName && key === this.options.attributesGroupName) { + const Ks = Object.keys(jObj[key]); + const L = Ks.length; + for (let j = 0; j < L; j++) { + attrStr += this.buildAttrPairStr(Ks[j], '' + jObj[key][Ks[j]]); + } + } else { + val += this.processTextOrObjNode(jObj[key], key, level) + } } + } + return {attrStr: attrStr, val: val}; +}; - return resolved; +Builder.prototype.buildAttrPairStr = function(attrName, val){ + val = this.options.attributeValueProcessor(attrName, '' + val); + val = this.replaceEntitiesValue(val); + if (this.options.suppressBooleanAttributes && val === "true") { + return ' ' + attrName; + } else return ' ' + attrName + '="' + val + '"'; } -function resolveCommand(parsed) { - return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); +function processTextOrObjNode (object, key, level) { + const result = this.j2x(object, level + 1); + if (object[this.options.textNodeName] !== undefined && Object.keys(object).length === 1) { + return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level); + } else { + return this.buildObjectNode(result.val, key, result.attrStr, level); + } } -module.exports = resolveCommand; - - -/***/ }), - -/***/ 28222: -/***/ ((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; - } +Builder.prototype.buildObjectNode = function(val, key, attrStr, level) { + if(val === ""){ + if(key[0] === "?") return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar; + else { + return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar; + } + }else{ - // 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+)/)); + let tagEndExp = '' + val + tagEndExp ); + } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) { + return this.indentate(level) + `` + this.newLine; + }else { + return ( + this.indentate(level) + '<' + key + attrStr + piClosingChar + this.tagEndChar + + val + + this.indentate(level) + tagEndExp ); + } + } } -/** - * 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; - } - }); - - args.splice(lastC, 0, c); +Builder.prototype.closeTag = function(key){ + let closeTag = ""; + if(this.options.unpairedTags.indexOf(key) !== -1){ //unpaired + if(!this.options.suppressUnpairedNode) closeTag = "/" + }else if(this.options.suppressEmptyNode){ //empty + closeTag = "/"; + }else{ + closeTag = `> {}); - -/** - * 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? - } +function buildEmptyObjNode(val, key, attrStr, level) { + if (val !== '') { + return this.buildObjectNode(val, key, attrStr, level); + } else { + if(key[0] === "?") return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar; + else { + return this.indentate(level) + '<' + key + attrStr + '/' + this.tagEndChar; + // return this.buildTagStr(level,key, attrStr); + } + } } -/** - * 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; +Builder.prototype.buildTextValNode = function(val, key, attrStr, level) { + if (this.options.cdataPropName !== false && key === this.options.cdataPropName) { + return this.indentate(level) + `` + this.newLine; + }else if (this.options.commentPropName !== false && key === this.options.commentPropName) { + return this.indentate(level) + `` + this.newLine; + }else if(key[0] === "?") {//PI tag + return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar; + }else{ + let textValue = this.options.tagValueProcessor(key, val); + textValue = this.replaceEntitiesValue(textValue); + + if( textValue === ''){ + return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar; + }else{ + return this.indentate(level) + '<' + key + attrStr + '>' + + textValue + + ' 0 && this.options.processEntities){ + for (let i=0; i { +/***/ 72462: +/***/ ((module) => { +const EOL = "\n"; /** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. + * + * @param {array} jArray + * @param {any} options + * @returns */ +function toXml(jArray, options) { + let indentation = ""; + if (options.format && options.indentBy.length > 0) { + indentation = EOL; + } + return arrToStr(jArray, options, "", indentation); +} -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__(80900); - 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; - - args[0] = createDebug.coerce(args[0]); - - 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); - - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); - - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); - - 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); - } +function arrToStr(arr, options, jPath, indentation) { + let xmlStr = ""; + let isPreviousElementTag = false; - return enabledCache; - }, - set: v => { - enableOverride = v; - } - }); + for (let i = 0; i < arr.length; i++) { + const tagObj = arr[i]; + const tagName = propName(tagObj); + if(tagName === undefined) continue; - // Env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } + let newJPath = ""; + if (jPath.length === 0) newJPath = tagName + else newJPath = `${jPath}.${tagName}`; - return debug; - } + if (tagName === options.textNodeName) { + let tagText = tagObj[tagName]; + if (!isStopNode(newJPath, options)) { + tagText = options.tagValueProcessor(tagName, tagText); + tagText = replaceEntitiesValue(tagText, options); + } + if (isPreviousElementTag) { + xmlStr += indentation; + } + xmlStr += tagText; + isPreviousElementTag = false; + continue; + } else if (tagName === options.cdataPropName) { + if (isPreviousElementTag) { + xmlStr += indentation; + } + xmlStr += ``; + isPreviousElementTag = false; + continue; + } else if (tagName === options.commentPropName) { + xmlStr += indentation + ``; + isPreviousElementTag = true; + continue; + } else if (tagName[0] === "?") { + const attStr = attr_to_str(tagObj[":@"], options); + const tempInd = tagName === "?xml" ? "" : indentation; + let piTextNodeName = tagObj[tagName][0][options.textNodeName]; + piTextNodeName = piTextNodeName.length !== 0 ? " " + piTextNodeName : ""; //remove extra spacing + xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr}?>`; + isPreviousElementTag = true; + continue; + } + let newIdentation = indentation; + if (newIdentation !== "") { + newIdentation += options.indentBy; + } + const attStr = attr_to_str(tagObj[":@"], options); + const tagStart = indentation + `<${tagName}${attStr}`; + const tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation); + if (options.unpairedTags.indexOf(tagName) !== -1) { + if (options.suppressUnpairedNode) xmlStr += tagStart + ">"; + else xmlStr += tagStart + "/>"; + } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) { + xmlStr += tagStart + "/>"; + } else if (tagValue && tagValue.endsWith(">")) { + xmlStr += tagStart + `>${tagValue}${indentation}`; + } else { + xmlStr += tagStart + ">"; + if (tagValue && indentation !== "" && (tagValue.includes("/>") || tagValue.includes("`; + } + isPreviousElementTag = true; + } - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } + return xmlStr; +} - /** - * 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; +function propName(obj) { + const keys = Object.keys(obj); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + if(!obj.hasOwnProperty(key)) continue; + if (key !== ":@") return key; + } +} - createDebug.names = []; - createDebug.skips = []; +function attr_to_str(attrMap, options) { + let attrStr = ""; + if (attrMap && !options.ignoreAttributes) { + for (let attr in attrMap) { + if(!attrMap.hasOwnProperty(attr)) continue; + let attrVal = options.attributeValueProcessor(attr, attrMap[attr]); + attrVal = replaceEntitiesValue(attrVal, options); + if (attrVal === true && options.suppressBooleanAttributes) { + attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`; + } else { + attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${attrVal}"`; + } + } + } + return attrStr; +} - let i; - const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - const len = split.length; +function isStopNode(jPath, options) { + jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1); + let tagName = jPath.substr(jPath.lastIndexOf(".") + 1); + for (let index in options.stopNodes) { + if (options.stopNodes[index] === jPath || options.stopNodes[index] === "*." + tagName) return true; + } + return false; +} - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } +function replaceEntitiesValue(textValue, options) { + if (textValue && textValue.length > 0 && options.processEntities) { + for (let i = 0; i < options.entities.length; i++) { + const entity = options.entities[i]; + textValue = textValue.replace(entity.regex, entity.val); + } + } + return textValue; +} +module.exports = toXml; - namespaces = split[i].replace(/\*/g, '.*?'); - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); - } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); - } - } - } +/***/ }), - /** - * 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; - } +/***/ 6072: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * 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; - } +const util = __nccwpck_require__(38280); - let i; - let len; +//TODO: handle comments +function readDocType(xmlData, i){ + + const entities = {}; + if( xmlData[i + 3] === 'O' && + xmlData[i + 4] === 'C' && + xmlData[i + 5] === 'T' && + xmlData[i + 6] === 'Y' && + xmlData[i + 7] === 'P' && + xmlData[i + 8] === 'E') + { + i = i+9; + let angleBracketsCount = 1; + let hasBody = false, comment = false; + let exp = ""; + for(;i') { //Read tag content + if(comment){ + if( xmlData[i - 1] === "-" && xmlData[i - 2] === "-"){ + comment = false; + angleBracketsCount--; + } + }else{ + angleBracketsCount--; + } + if (angleBracketsCount === 0) { + break; + } + }else if( xmlData[i] === '['){ + hasBody = true; + }else{ + exp += xmlData[i]; + } + } + if(angleBracketsCount !== 0){ + throw new Error(`Unclosed DOCTYPE`); + } + }else{ + throw new Error(`Invalid Tag instead of DOCTYPE`); + } + return {entities, i}; +} - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } +function readEntityExp(xmlData,i){ + //External entities are not supported + // - return false; - } + //Parameter entities are not supported + // - /** - * 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(/\.\*\?$/, '*'); - } + //Internal entities are supported + // + + //read EntityName + let entityName = ""; + for (; i < xmlData.length && (xmlData[i] !== "'" && xmlData[i] !== '"' ); i++) { + // if(xmlData[i] === " ") continue; + // else + entityName += xmlData[i]; + } + entityName = entityName.trim(); + if(entityName.indexOf(" ") !== -1) throw new Error("External entites are not supported"); - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } + //read Entity Value + const startChar = xmlData[i++]; + let val = "" + for (; i < xmlData.length && xmlData[i] !== startChar ; i++) { + val += xmlData[i]; + } + return [entityName, val, i]; +} - /** - * 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`.'); - } +function isComment(xmlData, i){ + if(xmlData[i+1] === '!' && + xmlData[i+2] === '-' && + xmlData[i+3] === '-') return true + return false +} +function isEntity(xmlData, i){ + if(xmlData[i+1] === '!' && + xmlData[i+2] === 'E' && + xmlData[i+3] === 'N' && + xmlData[i+4] === 'T' && + xmlData[i+5] === 'I' && + xmlData[i+6] === 'T' && + xmlData[i+7] === 'Y') return true + return false +} +function isElement(xmlData, i){ + if(xmlData[i+1] === '!' && + xmlData[i+2] === 'E' && + xmlData[i+3] === 'L' && + xmlData[i+4] === 'E' && + xmlData[i+5] === 'M' && + xmlData[i+6] === 'E' && + xmlData[i+7] === 'N' && + xmlData[i+8] === 'T') return true + return false +} - createDebug.enable(createDebug.load()); +function isAttlist(xmlData, i){ + if(xmlData[i+1] === '!' && + xmlData[i+2] === 'A' && + xmlData[i+3] === 'T' && + xmlData[i+4] === 'T' && + xmlData[i+5] === 'L' && + xmlData[i+6] === 'I' && + xmlData[i+7] === 'S' && + xmlData[i+8] === 'T') return true + return false +} +function isNotation(xmlData, i){ + if(xmlData[i+1] === '!' && + xmlData[i+2] === 'N' && + xmlData[i+3] === 'O' && + xmlData[i+4] === 'T' && + xmlData[i+5] === 'A' && + xmlData[i+6] === 'T' && + xmlData[i+7] === 'I' && + xmlData[i+8] === 'O' && + xmlData[i+9] === 'N') return true + return false +} - return createDebug; +function validateEntityName(name){ + if (util.isName(name)) + return name; + else + throw new Error(`Invalid entity name ${name}`); } -module.exports = setup; +module.exports = readDocType; /***/ }), -/***/ 38237: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 86993: +/***/ ((__unused_webpack_module, exports) => { -/** - * 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__(28222); -} else { - module.exports = __nccwpck_require__(35332); -} +const defaultOptions = { + preserveOrder: false, + attributeNamePrefix: '@_', + attributesGroupName: false, + textNodeName: '#text', + ignoreAttributes: true, + removeNSPrefix: false, // remove NS from tag name or attribute name if true + allowBooleanAttributes: false, //a tag can have attributes without any value + //ignoreRootElement : false, + parseTagValue: true, + parseAttributeValue: false, + trimValues: true, //Trim string values of tag and attributes + cdataPropName: false, + numberParseOptions: { + hex: true, + leadingZeros: true, + eNotation: true + }, + tagValueProcessor: function(tagName, val) { + return val; + }, + attributeValueProcessor: function(attrName, val) { + return val; + }, + stopNodes: [], //nested tags will not be parsed even for errors + alwaysCreateTextNode: false, + isArray: () => false, + commentPropName: false, + unpairedTags: [], + processEntities: true, + htmlEntities: false, + ignoreDeclaration: false, + ignorePiTags: false, + transformTagName: false, + transformAttributeName: false, + updateTag: function(tagName, jPath, attrs){ + return tagName + }, + // skipEmptyListItem: false +}; + +const buildOptions = function(options) { + return Object.assign({}, defaultOptions, options); +}; +exports.buildOptions = buildOptions; +exports.defaultOptions = defaultOptions; /***/ }), -/***/ 35332: -/***/ ((module, exports, __nccwpck_require__) => { - -/** - * Module dependencies. - */ +/***/ 25832: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const tty = __nccwpck_require__(76224); -const util = __nccwpck_require__(73837); +"use strict"; -/** - * This is the Node.js implementation of `debug()`. - */ +///@ts-check -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`.' -); +const util = __nccwpck_require__(38280); +const xmlNode = __nccwpck_require__(7462); +const readDocType = __nccwpck_require__(6072); +const toNumber = __nccwpck_require__(14526); -/** - * Colors. - */ +// const regx = +// '<((!\\[CDATA\\[([\\s\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\/)(NAME)\\s*>))([^<]*)' +// .replace(/NAME/g, util.nameRegexp); -exports.colors = [6, 2, 3, 4, 5, 1]; +//const tagsRegx = new RegExp("<(\\/?[\\w:\\-\._]+)([^>]*)>(\\s*"+cdataRegx+")*([^<]+)?","g"); +//const tagsRegx = new RegExp("<(\\/?)((\\w*:)?([\\w:\\-\._]+))([^>]*)>([^<]*)("+cdataRegx+"([^<]*))*([^<]+)?","g"); -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__(59318); +class OrderedObjParser{ + constructor(options){ + this.options = options; + this.currentNode = null; + this.tagsNodeStack = []; + this.docTypeEntities = {}; + this.lastEntities = { + "apos" : { regex: /&(apos|#39|#x27);/g, val : "'"}, + "gt" : { regex: /&(gt|#62|#x3E);/g, val : ">"}, + "lt" : { regex: /&(lt|#60|#x3C);/g, val : "<"}, + "quot" : { regex: /&(quot|#34|#x22);/g, val : "\""}, + }; + this.ampEntity = { regex: /&(amp|#38|#x26);/g, val : "&"}; + this.htmlEntities = { + "space": { regex: /&(nbsp|#160);/g, val: " " }, + // "lt" : { regex: /&(lt|#60);/g, val: "<" }, + // "gt" : { regex: /&(gt|#62);/g, val: ">" }, + // "amp" : { regex: /&(amp|#38);/g, val: "&" }, + // "quot" : { regex: /&(quot|#34);/g, val: "\"" }, + // "apos" : { regex: /&(apos|#39);/g, val: "'" }, + "cent" : { regex: /&(cent|#162);/g, val: "¢" }, + "pound" : { regex: /&(pound|#163);/g, val: "£" }, + "yen" : { regex: /&(yen|#165);/g, val: "¥" }, + "euro" : { regex: /&(euro|#8364);/g, val: "€" }, + "copyright" : { regex: /&(copy|#169);/g, val: "©" }, + "reg" : { regex: /&(reg|#174);/g, val: "®" }, + "inr" : { regex: /&(inr|#8377);/g, val: "₹" }, + "num_dec": { regex: /&#([0-9]{1,7});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 10)) }, + "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 16)) }, + }; + this.addExternalEntities = addExternalEntities; + this.parseXml = parseXml; + this.parseTextData = parseTextData; + this.resolveNameSpace = resolveNameSpace; + this.buildAttributesMap = buildAttributesMap; + this.isItStopNode = isItStopNode; + this.replaceEntitiesValue = replaceEntitiesValue; + this.readStopNodeData = readStopNodeData; + this.saveTextToParentTag = saveTextToParentTag; + this.addChild = addChild; + } - 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. } -/** - * 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(); - }); - - // 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; -}, {}); +function addExternalEntities(externalEntities){ + const entKeys = Object.keys(externalEntities); + for (let i = 0; i < entKeys.length; i++) { + const ent = entKeys[i]; + this.lastEntities[ent] = { + regex: new RegExp("&"+ent+";","g"), + val : externalEntities[ent] + } + } +} /** - * Is stdout a TTY? Colored output is enabled when `true`. + * @param {string} val + * @param {string} tagName + * @param {string} jPath + * @param {boolean} dontTrim + * @param {boolean} hasAttributes + * @param {boolean} isLeafNode + * @param {boolean} escapeEntities */ - -function useColors() { - return 'colors' in exports.inspectOpts ? - Boolean(exports.inspectOpts.colors) : - tty.isatty(process.stderr.fd); +function parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) { + if (val !== undefined) { + if (this.options.trimValues && !dontTrim) { + val = val.trim(); + } + if(val.length > 0){ + if(!escapeEntities) val = this.replaceEntitiesValue(val); + + const newval = this.options.tagValueProcessor(tagName, val, jPath, hasAttributes, isLeafNode); + if(newval === null || newval === undefined){ + //don't parse + return val; + }else if(typeof newval !== typeof val || newval !== val){ + //overwrite + return newval; + }else if(this.options.trimValues){ + return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions); + }else{ + const trimmedVal = val.trim(); + if(trimmedVal === val){ + return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions); + }else{ + return val; + } + } + } + } } -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ +function resolveNameSpace(tagname) { + if (this.options.removeNSPrefix) { + const tags = tagname.split(':'); + const prefix = tagname.charAt(0) === '/' ? '/' : ''; + if (tags[0] === 'xmlns') { + return ''; + } + if (tags.length === 2) { + tagname = prefix + tags[1]; + } + } + return tagname; +} -function formatArgs(args) { - const {namespace: name, useColors} = this; +//TODO: change regex to capture NS +//const attrsRegx = new RegExp("([\\w\\-\\.\\:]+)\\s*=\\s*(['\"])((.|\n)*?)\\2","gm"); +const attrsRegx = new RegExp('([^\\s=]+)\\s*(=\\s*([\'"])([\\s\\S]*?)\\3)?', 'gm'); - if (useColors) { - const c = this.color; - const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); - const prefix = ` ${colorCode};1m${name} \u001B[0m`; +function buildAttributesMap(attrStr, jPath, tagName) { + if (!this.options.ignoreAttributes && typeof attrStr === 'string') { + // attrStr = attrStr.replace(/\r?\n/g, ' '); + //attrStr = attrStr || attrStr.trim(); - 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]; - } + const matches = util.getAllMatches(attrStr, attrsRegx); + const len = matches.length; //don't make it inline + const attrs = {}; + for (let i = 0; i < len; i++) { + const attrName = this.resolveNameSpace(matches[i][1]); + let oldVal = matches[i][4]; + let aName = this.options.attributeNamePrefix + attrName; + if (attrName.length) { + if (this.options.transformAttributeName) { + aName = this.options.transformAttributeName(aName); + } + if(aName === "__proto__") aName = "#__proto__"; + if (oldVal !== undefined) { + if (this.options.trimValues) { + oldVal = oldVal.trim(); + } + oldVal = this.replaceEntitiesValue(oldVal); + const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath); + if(newVal === null || newVal === undefined){ + //don't parse + attrs[aName] = oldVal; + }else if(typeof newVal !== typeof oldVal || newVal !== oldVal){ + //overwrite + attrs[aName] = newVal; + }else{ + //parse + attrs[aName] = parseValue( + oldVal, + this.options.parseAttributeValue, + this.options.numberParseOptions + ); + } + } else if (this.options.allowBooleanAttributes) { + attrs[aName] = true; + } + } + } + if (!Object.keys(attrs).length) { + return; + } + if (this.options.attributesGroupName) { + const attrCollection = {}; + attrCollection[this.options.attributesGroupName] = attrs; + return attrCollection; + } + return attrs + } } -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } - return new Date().toISOString() + ' '; -} +const parseXml = function(xmlData) { + xmlData = xmlData.replace(/\r\n?/g, "\n"); //TODO: remove this line + const xmlObj = new xmlNode('!xml'); + let currentNode = xmlObj; + let textData = ""; + let jPath = ""; + for(let i=0; i< xmlData.length; i++){//for each char in XML data + const ch = xmlData[i]; + if(ch === '<'){ + // const nextIndex = i+1; + // const _2ndChar = xmlData[nextIndex]; + if( xmlData[i+1] === '/') {//Closing Tag + const closeIndex = findClosingIndex(xmlData, ">", i, "Closing Tag is not closed.") + let tagName = xmlData.substring(i+2,closeIndex).trim(); -/** - * Invokes `util.format()` with the specified arguments and writes to stderr. - */ + if(this.options.removeNSPrefix){ + const colonIndex = tagName.indexOf(":"); + if(colonIndex !== -1){ + tagName = tagName.substr(colonIndex+1); + } + } -function log(...args) { - return process.stderr.write(util.format(...args) + '\n'); -} + if(this.options.transformTagName) { + tagName = this.options.transformTagName(tagName); + } -/** - * 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(currentNode){ + textData = this.saveTextToParentTag(textData, currentNode, jPath); + } -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ + //check if last tag of nested tag was unpaired tag + const lastTagName = jPath.substring(jPath.lastIndexOf(".")+1); + if(tagName && this.options.unpairedTags.indexOf(tagName) !== -1 ){ + throw new Error(`Unpaired tag can not be used as closing tag: `); + } + let propIndex = 0 + if(lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1 ){ + propIndex = jPath.lastIndexOf('.', jPath.lastIndexOf('.')-1) + this.tagsNodeStack.pop(); + }else{ + propIndex = jPath.lastIndexOf("."); + } + jPath = jPath.substring(0, propIndex); -function load() { - return process.env.DEBUG; -} + currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope + textData = ""; + i = closeIndex; + } else if( xmlData[i+1] === '?') { -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ + let tagData = readTagExp(xmlData,i, false, "?>"); + if(!tagData) throw new Error("Pi Tag is not closed."); -function init(debug) { - debug.inspectOpts = {}; + textData = this.saveTextToParentTag(textData, currentNode, jPath); + if( (this.options.ignoreDeclaration && tagData.tagName === "?xml") || this.options.ignorePiTags){ - const keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} + }else{ + + const childNode = new xmlNode(tagData.tagName); + childNode.add(this.options.textNodeName, ""); + + if(tagData.tagName !== tagData.tagExp && tagData.attrExpPresent){ + childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName); + } + this.addChild(currentNode, childNode, jPath) -module.exports = __nccwpck_require__(46243)(exports); + } -const {formatters} = module.exports; -/** - * Map %o to `util.inspect()`, all on a single line. - */ + i = tagData.closeIndex + 1; + } else if(xmlData.substr(i + 1, 3) === '!--') { + const endIndex = findClosingIndex(xmlData, "-->", i+4, "Comment is not closed.") + if(this.options.commentPropName){ + const comment = xmlData.substring(i + 4, endIndex - 2); -formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n') - .map(str => str.trim()) - .join(' '); -}; + textData = this.saveTextToParentTag(textData, currentNode, jPath); -/** - * Map %O to `util.inspect()`, allowing multiple lines if needed. - */ + currentNode.add(this.options.commentPropName, [ { [this.options.textNodeName] : comment } ]); + } + i = endIndex; + } else if( xmlData.substr(i + 1, 2) === '!D') { + const result = readDocType(xmlData, i); + this.docTypeEntities = result.entities; + i = result.i; + }else if(xmlData.substr(i + 1, 2) === '![') { + const closeIndex = findClosingIndex(xmlData, "]]>", i, "CDATA is not closed.") - 2; + const tagExp = xmlData.substring(i + 9,closeIndex); -formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; + textData = this.saveTextToParentTag(textData, currentNode, jPath); + let val = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true); + if(val == undefined) val = ""; -/***/ }), + //cdata should be set even if it is 0 length string + if(this.options.cdataPropName){ + currentNode.add(this.options.cdataPropName, [ { [this.options.textNodeName] : tagExp } ]); + }else{ + currentNode.add(this.options.textNodeName, val); + } + + i = closeIndex + 2; + }else {//Opening tag + let result = readTagExp(xmlData,i, this.options.removeNSPrefix); + let tagName= result.tagName; + const rawTagName = result.rawTagName; + let tagExp = result.tagExp; + let attrExpPresent = result.attrExpPresent; + let closeIndex = result.closeIndex; -/***/ 18611: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (this.options.transformTagName) { + tagName = this.options.transformTagName(tagName); + } + + //save text as child node + if (currentNode && textData) { + if(currentNode.tagname !== '!xml'){ + //when nested tag is found + textData = this.saveTextToParentTag(textData, currentNode, jPath, false); + } + } -var Stream = (__nccwpck_require__(12781).Stream); -var util = __nccwpck_require__(73837); + //check if last tag was unpaired tag + const lastTag = currentNode; + if(lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1 ){ + currentNode = this.tagsNodeStack.pop(); + jPath = jPath.substring(0, jPath.lastIndexOf(".")); + } + if(tagName !== xmlObj.tagname){ + jPath += jPath ? "." + tagName : tagName; + } + if (this.isItStopNode(this.options.stopNodes, jPath, tagName)) { + let tagContent = ""; + //self-closing tag + if(tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1){ + if(tagName[tagName.length - 1] === "/"){ //remove trailing '/' + tagName = tagName.substr(0, tagName.length - 1); + jPath = jPath.substr(0, jPath.length - 1); + tagExp = tagName; + }else{ + tagExp = tagExp.substr(0, tagExp.length - 1); + } + i = result.closeIndex; + } + //unpaired tag + else if(this.options.unpairedTags.indexOf(tagName) !== -1){ + + i = result.closeIndex; + } + //normal tag + else{ + //read until closing tag is found + const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1); + if(!result) throw new Error(`Unexpected end of ${rawTagName}`); + i = result.i; + tagContent = result.tagContent; + } -module.exports = DelayedStream; -function DelayedStream() { - this.source = null; - this.dataSize = 0; - this.maxDataSize = 1024 * 1024; - this.pauseStream = true; + const childNode = new xmlNode(tagName); + if(tagName !== tagExp && attrExpPresent){ + childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); + } + if(tagContent) { + tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true); + } + + jPath = jPath.substr(0, jPath.lastIndexOf(".")); + childNode.add(this.options.textNodeName, tagContent); + + this.addChild(currentNode, childNode, jPath) + }else{ + //selfClosing tag + if(tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1){ + if(tagName[tagName.length - 1] === "/"){ //remove trailing '/' + tagName = tagName.substr(0, tagName.length - 1); + jPath = jPath.substr(0, jPath.length - 1); + tagExp = tagName; + }else{ + tagExp = tagExp.substr(0, tagExp.length - 1); + } + + if(this.options.transformTagName) { + tagName = this.options.transformTagName(tagName); + } - this._maxDataSizeExceeded = false; - this._released = false; - this._bufferedEvents = []; + const childNode = new xmlNode(tagName); + if(tagName !== tagExp && attrExpPresent){ + childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); + } + this.addChild(currentNode, childNode, jPath) + jPath = jPath.substr(0, jPath.lastIndexOf(".")); + } + //opening tag + else{ + const childNode = new xmlNode( tagName); + this.tagsNodeStack.push(currentNode); + + if(tagName !== tagExp && attrExpPresent){ + childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); + } + this.addChild(currentNode, childNode, jPath) + currentNode = childNode; + } + textData = ""; + i = closeIndex; + } + } + }else{ + textData += xmlData[i]; + } + } + return xmlObj.child; } -util.inherits(DelayedStream, Stream); -DelayedStream.create = function(source, options) { - var delayedStream = new this(); +function addChild(currentNode, childNode, jPath){ + const result = this.options.updateTag(childNode.tagname, jPath, childNode[":@"]) + if(result === false){ + }else if(typeof result === "string"){ + childNode.tagname = result + currentNode.addChild(childNode); + }else{ + currentNode.addChild(childNode); + } +} - options = options || {}; - for (var option in options) { - delayedStream[option] = options[option]; +const replaceEntitiesValue = function(val){ + + if(this.options.processEntities){ + for(let entityName in this.docTypeEntities){ + const entity = this.docTypeEntities[entityName]; + val = val.replace( entity.regx, entity.val); + } + for(let entityName in this.lastEntities){ + const entity = this.lastEntities[entityName]; + val = val.replace( entity.regex, entity.val); + } + if(this.options.htmlEntities){ + for(let entityName in this.htmlEntities){ + const entity = this.htmlEntities[entityName]; + val = val.replace( entity.regex, entity.val); + } + } + val = val.replace( this.ampEntity.regex, this.ampEntity.val); } + return val; +} +function saveTextToParentTag(textData, currentNode, jPath, isLeafNode) { + if (textData) { //store previously collected data as textNode + if(isLeafNode === undefined) isLeafNode = Object.keys(currentNode.child).length === 0 + + textData = this.parseTextData(textData, + currentNode.tagname, + jPath, + false, + currentNode[":@"] ? Object.keys(currentNode[":@"]).length !== 0 : false, + isLeafNode); - delayedStream.source = source; + if (textData !== undefined && textData !== "") + currentNode.add(this.options.textNodeName, textData); + textData = ""; + } + return textData; +} - var realEmit = source.emit; - source.emit = function() { - delayedStream._handleEmit(arguments); - return realEmit.apply(source, arguments); - }; +//TODO: use jPath to simplify the logic +/** + * + * @param {string[]} stopNodes + * @param {string} jPath + * @param {string} currentTagName + */ +function isItStopNode(stopNodes, jPath, currentTagName){ + const allNodesExp = "*." + currentTagName; + for (const stopNodePath in stopNodes) { + const stopNodeExp = stopNodes[stopNodePath]; + if( allNodesExp === stopNodeExp || jPath === stopNodeExp ) return true; + } + return false; +} - source.on('error', function() {}); - if (delayedStream.pauseStream) { - source.pause(); +/** + * Returns the tag Expression and where it is ending handling single-double quotes situation + * @param {string} xmlData + * @param {number} i starting index + * @returns + */ +function tagExpWithClosingIndex(xmlData, i, closingChar = ">"){ + let attrBoundary; + let tagExp = ""; + for (let index = i; index < xmlData.length; index++) { + let ch = xmlData[index]; + if (attrBoundary) { + if (ch === attrBoundary) attrBoundary = "";//reset + } else if (ch === '"' || ch === "'") { + attrBoundary = ch; + } else if (ch === closingChar[0]) { + if(closingChar[1]){ + if(xmlData[index + 1] === closingChar[1]){ + return { + data: tagExp, + index: index + } + } + }else{ + return { + data: tagExp, + index: index + } + } + } else if (ch === '\t') { + ch = " " + } + tagExp += ch; } +} - return delayedStream; -}; +function findClosingIndex(xmlData, str, i, errMsg){ + const closingIndex = xmlData.indexOf(str, i); + if(closingIndex === -1){ + throw new Error(errMsg) + }else{ + return closingIndex + str.length - 1; + } +} -Object.defineProperty(DelayedStream.prototype, 'readable', { - configurable: true, - enumerable: true, - get: function() { - return this.source.readable; +function readTagExp(xmlData,i, removeNSPrefix, closingChar = ">"){ + const result = tagExpWithClosingIndex(xmlData, i+1, closingChar); + if(!result) return; + let tagExp = result.data; + const closeIndex = result.index; + const separatorIndex = tagExp.search(/\s/); + let tagName = tagExp; + let attrExpPresent = true; + if(separatorIndex !== -1){//separate tag name and attributes expression + tagName = tagExp.substring(0, separatorIndex); + tagExp = tagExp.substring(separatorIndex + 1).trimStart(); } -}); -DelayedStream.prototype.setEncoding = function() { - return this.source.setEncoding.apply(this.source, arguments); -}; + const rawTagName = tagName; + if(removeNSPrefix){ + const colonIndex = tagName.indexOf(":"); + if(colonIndex !== -1){ + tagName = tagName.substr(colonIndex+1); + attrExpPresent = tagName !== result.data.substr(colonIndex + 1); + } + } -DelayedStream.prototype.resume = function() { - if (!this._released) { - this.release(); + return { + tagName: tagName, + tagExp: tagExp, + closeIndex: closeIndex, + attrExpPresent: attrExpPresent, + rawTagName: rawTagName, } +} +/** + * find paired tag for a stop node + * @param {string} xmlData + * @param {string} tagName + * @param {number} i + */ +function readStopNodeData(xmlData, tagName, i){ + const startIndex = i; + // Starting at 1 since we already have an open tag + let openTagCount = 1; - this.source.resume(); -}; + for (; i < xmlData.length; i++) { + if( xmlData[i] === "<"){ + if (xmlData[i+1] === "/") {//close tag + const closeIndex = findClosingIndex(xmlData, ">", i, `${tagName} is not closed`); + let closeTagName = xmlData.substring(i+2,closeIndex).trim(); + if(closeTagName === tagName){ + openTagCount--; + if (openTagCount === 0) { + return { + tagContent: xmlData.substring(startIndex, i), + i : closeIndex + } + } + } + i=closeIndex; + } else if(xmlData[i+1] === '?') { + const closeIndex = findClosingIndex(xmlData, "?>", i+1, "StopNode is not closed.") + i=closeIndex; + } else if(xmlData.substr(i + 1, 3) === '!--') { + const closeIndex = findClosingIndex(xmlData, "-->", i+3, "StopNode is not closed.") + i=closeIndex; + } else if(xmlData.substr(i + 1, 2) === '![') { + const closeIndex = findClosingIndex(xmlData, "]]>", i, "StopNode is not closed.") - 2; + i=closeIndex; + } else { + const tagData = readTagExp(xmlData, i, '>') -DelayedStream.prototype.pause = function() { - this.source.pause(); -}; + if (tagData) { + const openTagName = tagData && tagData.tagName; + if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length-1] !== "/") { + openTagCount++; + } + i=tagData.closeIndex; + } + } + } + }//end for loop +} -DelayedStream.prototype.release = function() { - this._released = true; +function parseValue(val, shouldParse, options) { + if (shouldParse && typeof val === 'string') { + //console.log(options) + const newval = val.trim(); + if(newval === 'true' ) return true; + else if(newval === 'false' ) return false; + else return toNumber(val, options); + } else { + if (util.isExist(val)) { + return val; + } else { + return ''; + } + } +} - this._bufferedEvents.forEach(function(args) { - this.emit.apply(this, args); - }.bind(this)); - this._bufferedEvents = []; -}; -DelayedStream.prototype.pipe = function() { - var r = Stream.prototype.pipe.apply(this, arguments); - this.resume(); - return r; -}; +module.exports = OrderedObjParser; -DelayedStream.prototype._handleEmit = function(args) { - if (this._released) { - this.emit.apply(this, args); - return; - } - if (args[0] === 'data') { - this.dataSize += args[1].length; - this._checkIfMaxDataSizeExceeded(); - } +/***/ }), - this._bufferedEvents.push(args); -}; +/***/ 42380: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { - if (this._maxDataSizeExceeded) { - return; - } +const { buildOptions} = __nccwpck_require__(86993); +const OrderedObjParser = __nccwpck_require__(25832); +const { prettify} = __nccwpck_require__(42882); +const validator = __nccwpck_require__(61739); - if (this.dataSize <= this.maxDataSize) { - return; - } +class XMLParser{ + + constructor(options){ + this.externalEntities = {}; + this.options = buildOptions(options); + + } + /** + * Parse XML dats to JS object + * @param {string|Buffer} xmlData + * @param {boolean|Object} validationOption + */ + parse(xmlData,validationOption){ + if(typeof xmlData === "string"){ + }else if( xmlData.toString){ + xmlData = xmlData.toString(); + }else{ + throw new Error("XML data is accepted in String or Bytes[] form.") + } + if( validationOption){ + if(validationOption === true) validationOption = {}; //validate with default options + + const result = validator.validate(xmlData, validationOption); + if (result !== true) { + throw Error( `${result.err.msg}:${result.err.line}:${result.err.col}` ) + } + } + const orderedObjParser = new OrderedObjParser(this.options); + orderedObjParser.addExternalEntities(this.externalEntities); + const orderedResult = orderedObjParser.parseXml(xmlData); + if(this.options.preserveOrder || orderedResult === undefined) return orderedResult; + else return prettify(orderedResult, this.options); + } - this._maxDataSizeExceeded = true; - var message = - 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' - this.emit('error', new Error(message)); -}; + /** + * Add Entity which is not by default supported by this library + * @param {string} key + * @param {string} value + */ + addEntity(key, value){ + if(value.indexOf("&") !== -1){ + throw new Error("Entity value can't have '&'") + }else if(key.indexOf("&") !== -1 || key.indexOf(";") !== -1){ + throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for ' '") + }else if(value === "&"){ + throw new Error("An entity with value '&' is not permitted"); + }else{ + this.externalEntities[key] = value; + } + } +} +module.exports = XMLParser; /***/ }), -/***/ 58932: +/***/ 42882: /***/ ((__unused_webpack_module, exports) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); +/** + * + * @param {array} node + * @param {any} options + * @returns + */ +function prettify(node, options){ + return compress( node, options); +} -class Deprecation extends Error { - constructor(message) { - super(message); // Maintains proper stack trace (only available on V8) +/** + * + * @param {array} arr + * @param {object} options + * @param {string} jPath + * @returns object + */ +function compress(arr, options, jPath){ + let text; + const compressedObj = {}; + for (let i = 0; i < arr.length; i++) { + const tagObj = arr[i]; + const property = propName(tagObj); + let newJpath = ""; + if(jPath === undefined) newJpath = property; + else newJpath = jPath + "." + property; - /* istanbul ignore next */ + if(property === options.textNodeName){ + if(text === undefined) text = tagObj[property]; + else text += "" + tagObj[property]; + }else if(property === undefined){ + continue; + }else if(tagObj[property]){ + + let val = compress(tagObj[property], options, newJpath); + const isLeaf = isLeafTag(val, options); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); + if(tagObj[":@"]){ + assignAttributes( val, tagObj[":@"], newJpath, options); + }else if(Object.keys(val).length === 1 && val[options.textNodeName] !== undefined && !options.alwaysCreateTextNode){ + val = val[options.textNodeName]; + }else if(Object.keys(val).length === 0){ + if(options.alwaysCreateTextNode) val[options.textNodeName] = ""; + else val = ""; + } + + if(compressedObj[property] !== undefined && compressedObj.hasOwnProperty(property)) { + if(!Array.isArray(compressedObj[property])) { + compressedObj[property] = [ compressedObj[property] ]; + } + compressedObj[property].push(val); + }else{ + //TODO: if a node is not an array, then check if it should be an array + //also determine if it is a leaf node + if (options.isArray(property, newJpath, isLeaf )) { + compressedObj[property] = [val]; + }else{ + compressedObj[property] = val; + } + } } + + } + // if(text && text.length > 0) compressedObj[options.textNodeName] = text; + if(typeof text === "string"){ + if(text.length > 0) compressedObj[options.textNodeName] = text; + }else if(text !== undefined) compressedObj[options.textNodeName] = text; + return compressedObj; +} - this.name = 'Deprecation'; +function propName(obj){ + const keys = Object.keys(obj); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + if(key !== ":@") return key; } +} +function assignAttributes(obj, attrMap, jpath, options){ + if (attrMap) { + const keys = Object.keys(attrMap); + const len = keys.length; //don't make it inline + for (let i = 0; i < len; i++) { + const atrrName = keys[i]; + if (options.isArray(atrrName, jpath + "." + atrrName, true, true)) { + obj[atrrName] = [ attrMap[atrrName] ]; + } else { + obj[atrrName] = attrMap[atrrName]; + } + } + } } -exports.Deprecation = Deprecation; +function isLeafTag(obj, options){ + const { textNodeName } = options; + const propCount = Object.keys(obj).length; + + if (propCount === 0) { + return true; + } + + if ( + propCount === 1 && + (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0) + ) { + return true; + } + + return false; +} +exports.prettify = prettify; /***/ }), -/***/ 13598: +/***/ 7462: /***/ ((module) => { "use strict"; -function _process (v, mod) { - var i - var r - - if (typeof mod === 'function') { - r = mod(v) - if (r !== undefined) { - v = r - } - } else if (Array.isArray(mod)) { - for (i = 0; i < mod.length; i++) { - r = mod[i](v) - if (r !== undefined) { - v = r - } - } +class XmlNode{ + constructor(tagname) { + this.tagname = tagname; + this.child = []; //nested tags, text, cdata, comments in order + this[":@"] = {}; //attributes map } - - return v -} - -function parseKey (key, val) { - // detect negative index notation - if (key[0] === '-' && Array.isArray(val) && /^-\d+$/.test(key)) { - return val.length + parseInt(key, 10) + add(key,val){ + // this.child.push( {name : key, val: val, isCdata: isCdata }); + if(key === "__proto__") key = "#__proto__"; + this.child.push( {[key]: val }); } - return key -} + addChild(node) { + if(node.tagname === "__proto__") node.tagname = "#__proto__"; + if(node[":@"] && Object.keys(node[":@"]).length > 0){ + this.child.push( { [node.tagname]: node.child, [":@"]: node[":@"] }); + }else{ + this.child.push( { [node.tagname]: node.child }); + } + }; +}; -function isIndex (k) { - return /^\d+$/.test(k) -} -function isObject (val) { - return Object.prototype.toString.call(val) === '[object Object]' -} +module.exports = XmlNode; -function isArrayOrObject (val) { - return Object(val) === val -} +/***/ }), -function isEmptyObject (val) { - return Object.keys(val).length === 0 -} +/***/ 31133: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var blacklist = ['__proto__', 'prototype', 'constructor'] -var blacklistFilter = function (part) { return blacklist.indexOf(part) === -1 } +var debug; -function parsePath (path, sep) { - if (path.indexOf('[') >= 0) { - path = path.replace(/\[/g, sep).replace(/]/g, '') +module.exports = function () { + if (!debug) { + try { + /* eslint global-require: off */ + debug = __nccwpck_require__(38237)("follow-redirects"); + } + catch (error) { /* */ } + if (typeof debug !== "function") { + debug = function () { /* */ }; + } } + debug.apply(null, arguments); +}; - var parts = path.split(sep) - - var check = parts.filter(blacklistFilter) - if (check.length !== parts.length) { - throw Error('Refusing to update blacklisted property ' + path) - } +/***/ }), - return parts -} +/***/ 67707: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var hasOwnProperty = Object.prototype.hasOwnProperty +var url = __nccwpck_require__(57310); +var URL = url.URL; +var http = __nccwpck_require__(13685); +var https = __nccwpck_require__(95687); +var Writable = (__nccwpck_require__(12781).Writable); +var assert = __nccwpck_require__(39491); +var debug = __nccwpck_require__(31133); -function DotObject (separator, override, useArray, useBrackets) { - if (!(this instanceof DotObject)) { - return new DotObject(separator, override, useArray, useBrackets) +// Preventive platform detection +// istanbul ignore next +(function detectUnsupportedEnvironment() { + var looksLikeNode = typeof process !== "undefined"; + var looksLikeBrowser = typeof window !== "undefined" && typeof document !== "undefined"; + var looksLikeV8 = isFunction(Error.captureStackTrace); + if (!looksLikeNode && (looksLikeBrowser || !looksLikeV8)) { + console.warn("The follow-redirects package should be excluded from browser builds."); } +}()); - if (typeof override === 'undefined') override = false - if (typeof useArray === 'undefined') useArray = true - if (typeof useBrackets === 'undefined') useBrackets = true - this.separator = separator || '.' - this.override = override - this.useArray = useArray - this.useBrackets = useBrackets - this.keepArray = false - - // contains touched arrays - this.cleanup = [] +// Whether to use the native URL object or the legacy url module +var useNativeURL = false; +try { + assert(new URL("")); } - -var dotDefault = new DotObject('.', false, true, true) -function wrap (method) { - return function () { - return dotDefault[method].apply(dotDefault, arguments) - } +catch (error) { + useNativeURL = error.code === "ERR_INVALID_URL"; } -DotObject.prototype._fill = function (a, obj, v, mod) { - var k = a.shift() - - if (a.length > 0) { - obj[k] = obj[k] || (this.useArray && isIndex(a[0]) ? [] : {}) +// URL fields to preserve in copy operations +var preservedUrlFields = [ + "auth", + "host", + "hostname", + "href", + "path", + "pathname", + "port", + "protocol", + "query", + "search", + "hash", +]; - if (!isArrayOrObject(obj[k])) { - if (this.override) { - obj[k] = {} - } else { - if (!(isArrayOrObject(v) && isEmptyObject(v))) { - throw new Error( - 'Trying to redefine `' + k + '` which is a ' + typeof obj[k] - ) - } +// Create handlers that pass events from native requests +var events = ["abort", "aborted", "connect", "error", "socket", "timeout"]; +var eventHandlers = Object.create(null); +events.forEach(function (event) { + eventHandlers[event] = function (arg1, arg2, arg3) { + this._redirectable.emit(event, arg1, arg2, arg3); + }; +}); - return - } - } +// Error types with codes +var InvalidUrlError = createErrorType( + "ERR_INVALID_URL", + "Invalid URL", + TypeError +); +var RedirectionError = createErrorType( + "ERR_FR_REDIRECTION_FAILURE", + "Redirected request failed" +); +var TooManyRedirectsError = createErrorType( + "ERR_FR_TOO_MANY_REDIRECTS", + "Maximum number of redirects exceeded", + RedirectionError +); +var MaxBodyLengthExceededError = createErrorType( + "ERR_FR_MAX_BODY_LENGTH_EXCEEDED", + "Request body larger than maxBodyLength limit" +); +var WriteAfterEndError = createErrorType( + "ERR_STREAM_WRITE_AFTER_END", + "write after end" +); - this._fill(a, obj[k], v, mod) - } else { - if (!this.override && isArrayOrObject(obj[k]) && !isEmptyObject(obj[k])) { - if (!(isArrayOrObject(v) && isEmptyObject(v))) { - throw new Error("Trying to redefine non-empty obj['" + k + "']") - } +// istanbul ignore next +var destroy = Writable.prototype.destroy || noop; - return - } +// An HTTP(S) request that can be redirected +function RedirectableRequest(options, responseCallback) { + // Initialize the request + Writable.call(this); + this._sanitizeOptions(options); + this._options = options; + this._ended = false; + this._ending = false; + this._redirectCount = 0; + this._redirects = []; + this._requestBodyLength = 0; + this._requestBodyBuffers = []; - obj[k] = _process(v, mod) + // Attach a callback if passed + if (responseCallback) { + this.on("response", responseCallback); } -} - -/** - * - * Converts an object with dotted-key/value pairs to it's expanded version - * - * Optionally transformed by a set of modifiers. - * - * Usage: - * - * var row = { - * 'nr': 200, - * 'doc.name': ' My Document ' - * } - * - * var mods = { - * 'doc.name': [_s.trim, _s.underscored] - * } - * - * dot.object(row, mods) - * - * @param {Object} obj - * @param {Object} mods - */ -DotObject.prototype.object = function (obj, mods) { - var self = this - - Object.keys(obj).forEach(function (k) { - var mod = mods === undefined ? null : mods[k] - // normalize array notation. - var ok = parsePath(k, self.separator).join(self.separator) - if (ok.indexOf(self.separator) !== -1) { - self._fill(ok.split(self.separator), obj, obj[k], mod) - delete obj[k] - } else { - obj[k] = _process(obj[k], mod) + // React to responses of native requests + var self = this; + this._onNativeResponse = function (response) { + try { + self._processResponse(response); } - }) + catch (cause) { + self.emit("error", cause instanceof RedirectionError ? + cause : new RedirectionError({ cause: cause })); + } + }; - return obj + // Perform the first request + this._performRequest(); } +RedirectableRequest.prototype = Object.create(Writable.prototype); -/** - * @param {String} path dotted path - * @param {String} v value to be set - * @param {Object} obj object to be modified - * @param {Function|Array} mod optional modifier - */ -DotObject.prototype.str = function (path, v, obj, mod) { - var ok = parsePath(path, this.separator).join(this.separator) - - if (path.indexOf(this.separator) !== -1) { - this._fill(ok.split(this.separator), obj, v, mod) - } else { - obj[path] = _process(v, mod) - } +RedirectableRequest.prototype.abort = function () { + destroyRequest(this._currentRequest); + this._currentRequest.abort(); + this.emit("abort"); +}; - return obj -} +RedirectableRequest.prototype.destroy = function (error) { + destroyRequest(this._currentRequest, error); + destroy.call(this, error); + return this; +}; -/** - * - * Pick a value from an object using dot notation. - * - * Optionally remove the value - * - * @param {String} path - * @param {Object} obj - * @param {Boolean} remove - */ -DotObject.prototype.pick = function (path, obj, remove, reindexArray) { - var i - var keys - var val - var key - var cp +// Writes buffered data to the current native request +RedirectableRequest.prototype.write = function (data, encoding, callback) { + // Writing is not allowed if end has been called + if (this._ending) { + throw new WriteAfterEndError(); + } - keys = parsePath(path, this.separator) - for (i = 0; i < keys.length; i++) { - key = parseKey(keys[i], obj) - if (obj && typeof obj === 'object' && key in obj) { - if (i === keys.length - 1) { - if (remove) { - val = obj[key] - if (reindexArray && Array.isArray(obj)) { - obj.splice(key, 1) - } else { - delete obj[key] - } - if (Array.isArray(obj)) { - cp = keys.slice(0, -1).join('.') - if (this.cleanup.indexOf(cp) === -1) { - this.cleanup.push(cp) - } - } - return val - } else { - return obj[key] - } - } else { - obj = obj[key] - } - } else { - return undefined - } + // Validate input and shift parameters if necessary + if (!isString(data) && !isBuffer(data)) { + throw new TypeError("data should be a string, Buffer or Uint8Array"); } - if (remove && Array.isArray(obj)) { - obj = obj.filter(function (n) { - return n !== undefined - }) + if (isFunction(encoding)) { + callback = encoding; + encoding = null; } - return obj -} -/** - * - * Delete value from an object using dot notation. - * - * @param {String} path - * @param {Object} obj - * @return {any} The removed value - */ -DotObject.prototype.delete = function (path, obj) { - return this.remove(path, obj, true) -} - -/** - * - * Remove value from an object using dot notation. - * - * Will remove multiple items if path is an array. - * In this case array indexes will be retained until all - * removals have been processed. - * - * Use dot.delete() to automatically re-index arrays. - * - * @param {String|Array} path - * @param {Object} obj - * @param {Boolean} reindexArray - * @return {any} The removed value - */ -DotObject.prototype.remove = function (path, obj, reindexArray) { - var i - this.cleanup = [] - if (Array.isArray(path)) { - for (i = 0; i < path.length; i++) { - this.pick(path[i], obj, true, reindexArray) - } - if (!reindexArray) { - this._cleanup(obj) + // Ignore empty buffers, since writing them doesn't invoke the callback + // https://github.com/nodejs/node/issues/22066 + if (data.length === 0) { + if (callback) { + callback(); } - return obj - } else { - return this.pick(path, obj, true, reindexArray) + return; } -} - -DotObject.prototype._cleanup = function (obj) { - var ret - var i - var keys - var root - if (this.cleanup.length) { - for (i = 0; i < this.cleanup.length; i++) { - keys = this.cleanup[i].split('.') - root = keys.splice(0, -1).join('.') - ret = root ? this.pick(root, obj) : obj - ret = ret[keys[0]].filter(function (v) { - return v !== undefined - }) - this.set(this.cleanup[i], ret, obj) - } - this.cleanup = [] + // Only write when we don't exceed the maximum body length + if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { + this._requestBodyLength += data.length; + this._requestBodyBuffers.push({ data: data, encoding: encoding }); + this._currentRequest.write(data, encoding, callback); } -} + // Error when we exceed the maximum body length + else { + this.emit("error", new MaxBodyLengthExceededError()); + this.abort(); + } +}; -/** - * Alias method for `dot.remove` - * - * Note: this is not an alias for dot.delete() - * - * @param {String|Array} path - * @param {Object} obj - * @param {Boolean} reindexArray - * @return {any} The removed value - */ -DotObject.prototype.del = DotObject.prototype.remove +// Ends the current native request +RedirectableRequest.prototype.end = function (data, encoding, callback) { + // Shift parameters if necessary + if (isFunction(data)) { + callback = data; + data = encoding = null; + } + else if (isFunction(encoding)) { + callback = encoding; + encoding = null; + } -/** - * - * Move a property from one place to the other. - * - * If the source path does not exist (undefined) - * the target property will not be set. - * - * @param {String} source - * @param {String} target - * @param {Object} obj - * @param {Function|Array} mods - * @param {Boolean} merge - */ -DotObject.prototype.move = function (source, target, obj, mods, merge) { - if (typeof mods === 'function' || Array.isArray(mods)) { - this.set(target, _process(this.pick(source, obj, true), mods), obj, merge) - } else { - merge = mods - this.set(target, this.pick(source, obj, true), obj, merge) + // Write data if needed and end + if (!data) { + this._ended = this._ending = true; + this._currentRequest.end(null, null, callback); + } + else { + var self = this; + var currentRequest = this._currentRequest; + this.write(data, encoding, function () { + self._ended = true; + currentRequest.end(null, null, callback); + }); + this._ending = true; } +}; - return obj -} +// Sets a header value on the current native request +RedirectableRequest.prototype.setHeader = function (name, value) { + this._options.headers[name] = value; + this._currentRequest.setHeader(name, value); +}; -/** - * - * Transfer a property from one object to another object. - * - * If the source path does not exist (undefined) - * the property on the other object will not be set. - * - * @param {String} source - * @param {String} target - * @param {Object} obj1 - * @param {Object} obj2 - * @param {Function|Array} mods - * @param {Boolean} merge - */ -DotObject.prototype.transfer = function ( - source, - target, - obj1, - obj2, - mods, - merge -) { - if (typeof mods === 'function' || Array.isArray(mods)) { - this.set( - target, - _process(this.pick(source, obj1, true), mods), - obj2, - merge - ) - } else { - merge = mods - this.set(target, this.pick(source, obj1, true), obj2, merge) - } +// Clears a header value on the current native request +RedirectableRequest.prototype.removeHeader = function (name) { + delete this._options.headers[name]; + this._currentRequest.removeHeader(name); +}; - return obj2 -} +// Global timeout for all underlying requests +RedirectableRequest.prototype.setTimeout = function (msecs, callback) { + var self = this; -/** - * - * Copy a property from one object to another object. - * - * If the source path does not exist (undefined) - * the property on the other object will not be set. - * - * @param {String} source - * @param {String} target - * @param {Object} obj1 - * @param {Object} obj2 - * @param {Function|Array} mods - * @param {Boolean} merge - */ -DotObject.prototype.copy = function (source, target, obj1, obj2, mods, merge) { - if (typeof mods === 'function' || Array.isArray(mods)) { - this.set( - target, - _process( - // clone what is picked - JSON.parse(JSON.stringify(this.pick(source, obj1, false))), - mods - ), - obj2, - merge - ) - } else { - merge = mods - this.set(target, this.pick(source, obj1, false), obj2, merge) + // Destroys the socket on timeout + function destroyOnTimeout(socket) { + socket.setTimeout(msecs); + socket.removeListener("timeout", socket.destroy); + socket.addListener("timeout", socket.destroy); } - return obj2 -} + // Sets up a timer to trigger a timeout event + function startTimer(socket) { + if (self._timeout) { + clearTimeout(self._timeout); + } + self._timeout = setTimeout(function () { + self.emit("timeout"); + clearTimer(); + }, msecs); + destroyOnTimeout(socket); + } -/** - * - * Set a property on an object using dot notation. - * - * @param {String} path - * @param {any} val - * @param {Object} obj - * @param {Boolean} merge - */ -DotObject.prototype.set = function (path, val, obj, merge) { - var i - var k - var keys - var key + // Stops a timeout from triggering + function clearTimer() { + // Clear the timeout + if (self._timeout) { + clearTimeout(self._timeout); + self._timeout = null; + } - // Do not operate if the value is undefined. - if (typeof val === 'undefined') { - return obj + // Clean up all attached listeners + self.removeListener("abort", clearTimer); + self.removeListener("error", clearTimer); + self.removeListener("response", clearTimer); + self.removeListener("close", clearTimer); + if (callback) { + self.removeListener("timeout", callback); + } + if (!self.socket) { + self._currentRequest.removeListener("socket", startTimer); + } } - keys = parsePath(path, this.separator) - for (i = 0; i < keys.length; i++) { - key = keys[i] - if (i === keys.length - 1) { - if (merge && isObject(val) && isObject(obj[key])) { - for (k in val) { - if (hasOwnProperty.call(val, k)) { - obj[key][k] = val[k] - } - } - } else if (merge && Array.isArray(obj[key]) && Array.isArray(val)) { - for (var j = 0; j < val.length; j++) { - obj[keys[i]].push(val[j]) - } - } else { - obj[key] = val - } - } else if ( - // force the value to be an object - !hasOwnProperty.call(obj, key) || - (!isObject(obj[key]) && !Array.isArray(obj[key])) - ) { - // initialize as array if next key is numeric - if (/^\d+$/.test(keys[i + 1])) { - obj[key] = [] - } else { - obj[key] = {} - } - } - obj = obj[key] + // Attach callback if passed + if (callback) { + this.on("timeout", callback); } - return obj -} -/** - * - * Transform an object - * - * Usage: - * - * var obj = { - * "id": 1, - * "some": { - * "thing": "else" - * } - * } - * - * var transform = { - * "id": "nr", - * "some.thing": "name" - * } - * - * var tgt = dot.transform(transform, obj) - * - * @param {Object} recipe Transform recipe - * @param {Object} obj Object to be transformed - * @param {Array} mods modifiers for the target - */ -DotObject.prototype.transform = function (recipe, obj, tgt) { - obj = obj || {} - tgt = tgt || {} - Object.keys(recipe).forEach( - function (key) { - this.set(recipe[key], this.pick(key, obj), tgt) - }.bind(this) - ) - return tgt -} + // Start the timer if or when the socket is opened + if (this.socket) { + startTimer(this.socket); + } + else { + this._currentRequest.once("socket", startTimer); + } -/** - * - * Convert object to dotted-key/value pair - * - * Usage: - * - * var tgt = dot.dot(obj) - * - * or - * - * var tgt = {} - * dot.dot(obj, tgt) - * - * @param {Object} obj source object - * @param {Object} tgt target object - * @param {Array} path path array (internal) - */ -DotObject.prototype.dot = function (obj, tgt, path) { - tgt = tgt || {} - path = path || [] - var isArray = Array.isArray(obj) + // Clean up on events + this.on("socket", destroyOnTimeout); + this.on("abort", clearTimer); + this.on("error", clearTimer); + this.on("response", clearTimer); + this.on("close", clearTimer); - Object.keys(obj).forEach( - function (key) { - var index = isArray && this.useBrackets ? '[' + key + ']' : key - if ( - isArrayOrObject(obj[key]) && - ((isObject(obj[key]) && !isEmptyObject(obj[key])) || - (Array.isArray(obj[key]) && !this.keepArray && obj[key].length !== 0)) - ) { - if (isArray && this.useBrackets) { - var previousKey = path[path.length - 1] || '' - return this.dot( - obj[key], - tgt, - path.slice(0, -1).concat(previousKey + index) - ) - } else { - return this.dot(obj[key], tgt, path.concat(index)) - } - } else { - if (isArray && this.useBrackets) { - tgt[path.join(this.separator).concat('[' + key + ']')] = obj[key] - } else { - tgt[path.concat(index).join(this.separator)] = obj[key] - } - } - }.bind(this) - ) - return tgt -} + return this; +}; -DotObject.pick = wrap('pick') -DotObject.move = wrap('move') -DotObject.transfer = wrap('transfer') -DotObject.transform = wrap('transform') -DotObject.copy = wrap('copy') -DotObject.object = wrap('object') -DotObject.str = wrap('str') -DotObject.set = wrap('set') -DotObject.delete = wrap('delete') -DotObject.del = DotObject.remove = wrap('remove') -DotObject.dot = wrap('dot'); -['override', 'overwrite'].forEach(function (prop) { - Object.defineProperty(DotObject, prop, { - get: function () { - return dotDefault.override - }, - set: function (val) { - dotDefault.override = !!val - } - }) +// Proxy all other public ClientRequest methods +[ + "flushHeaders", "getHeader", + "setNoDelay", "setSocketKeepAlive", +].forEach(function (method) { + RedirectableRequest.prototype[method] = function (a, b) { + return this._currentRequest[method](a, b); + }; }); -['useArray', 'keepArray', 'useBrackets'].forEach(function (prop) { - Object.defineProperty(DotObject, prop, { - get: function () { - return dotDefault[prop] - }, - set: function (val) { - dotDefault[prop] = val - } - }) -}) -DotObject._process = _process +// Proxy all public ClientRequest properties +["aborted", "connection", "socket"].forEach(function (property) { + Object.defineProperty(RedirectableRequest.prototype, property, { + get: function () { return this._currentRequest[property]; }, + }); +}); -module.exports = DotObject +RedirectableRequest.prototype._sanitizeOptions = function (options) { + // Ensure headers are always present + if (!options.headers) { + options.headers = {}; + } + // Since http.request treats host as an alias of hostname, + // but the url module interprets host as hostname plus port, + // eliminate the host property to avoid confusion. + if (options.host) { + // Use hostname if set, because it has precedence + if (!options.hostname) { + options.hostname = options.host; + } + delete options.host; + } -/***/ }), + // Complete the URL object when necessary + if (!options.pathname && options.path) { + var searchPos = options.path.indexOf("?"); + if (searchPos < 0) { + options.pathname = options.path; + } + else { + options.pathname = options.path.substring(0, searchPos); + options.search = options.path.substring(searchPos); + } + } +}; -/***/ 62693: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +// Executes the next native request (initial or redirect) +RedirectableRequest.prototype._performRequest = function () { + // Load the native protocol + var protocol = this._options.protocol; + var nativeProtocol = this._options.nativeProtocols[protocol]; + if (!nativeProtocol) { + throw new TypeError("Unsupported protocol " + protocol); + } + // If specified, use the agent corresponding to the protocol + // (HTTP and HTTPS use different types of agents) + if (this._options.agents) { + var scheme = protocol.slice(0, -1); + this._options.agent = this._options.agents[scheme]; + } -var callBind = __nccwpck_require__(86815); -var gOPD = __nccwpck_require__(34709); + // Create the native request and set up its event handlers + var request = this._currentRequest = + nativeProtocol.request(this._options, this._onNativeResponse); + request._redirectable = this; + for (var event of events) { + request.on(event, eventHandlers[event]); + } -var hasProtoAccessor; -try { - // eslint-disable-next-line no-extra-parens, no-proto - hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */ ([]).__proto__ === Array.prototype; -} catch (e) { - if (!e || typeof e !== 'object' || !('code' in e) || e.code !== 'ERR_PROTO_ACCESS') { - throw e; - } -} + // RFC7230§5.3.1: When making a request directly to an origin server, […] + // a client MUST send only the absolute path […] as the request-target. + this._currentUrl = /^\//.test(this._options.path) ? + url.format(this._options) : + // When making a request to a proxy, […] + // a client MUST send the target URI in absolute-form […]. + this._options.path; -// eslint-disable-next-line no-extra-parens -var desc = !!hasProtoAccessor && gOPD && gOPD(Object.prototype, /** @type {keyof typeof Object.prototype} */ ('__proto__')); + // End a redirected request + // (The first request must be ended explicitly with RedirectableRequest#end) + if (this._isRedirect) { + // Write the request entity and end + var i = 0; + var self = this; + var buffers = this._requestBodyBuffers; + (function writeNext(error) { + // Only write if this request has not been redirected yet + // istanbul ignore else + if (request === self._currentRequest) { + // Report any write errors + // istanbul ignore if + if (error) { + self.emit("error", error); + } + // Write the next buffer if there are still left + else if (i < buffers.length) { + var buffer = buffers[i++]; + // istanbul ignore else + if (!request.finished) { + request.write(buffer.data, buffer.encoding, writeNext); + } + } + // End the request if `end` has been called on us + else if (self._ended) { + request.end(); + } + } + }()); + } +}; -var $Object = Object; -var $getPrototypeOf = $Object.getPrototypeOf; +// Processes a response from the current native request +RedirectableRequest.prototype._processResponse = function (response) { + // Store the redirected response + var statusCode = response.statusCode; + if (this._options.trackRedirects) { + this._redirects.push({ + url: this._currentUrl, + headers: response.headers, + statusCode: statusCode, + }); + } -/** @type {import('./get')} */ -module.exports = desc && typeof desc.get === 'function' - ? callBind([desc.get]) - : typeof $getPrototypeOf === 'function' - ? /** @type {import('./get')} */ function getDunder(value) { - // eslint-disable-next-line eqeqeq - return $getPrototypeOf(value == null ? value : $Object(value)); - } - : false; + // RFC7231§6.4: The 3xx (Redirection) class of status code indicates + // that further action needs to be taken by the user agent in order to + // fulfill the request. If a Location header field is provided, + // the user agent MAY automatically redirect its request to the URI + // referenced by the Location field value, + // even if the specific status code is not understood. + // If the response is not a redirect; return it as-is + var location = response.headers.location; + if (!location || this._options.followRedirects === false || + statusCode < 300 || statusCode >= 400) { + response.responseUrl = this._currentUrl; + response.redirects = this._redirects; + this.emit("response", response); -/***/ }), + // Clean up + this._requestBodyBuffers = []; + return; + } -/***/ 19185: -/***/ ((module) => { + // The response is a redirect, so abort the current request + destroyRequest(this._currentRequest); + // Discard the remainder of the response to avoid waiting for data + response.destroy(); -"use strict"; + // RFC7231§6.4: A client SHOULD detect and intervene + // in cyclical redirections (i.e., "infinite" redirection loops). + if (++this._redirectCount > this._options.maxRedirects) { + throw new TooManyRedirectsError(); + } + // Store the request headers if applicable + var requestHeaders; + var beforeRedirect = this._options.beforeRedirect; + if (beforeRedirect) { + requestHeaders = Object.assign({ + // The Host header was set by nativeProtocol.request + Host: response.req.getHeader("host"), + }, this._options.headers); + } -/** @type {import('./gOPD')} */ -module.exports = Object.getOwnPropertyDescriptor; + // RFC7231§6.4: Automatic redirection needs to done with + // care for methods not known to be safe, […] + // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change + // the request method from POST to GET for the subsequent request. + var method = this._options.method; + if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || + // RFC7231§6.4.4: The 303 (See Other) status code indicates that + // the server is redirecting the user agent to a different resource […] + // A user agent can perform a retrieval request targeting that URI + // (a GET or HEAD request if using HTTP) […] + (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) { + this._options.method = "GET"; + // Drop a possible entity and headers related to it + this._requestBodyBuffers = []; + removeMatchingHeaders(/^content-/i, this._options.headers); + } + // Drop the Host header, as the redirect might lead to a different host + var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers); -/***/ }), + // If the redirect is relative, carry over the host of the last request + var currentUrlParts = parseUrl(this._currentUrl); + var currentHost = currentHostHeader || currentUrlParts.host; + var currentUrl = /^\w+:/.test(location) ? this._currentUrl : + url.format(Object.assign(currentUrlParts, { host: currentHost })); -/***/ 34709: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Create the redirected request + var redirectUrl = resolveUrl(location, currentUrl); + debug("redirecting to", redirectUrl.href); + this._isRedirect = true; + spreadUrlObject(redirectUrl, this._options); -"use strict"; + // Drop confidential headers when redirecting to a less secure protocol + // or to a different domain that is not a superdomain + if (redirectUrl.protocol !== currentUrlParts.protocol && + redirectUrl.protocol !== "https:" || + redirectUrl.host !== currentHost && + !isSubdomain(redirectUrl.host, currentHost)) { + removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this._options.headers); + } + // Evaluate the beforeRedirect callback + if (isFunction(beforeRedirect)) { + var responseDetails = { + headers: response.headers, + statusCode: statusCode, + }; + var requestDetails = { + url: currentUrl, + method: method, + headers: requestHeaders, + }; + beforeRedirect(this._options, responseDetails, requestDetails); + this._sanitizeOptions(this._options); + } -/** @type {import('.')} */ -var $gOPD = __nccwpck_require__(19185); + // Perform the redirected request + this._performRequest(); +}; -if ($gOPD) { - try { - $gOPD([], 'length'); - } catch (e) { - // IE 8 has a broken gOPD - $gOPD = null; - } -} +// Wraps the key/value object of protocols with redirect functionality +function wrap(protocols) { + // Default settings + var exports = { + maxRedirects: 21, + maxBodyLength: 10 * 1024 * 1024, + }; -module.exports = $gOPD; + // Wrap each protocol + var nativeProtocols = {}; + Object.keys(protocols).forEach(function (scheme) { + var protocol = scheme + ":"; + var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; + var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); + // Executes a request, following redirects + function request(input, options, callback) { + // Parse parameters, ensuring that input is an object + if (isURL(input)) { + input = spreadUrlObject(input); + } + else if (isString(input)) { + input = spreadUrlObject(parseUrl(input)); + } + else { + callback = options; + options = validateUrl(input); + input = { protocol: protocol }; + } + if (isFunction(options)) { + callback = options; + options = null; + } -/***/ }), + // Set defaults + options = Object.assign({ + maxRedirects: exports.maxRedirects, + maxBodyLength: exports.maxBodyLength, + }, input, options); + options.nativeProtocols = nativeProtocols; + if (!isString(options.host) && !isString(options.hostname)) { + options.hostname = "::1"; + } -/***/ 49865: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + assert.equal(options.protocol, protocol, "protocol mismatch"); + debug("options", options); + return new RedirectableRequest(options, callback); + } -var crypto = __nccwpck_require__(6113); -var BigInteger = (__nccwpck_require__(85587).BigInteger); -var ECPointFp = (__nccwpck_require__(3943).ECPointFp); -var Buffer = (__nccwpck_require__(15118).Buffer); -exports.ECCurves = __nccwpck_require__(41452); + // Executes a GET request, following redirects + function get(input, options, callback) { + var wrappedRequest = wrappedProtocol.request(input, options, callback); + wrappedRequest.end(); + return wrappedRequest; + } -// zero prepad -function unstupid(hex,len) -{ - return (hex.length >= len) ? hex : unstupid("0"+hex,len); + // Expose the properties on the wrapped protocol + Object.defineProperties(wrappedProtocol, { + request: { value: request, configurable: true, enumerable: true, writable: true }, + get: { value: get, configurable: true, enumerable: true, writable: true }, + }); + }); + return exports; } -exports.ECKey = function(curve, key, isPublic) -{ - var priv; - var c = curve(); - var n = c.getN(); - var bytes = Math.floor(n.bitLength()/8); +function noop() { /* empty */ } - if(key) - { - if(isPublic) - { - var curve = c.getCurve(); -// var x = key.slice(1,bytes+1); // skip the 04 for uncompressed format -// var y = key.slice(bytes+1); -// this.P = new ECPointFp(curve, -// curve.fromBigInteger(new BigInteger(x.toString("hex"), 16)), -// curve.fromBigInteger(new BigInteger(y.toString("hex"), 16))); - this.P = curve.decodePointHex(key.toString("hex")); - }else{ - if(key.length != bytes) return false; - priv = new BigInteger(key.toString("hex"), 16); - } - }else{ - var n1 = n.subtract(BigInteger.ONE); - var r = new BigInteger(crypto.randomBytes(n.bitLength())); - priv = r.mod(n1).add(BigInteger.ONE); - this.P = c.getG().multiply(priv); - } - if(this.P) - { -// var pubhex = unstupid(this.P.getX().toBigInteger().toString(16),bytes*2)+unstupid(this.P.getY().toBigInteger().toString(16),bytes*2); -// this.PublicKey = Buffer.from("04"+pubhex,"hex"); - this.PublicKey = Buffer.from(c.getCurve().encodeCompressedPointHex(this.P),"hex"); +function parseUrl(input) { + var parsed; + // istanbul ignore else + if (useNativeURL) { + parsed = new URL(input); } - if(priv) - { - this.PrivateKey = Buffer.from(unstupid(priv.toString(16),bytes*2),"hex"); - this.deriveSharedSecret = function(key) - { - if(!key || !key.P) return false; - var S = key.P.multiply(priv); - return Buffer.from(unstupid(S.getX().toBigInteger().toString(16),bytes*2),"hex"); - } + else { + // Ensure the URL is valid and absolute + parsed = validateUrl(url.parse(input)); + if (!isString(parsed.protocol)) { + throw new InvalidUrlError({ input }); + } } + return parsed; } +function resolveUrl(relative, base) { + // istanbul ignore next + return useNativeURL ? new URL(relative, base) : parseUrl(url.resolve(base, relative)); +} +function validateUrl(input) { + if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) { + throw new InvalidUrlError({ input: input.href || input }); + } + if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) { + throw new InvalidUrlError({ input: input.href || input }); + } + return input; +} -/***/ }), +function spreadUrlObject(urlObject, target) { + var spread = target || {}; + for (var key of preservedUrlFields) { + spread[key] = urlObject[key]; + } -/***/ 3943: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Fix IPv6 hostname + if (spread.hostname.startsWith("[")) { + spread.hostname = spread.hostname.slice(1, -1); + } + // Ensure port is a number + if (spread.port !== "") { + spread.port = Number(spread.port); + } + // Concatenate path + spread.path = spread.search ? spread.pathname + spread.search : spread.pathname; -// Basic Javascript Elliptic Curve implementation -// Ported loosely from BouncyCastle's Java EC code -// Only Fp curves implemented for now + return spread; +} -// Requires jsbn.js and jsbn2.js -var BigInteger = (__nccwpck_require__(85587).BigInteger) -var Barrett = BigInteger.prototype.Barrett +function removeMatchingHeaders(regex, headers) { + var lastValue; + for (var header in headers) { + if (regex.test(header)) { + lastValue = headers[header]; + delete headers[header]; + } + } + return (lastValue === null || typeof lastValue === "undefined") ? + undefined : String(lastValue).trim(); +} -// ---------------- -// ECFieldElementFp +function createErrorType(code, message, baseClass) { + // Create constructor + function CustomError(properties) { + // istanbul ignore else + if (isFunction(Error.captureStackTrace)) { + Error.captureStackTrace(this, this.constructor); + } + Object.assign(this, properties || {}); + this.code = code; + this.message = this.cause ? message + ": " + this.cause.message : message; + } -// constructor -function ECFieldElementFp(q,x) { - this.x = x; - // TODO if(x.compareTo(q) >= 0) error - this.q = q; + // Attach constructor and set default properties + CustomError.prototype = new (baseClass || Error)(); + Object.defineProperties(CustomError.prototype, { + constructor: { + value: CustomError, + enumerable: false, + }, + name: { + value: "Error [" + code + "]", + enumerable: false, + }, + }); + return CustomError; } -function feFpEquals(other) { - if(other == this) return true; - return (this.q.equals(other.q) && this.x.equals(other.x)); +function destroyRequest(request, error) { + for (var event of events) { + request.removeListener(event, eventHandlers[event]); + } + request.on("error", noop); + request.destroy(error); } -function feFpToBigInteger() { - return this.x; +function isSubdomain(subdomain, domain) { + assert(isString(subdomain) && isString(domain)); + var dot = subdomain.length - domain.length - 1; + return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain); } -function feFpNegate() { - return new ECFieldElementFp(this.q, this.x.negate().mod(this.q)); +function isString(value) { + return typeof value === "string" || value instanceof String; } -function feFpAdd(b) { - return new ECFieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q)); +function isFunction(value) { + return typeof value === "function"; } -function feFpSubtract(b) { - return new ECFieldElementFp(this.q, this.x.subtract(b.toBigInteger()).mod(this.q)); +function isBuffer(value) { + return typeof value === "object" && ("length" in value); } -function feFpMultiply(b) { - return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger()).mod(this.q)); +function isURL(value) { + return URL && value instanceof URL; } -function feFpSquare() { - return new ECFieldElementFp(this.q, this.x.square().mod(this.q)); -} +// Exports +module.exports = wrap({ http: http, https: https }); +module.exports.wrap = wrap; -function feFpDivide(b) { - return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger().modInverse(this.q)).mod(this.q)); -} -ECFieldElementFp.prototype.equals = feFpEquals; -ECFieldElementFp.prototype.toBigInteger = feFpToBigInteger; -ECFieldElementFp.prototype.negate = feFpNegate; -ECFieldElementFp.prototype.add = feFpAdd; -ECFieldElementFp.prototype.subtract = feFpSubtract; -ECFieldElementFp.prototype.multiply = feFpMultiply; -ECFieldElementFp.prototype.square = feFpSquare; -ECFieldElementFp.prototype.divide = feFpDivide; +/***/ }), -// ---------------- -// ECPointFp +/***/ 47568: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// constructor -function ECPointFp(curve,x,y,z) { - this.curve = curve; - this.x = x; - this.y = y; - // Projective coordinates: either zinv == null or z * zinv == 1 - // z and zinv are just BigIntegers, not fieldElements - if(z == null) { - this.z = BigInteger.ONE; - } - else { - this.z = z; +module.exports = ForeverAgent +ForeverAgent.SSL = ForeverAgentSSL + +var util = __nccwpck_require__(73837) + , Agent = (__nccwpck_require__(13685).Agent) + , net = __nccwpck_require__(41808) + , tls = __nccwpck_require__(24404) + , AgentSSL = (__nccwpck_require__(95687).Agent) + +function getConnectionName(host, port) { + var name = '' + if (typeof host === 'string') { + name = host + ':' + port + } else { + // For node.js v012.0 and iojs-v1.5.1, host is an object. And any existing localAddress is part of the connection name. + name = host.host + ':' + host.port + ':' + (host.localAddress ? (host.localAddress + ':') : ':') + } + return name +} + +function ForeverAgent(options) { + var self = this + self.options = options || {} + self.requests = {} + self.sockets = {} + self.freeSockets = {} + self.maxSockets = self.options.maxSockets || Agent.defaultMaxSockets + self.minSockets = self.options.minSockets || ForeverAgent.defaultMinSockets + self.on('free', function(socket, host, port) { + var name = getConnectionName(host, port) + + if (self.requests[name] && self.requests[name].length) { + self.requests[name].shift().onSocket(socket) + } else if (self.sockets[name].length < self.minSockets) { + if (!self.freeSockets[name]) self.freeSockets[name] = [] + self.freeSockets[name].push(socket) + + // if an error happens while we don't use the socket anyway, meh, throw the socket away + var onIdleError = function() { + socket.destroy() + } + socket._onIdleError = onIdleError + socket.on('error', onIdleError) + } else { + // If there are no pending requests just destroy the + // socket and it will get removed from the pool. This + // gets us out of timeout issues and allows us to + // default to Connection:keep-alive. + socket.destroy() } - this.zinv = null; - //TODO: compression flag + }) + } +util.inherits(ForeverAgent, Agent) -function pointFpGetX() { - if(this.zinv == null) { - this.zinv = this.z.modInverse(this.curve.q); - } - var r = this.x.toBigInteger().multiply(this.zinv); - this.curve.reduce(r); - return this.curve.fromBigInteger(r); +ForeverAgent.defaultMinSockets = 5 + + +ForeverAgent.prototype.createConnection = net.createConnection +ForeverAgent.prototype.addRequestNoreuse = Agent.prototype.addRequest +ForeverAgent.prototype.addRequest = function(req, host, port) { + var name = getConnectionName(host, port) + + if (typeof host !== 'string') { + var options = host + port = options.port + host = options.host + } + + if (this.freeSockets[name] && this.freeSockets[name].length > 0 && !req.useChunkedEncodingByDefault) { + var idleSocket = this.freeSockets[name].pop() + idleSocket.removeListener('error', idleSocket._onIdleError) + delete idleSocket._onIdleError + req._reusedSocket = true + req.onSocket(idleSocket) + } else { + this.addRequestNoreuse(req, host, port) + } } -function pointFpGetY() { - if(this.zinv == null) { - this.zinv = this.z.modInverse(this.curve.q); +ForeverAgent.prototype.removeSocket = function(s, name, host, port) { + if (this.sockets[name]) { + var index = this.sockets[name].indexOf(s) + if (index !== -1) { + this.sockets[name].splice(index, 1) } - var r = this.y.toBigInteger().multiply(this.zinv); - this.curve.reduce(r); - return this.curve.fromBigInteger(r); -} + } else if (this.sockets[name] && this.sockets[name].length === 0) { + // don't leak + delete this.sockets[name] + delete this.requests[name] + } + + if (this.freeSockets[name]) { + var index = this.freeSockets[name].indexOf(s) + if (index !== -1) { + this.freeSockets[name].splice(index, 1) + if (this.freeSockets[name].length === 0) { + delete this.freeSockets[name] + } + } + } -function pointFpEquals(other) { - if(other == this) return true; - if(this.isInfinity()) return other.isInfinity(); - if(other.isInfinity()) return this.isInfinity(); - var u, v; - // u = Y2 * Z1 - Y1 * Z2 - u = other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod(this.curve.q); - if(!u.equals(BigInteger.ZERO)) return false; - // v = X2 * Z1 - X1 * Z2 - v = other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod(this.curve.q); - return v.equals(BigInteger.ZERO); + if (this.requests[name] && this.requests[name].length) { + // If we have pending requests and a socket gets closed a new one + // needs to be created to take over in the pool for the one that closed. + this.createSocket(name, host, port).emit('free') + } } -function pointFpIsInfinity() { - if((this.x == null) && (this.y == null)) return true; - return this.z.equals(BigInteger.ZERO) && !this.y.toBigInteger().equals(BigInteger.ZERO); +function ForeverAgentSSL (options) { + ForeverAgent.call(this, options) } +util.inherits(ForeverAgentSSL, ForeverAgent) -function pointFpNegate() { - return new ECPointFp(this.curve, this.x, this.y.negate(), this.z); +ForeverAgentSSL.prototype.createConnection = createConnectionSSL +ForeverAgentSSL.prototype.addRequestNoreuse = AgentSSL.prototype.addRequest + +function createConnectionSSL (port, host, options) { + if (typeof port === 'object') { + options = port; + } else if (typeof host === 'object') { + options = host; + } else if (typeof options === 'object') { + options = options; + } else { + options = {}; + } + + if (typeof port === 'number') { + options.port = port; + } + + if (typeof host === 'string') { + options.host = host; + } + + return tls.connect(options); } -function pointFpAdd(b) { - if(this.isInfinity()) return b; - if(b.isInfinity()) return this; - // u = Y2 * Z1 - Y1 * Z2 - var u = b.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(b.z)).mod(this.curve.q); - // v = X2 * Z1 - X1 * Z2 - var v = b.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(b.z)).mod(this.curve.q); +/***/ }), - if(BigInteger.ZERO.equals(v)) { - if(BigInteger.ZERO.equals(u)) { - return this.twice(); // this == b, so double - } - return this.curve.getInfinity(); // this = -b, so infinity - } +/***/ 27714: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var THREE = new BigInteger("3"); - var x1 = this.x.toBigInteger(); - var y1 = this.y.toBigInteger(); - var x2 = b.x.toBigInteger(); - var y2 = b.y.toBigInteger(); +"use strict"; - var v2 = v.square(); - var v3 = v2.multiply(v); - var x1v2 = x1.multiply(v2); - var zu2 = u.square().multiply(this.z); +const MiniPass = __nccwpck_require__(41077) +const EE = (__nccwpck_require__(82361).EventEmitter) +const fs = __nccwpck_require__(57147) - // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3) - var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.q); - // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3 - var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.q); - // z3 = v^3 * z1 * z2 - var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.q); +let writev = fs.writev +/* istanbul ignore next */ +if (!writev) { + // This entire block can be removed if support for earlier than Node.js + // 12.9.0 is not needed. + const binding = process.binding('fs') + const FSReqWrap = binding.FSReqWrap || binding.FSReqCallback - return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3); + writev = (fd, iovec, pos, cb) => { + const done = (er, bw) => cb(er, bw, iovec) + const req = new FSReqWrap() + req.oncomplete = done + binding.writeBuffers(fd, iovec, pos, req) + } } -function pointFpTwice() { - if(this.isInfinity()) return this; - if(this.y.toBigInteger().signum() == 0) return this.curve.getInfinity(); +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') - // TODO: optimized handling of constants - var THREE = new BigInteger("3"); - var x1 = this.x.toBigInteger(); - var y1 = this.y.toBigInteger(); +class ReadStream extends MiniPass { + constructor (path, opt) { + opt = opt || {} + super(opt) - var y1z1 = y1.multiply(this.z); - var y1sqz1 = y1z1.multiply(y1).mod(this.curve.q); - var a = this.curve.a.toBigInteger(); + this.readable = true + this.writable = false - // w = 3 * x1^2 + a * z1^2 - var w = x1.square().multiply(THREE); - if(!BigInteger.ZERO.equals(a)) { - w = w.add(this.z.square().multiply(a)); + if (typeof path !== 'string') + throw new TypeError('path must be a string') + + 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]() + } + + get fd () { return this[_fd] } + get path () { return this[_path] } + + write () { + throw new TypeError('this is a readable stream') + } + + end () { + throw new TypeError('this is a readable stream') + } + + [_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]() } - w = w.mod(this.curve.q); - //this.curve.reduce(w); - // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1) - var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.q); - // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3 - var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.square().multiply(w)).mod(this.curve.q); - // z3 = 8 * (y1 * z1)^3 - var z3 = y1z1.square().multiply(y1z1).shiftLeft(3).mod(this.curve.q); + } - return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3); -} + [_makeBuf] () { + return Buffer.allocUnsafe(Math.min(this[_readSize], this[_remain])) + } -// Simple NAF (Non-Adjacent Form) multiplication algorithm -// TODO: modularize the multiplication algorithm -function pointFpMultiply(k) { - if(this.isInfinity()) return this; - if(k.signum() == 0) return this.curve.getInfinity(); + [_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, buf) => + this[_onread](er, br, buf)) + } + } - var e = k; - var h = e.multiply(new BigInteger("3")); + [_onread] (er, br, buf) { + this[_reading] = false + if (er) + this[_onerror](er) + else if (this[_handleChunk](br, buf)) + this[_read]() + } - var neg = this.negate(); - var R = 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')) + } + } - var i; - for(i = h.bitLength() - 2; i > 0; --i) { - R = R.twice(); + [_onerror] (er) { + this[_reading] = true + this[_close]() + this.emit('error', er) + } - var hBit = h.testBit(i); - var eBit = e.testBit(i); + [_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 (hBit != eBit) { - R = R.add(hBit ? this : neg); - } + if (br === 0 || this[_remain] <= 0) { + ret = false + this[_close]() + super.end() } - return R; -} + return ret + } -// Compute this*j + x*k (simultaneous multiplication) -function pointFpMultiplyTwo(j,x,k) { - var i; - if(j.bitLength() > k.bitLength()) - i = j.bitLength() - 1; - else - i = k.bitLength() - 1; + emit (ev, data) { + switch (ev) { + case 'prefinish': + case 'finish': + break - var R = this.curve.getInfinity(); - var both = this.add(x); - while(i >= 0) { - R = R.twice(); - if(j.testBit(i)) { - if(k.testBit(i)) { - R = R.add(both); - } - else { - R = R.add(this); - } + case 'drain': + if (typeof this[_fd] === 'number') + this[_read]() + break + + case 'error': + if (this[_errored]) + return + this[_errored] = true + return super.emit(ev, data) + + default: + return super.emit(ev, 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]() } - else { - if(k.testBit(i)) { - R = R.add(x); + } + + [_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]() } - --i; } - return R; -} - -ECPointFp.prototype.getX = pointFpGetX; -ECPointFp.prototype.getY = pointFpGetY; -ECPointFp.prototype.equals = pointFpEquals; -ECPointFp.prototype.isInfinity = pointFpIsInfinity; -ECPointFp.prototype.negate = pointFpNegate; -ECPointFp.prototype.add = pointFpAdd; -ECPointFp.prototype.twice = pointFpTwice; -ECPointFp.prototype.multiply = pointFpMultiply; -ECPointFp.prototype.multiplyTwo = pointFpMultiplyTwo; - -// ---------------- -// ECCurveFp - -// constructor -function ECCurveFp(q,a,b) { - this.q = q; - this.a = this.fromBigInteger(a); - this.b = this.fromBigInteger(b); - this.infinity = new ECPointFp(this, null, null); - this.reducer = new Barrett(this.q); -} - -function curveFpGetQ() { - return this.q; + [_close] () { + if (this[_autoClose] && typeof this[_fd] === 'number') { + const fd = this[_fd] + this[_fd] = null + fs.closeSync(fd) + this.emit('close') + } + } } -function curveFpGetA() { - return this.a; -} +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 curveFpGetB() { - return this.b; -} + // 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 -function curveFpEquals(other) { - if(other == this) return true; - return(this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b)); -} + if (this[_fd] === null) + this[_open]() + } -function curveFpGetInfinity() { - return this.infinity; -} + emit (ev, data) { + if (ev === 'error') { + if (this[_errored]) + return + this[_errored] = true + } + return super.emit(ev, data) + } -function curveFpFromBigInteger(x) { - return new ECFieldElementFp(this.q, x); -} -function curveReduce(x) { - this.reducer.reduce(x); -} + get fd () { return this[_fd] } + get path () { return this[_path] } -// for now, work with hex strings because they're easier in JS -function curveFpDecodePointHex(s) { - switch(parseInt(s.substr(0,2), 16)) { // first byte - case 0: - return this.infinity; - case 2: - case 3: - // point compression not supported yet - return null; - case 4: - case 6: - case 7: - var len = (s.length - 2) / 2; - var xHex = s.substr(2, len); - var yHex = s.substr(len+2, len); + [_onerror] (er) { + this[_close]() + this[_writing] = true + this.emit('error', er) + } - return new ECPointFp(this, - this.fromBigInteger(new BigInteger(xHex, 16)), - this.fromBigInteger(new BigInteger(yHex, 16))); + [_open] () { + fs.open(this[_path], this[_flags], this[_mode], + (er, fd) => this[_onopen](er, fd)) + } - default: // unsupported - return null; + [_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) + this[_flush]() } -} + } -function curveFpEncodePointHex(p) { - if (p.isInfinity()) return "00"; - var xHex = p.getX().toBigInteger().toString(16); - var yHex = p.getY().toBigInteger().toString(16); - var oLen = this.getQ().toString(16).length; - if ((oLen % 2) != 0) oLen++; - while (xHex.length < oLen) { - xHex = "0" + xHex; - } - while (yHex.length < oLen) { - yHex = "0" + yHex; - } - return "04" + xHex + yHex; -} + end (buf, enc) { + if (buf) + this.write(buf, enc) -ECCurveFp.prototype.getQ = curveFpGetQ; -ECCurveFp.prototype.getA = curveFpGetA; -ECCurveFp.prototype.getB = curveFpGetB; -ECCurveFp.prototype.equals = curveFpEquals; -ECCurveFp.prototype.getInfinity = curveFpGetInfinity; -ECCurveFp.prototype.fromBigInteger = curveFpFromBigInteger; -ECCurveFp.prototype.reduce = curveReduce; -//ECCurveFp.prototype.decodePointHex = curveFpDecodePointHex; -ECCurveFp.prototype.encodePointHex = curveFpEncodePointHex; + this[_ended] = true -// from: https://github.com/kaielvin/jsbn-ec-point-compression -ECCurveFp.prototype.decodePointHex = function(s) -{ - var yIsEven; - switch(parseInt(s.substr(0,2), 16)) { // first byte - case 0: - return this.infinity; - case 2: - yIsEven = false; - case 3: - if(yIsEven == undefined) yIsEven = true; - var len = s.length - 2; - var xHex = s.substr(2, len); - var x = this.fromBigInteger(new BigInteger(xHex,16)); - var alpha = x.multiply(x.square().add(this.getA())).add(this.getB()); - var beta = alpha.sqrt(); + // synthetic after-write logic, where drain/finish live + if (!this[_writing] && !this[_queue].length && + typeof this[_fd] === 'number') + this[_onwrite](null, 0) + return this + } - if (beta == null) throw "Invalid point compression"; + write (buf, enc) { + if (typeof buf === 'string') + buf = Buffer.from(buf, enc) - var betaValue = beta.toBigInteger(); - if (betaValue.testBit(0) != yIsEven) - { - // Use the other root - beta = this.fromBigInteger(this.getQ().subtract(betaValue)); + if (this[_ended]) { + this.emit('error', new Error('write() after end()')) + return false } - return new ECPointFp(this,x,beta); - case 4: - case 6: - case 7: - var len = (s.length - 2) / 2; - var xHex = s.substr(2, len); - var yHex = s.substr(len+2, len); - - return new ECPointFp(this, - this.fromBigInteger(new BigInteger(xHex, 16)), - this.fromBigInteger(new BigInteger(yHex, 16))); - default: // unsupported - return null; + if (this[_fd] === null || this[_writing] || this[_queue].length) { + this[_queue].push(buf) + this[_needDrain] = true + return false } -} -ECCurveFp.prototype.encodeCompressedPointHex = function(p) -{ - if (p.isInfinity()) return "00"; - var xHex = p.getX().toBigInteger().toString(16); - var oLen = this.getQ().toString(16).length; - if ((oLen % 2) != 0) oLen++; - while (xHex.length < oLen) - xHex = "0" + xHex; - var yPrefix; - if(p.getY().toBigInteger().isEven()) yPrefix = "02"; - else yPrefix = "03"; - return yPrefix + xHex; -} + this[_writing] = true + this[_write](buf) + return true + } + [_write] (buf) { + fs.write(this[_fd], buf, 0, buf.length, this[_pos], (er, bw) => + this[_onwrite](er, bw)) + } -ECFieldElementFp.prototype.getR = function() -{ - if(this.r != undefined) return this.r; + [_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 - this.r = null; - var bitLength = this.q.bitLength(); - if (bitLength > 128) - { - var firstWord = this.q.shiftRight(bitLength - 64); - if (firstWord.intValue() == -1) - { - this.r = BigInteger.ONE.shiftLeft(bitLength).subtract(this.q); + if (this[_ended] && !this[_finished]) { + this[_finished] = true + this[_close]() + this.emit('finish') + } else if (this[_needDrain]) { + this[_needDrain] = false + this.emit('drain') } + } } - return this.r; -} -ECFieldElementFp.prototype.modMult = function(x1,x2) -{ - return this.modReduce(x1.multiply(x2)); -} -ECFieldElementFp.prototype.modReduce = function(x) -{ - if (this.getR() != null) - { - var qLen = q.bitLength(); - while (x.bitLength() > (qLen + 1)) - { - var u = x.shiftRight(qLen); - var v = x.subtract(u.shiftLeft(qLen)); - if (!this.getR().equals(BigInteger.ONE)) - { - u = u.multiply(this.getR()); - } - x = u.add(v); - } - while (x.compareTo(q) >= 0) - { - x = x.subtract(q); - } + } + + [_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)) } - else - { - x = x.mod(q); + } + + [_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 x; + } } -ECFieldElementFp.prototype.sqrt = function() -{ - if (!this.q.testBit(0)) throw "unsupported"; - // p mod 4 == 3 - if (this.q.testBit(1)) - { - var z = new ECFieldElementFp(this.q,this.x.modPow(this.q.shiftRight(2).add(BigInteger.ONE),this.q)); - return z.square().equals(this) ? z : null; - } +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]) - // p mod 4 == 1 - var qMinusOne = this.q.subtract(BigInteger.ONE); + this[_onopen](null, fd) + } - var legendreExponent = qMinusOne.shiftRight(1); - if (!(this.x.modPow(legendreExponent, this.q).equals(BigInteger.ONE))) - { - return null; + [_close] () { + if (this[_autoClose] && typeof this[_fd] === 'number') { + const fd = this[_fd] + this[_fd] = null + fs.closeSync(fd) + this.emit('close') } + } - var u = qMinusOne.shiftRight(2); - var k = u.shiftLeft(1).add(BigInteger.ONE); + [_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 (_) {} + } + } +} - var Q = this.x; - var fourQ = modDouble(modDouble(Q)); +exports.ReadStream = ReadStream +exports.ReadStreamSync = ReadStreamSync - var U, V; - do - { - var P; - do - { - P = new BigInteger(this.q.bitLength(), new SecureRandom()); - } - while (P.compareTo(this.q) >= 0 - || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, this.q).equals(qMinusOne))); +exports.WriteStream = WriteStream +exports.WriteStreamSync = WriteStreamSync - var result = this.lucasSequence(P, Q, k); - U = result[0]; - V = result[1]; - if (this.modMult(V, V).equals(fourQ)) - { - // Integer division by 2, mod q - if (V.testBit(0)) - { - V = V.add(q); - } +/***/ }), - V = V.shiftRight(1); +/***/ 46863: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return new ECFieldElementFp(q,V); - } - } - while (U.equals(BigInteger.ONE) || U.equals(qMinusOne)); +module.exports = realpath +realpath.realpath = realpath +realpath.sync = realpathSync +realpath.realpathSync = realpathSync +realpath.monkeypatch = monkeypatch +realpath.unmonkeypatch = unmonkeypatch - return null; -} -ECFieldElementFp.prototype.lucasSequence = function(P,Q,k) -{ - var n = k.bitLength(); - var s = k.getLowestSetBit(); +var fs = __nccwpck_require__(57147) +var origRealpath = fs.realpath +var origRealpathSync = fs.realpathSync - var Uh = BigInteger.ONE; - var Vl = BigInteger.TWO; - var Vh = P; - var Ql = BigInteger.ONE; - var Qh = BigInteger.ONE; +var version = process.version +var ok = /^v[0-5]\./.test(version) +var old = __nccwpck_require__(71734) - for (var j = n - 1; j >= s + 1; --j) - { - Ql = this.modMult(Ql, Qh); +function newError (er) { + return er && er.syscall === 'realpath' && ( + er.code === 'ELOOP' || + er.code === 'ENOMEM' || + er.code === 'ENAMETOOLONG' + ) +} - if (k.testBit(j)) - { - Qh = this.modMult(Ql, Q); - Uh = this.modMult(Uh, Vh); - Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); - Vh = this.modReduce(Vh.multiply(Vh).subtract(Qh.shiftLeft(1))); - } - else - { - Qh = Ql; - Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql)); - Vh = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); - Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1))); - } +function realpath (p, cache, cb) { + if (ok) { + return origRealpath(p, cache, cb) + } + + if (typeof cache === 'function') { + cb = cache + cache = null + } + origRealpath(p, cache, function (er, result) { + if (newError(er)) { + old.realpath(p, cache, cb) + } else { + cb(er, result) } + }) +} - Ql = this.modMult(Ql, Qh); - Qh = this.modMult(Ql, Q); - Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql)); - Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); - Ql = this.modMult(Ql, Qh); +function realpathSync (p, cache) { + if (ok) { + return origRealpathSync(p, cache) + } - for (var j = 1; j <= s; ++j) - { - Uh = this.modMult(Uh, Vl); - Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1))); - Ql = this.modMult(Ql, Ql); + try { + return origRealpathSync(p, cache) + } catch (er) { + if (newError(er)) { + return old.realpathSync(p, cache) + } else { + throw er } - - return [ Uh, Vl ]; + } } -var exports = { - ECCurveFp: ECCurveFp, - ECPointFp: ECPointFp, - ECFieldElementFp: ECFieldElementFp +function monkeypatch () { + fs.realpath = realpath + fs.realpathSync = realpathSync } -module.exports = exports +function unmonkeypatch () { + fs.realpath = origRealpath + fs.realpathSync = origRealpathSync +} /***/ }), -/***/ 41452: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 71734: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// Named EC curves +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. -// Requires ec.js, jsbn.js, and jsbn2.js -var BigInteger = (__nccwpck_require__(85587).BigInteger) -var ECCurveFp = (__nccwpck_require__(3943).ECCurveFp) +var pathModule = __nccwpck_require__(71017); +var isWindows = process.platform === 'win32'; +var fs = __nccwpck_require__(57147); +// JavaScript implementation of realpath, ported from node pre-v6 -// ---------------- -// X9ECParameters +var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); -// constructor -function X9ECParameters(curve,g,n,h) { - this.curve = curve; - this.g = g; - this.n = n; - this.h = h; -} +function rethrow() { + // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and + // is fairly slow to generate. + var callback; + if (DEBUG) { + var backtrace = new Error; + callback = debugCallback; + } else + callback = missingCallback; -function x9getCurve() { - return this.curve; -} + return callback; -function x9getG() { - return this.g; -} + function debugCallback(err) { + if (err) { + backtrace.message = err.message; + err = backtrace; + missingCallback(err); + } + } -function x9getN() { - return this.n; + function missingCallback(err) { + if (err) { + if (process.throwDeprecation) + throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs + else if (!process.noDeprecation) { + var msg = 'fs: missing callback ' + (err.stack || err.message); + if (process.traceDeprecation) + console.trace(msg); + else + console.error(msg); + } + } + } } -function x9getH() { - return this.h; +function maybeCallback(cb) { + return typeof cb === 'function' ? cb : rethrow(); } -X9ECParameters.prototype.getCurve = x9getCurve; -X9ECParameters.prototype.getG = x9getG; -X9ECParameters.prototype.getN = x9getN; -X9ECParameters.prototype.getH = x9getH; - -// ---------------- -// SECNamedCurves - -function fromHex(s) { return new BigInteger(s, 16); } +var normalize = pathModule.normalize; -function secp128r1() { - // p = 2^128 - 2^97 - 1 - var p = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF"); - var a = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC"); - var b = fromHex("E87579C11079F43DD824993C2CEE5ED3"); - //byte[] S = Hex.decode("000E0D4D696E6768756151750CC03A4473D03679"); - var n = fromHex("FFFFFFFE0000000075A30D1B9038A115"); - var h = BigInteger.ONE; - var curve = new ECCurveFp(p, a, b); - var G = curve.decodePointHex("04" - + "161FF7528B899B2D0C28607CA52C5B86" - + "CF5AC8395BAFEB13C02DA292DDED7A83"); - return new X9ECParameters(curve, G, n, h); +// Regexp that finds the next partion of a (partial) path +// result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] +if (isWindows) { + var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; +} else { + var nextPartRe = /(.*?)(?:[\/]+|$)/g; } -function secp160k1() { - // p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1 - var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73"); - var a = BigInteger.ZERO; - var b = fromHex("7"); - //byte[] S = null; - var n = fromHex("0100000000000000000001B8FA16DFAB9ACA16B6B3"); - var h = BigInteger.ONE; - var curve = new ECCurveFp(p, a, b); - var G = curve.decodePointHex("04" - + "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB" - + "938CF935318FDCED6BC28286531733C3F03C4FEE"); - return new X9ECParameters(curve, G, n, h); +// Regex to find the device root, including trailing slash. E.g. 'c:\\'. +if (isWindows) { + var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; +} else { + var splitRootRe = /^[\/]*/; } -function secp160r1() { - // p = 2^160 - 2^31 - 1 - var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF"); - var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC"); - var b = fromHex("1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45"); - //byte[] S = Hex.decode("1053CDE42C14D696E67687561517533BF3F83345"); - var n = fromHex("0100000000000000000001F4C8F927AED3CA752257"); - var h = BigInteger.ONE; - var curve = new ECCurveFp(p, a, b); - var G = curve.decodePointHex("04" - + "4A96B5688EF573284664698968C38BB913CBFC82" - + "23A628553168947D59DCC912042351377AC5FB32"); - return new X9ECParameters(curve, G, n, h); -} +exports.realpathSync = function realpathSync(p, cache) { + // make p is absolute + p = pathModule.resolve(p); -function secp192k1() { - // p = 2^192 - 2^32 - 2^12 - 2^8 - 2^7 - 2^6 - 2^3 - 1 - var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37"); - var a = BigInteger.ZERO; - var b = fromHex("3"); - //byte[] S = null; - var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D"); - var h = BigInteger.ONE; - var curve = new ECCurveFp(p, a, b); - var G = curve.decodePointHex("04" - + "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D" - + "9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D"); - return new X9ECParameters(curve, G, n, h); -} + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return cache[p]; + } -function secp192r1() { - // p = 2^192 - 2^64 - 1 - var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF"); - var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC"); - var b = fromHex("64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1"); - //byte[] S = Hex.decode("3045AE6FC8422F64ED579528D38120EAE12196D5"); - var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831"); - var h = BigInteger.ONE; - var curve = new ECCurveFp(p, a, b); - var G = curve.decodePointHex("04" - + "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012" - + "07192B95FFC8DA78631011ED6B24CDD573F977A11E794811"); - return new X9ECParameters(curve, G, n, h); -} + var original = p, + seenLinks = {}, + knownHard = {}; -function secp224r1() { - // p = 2^224 - 2^96 + 1 - var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001"); - var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE"); - var b = fromHex("B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4"); - //byte[] S = Hex.decode("BD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5"); - var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D"); - var h = BigInteger.ONE; - var curve = new ECCurveFp(p, a, b); - var G = curve.decodePointHex("04" - + "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21" - + "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34"); - return new X9ECParameters(curve, G, n, h); -} + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; -function secp256r1() { - // p = 2^224 (2^32 - 1) + 2^192 + 2^96 - 1 - var p = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF"); - var a = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC"); - var b = fromHex("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B"); - //byte[] S = Hex.decode("C49D360886E704936A6678E1139D26B7819F7E90"); - var n = fromHex("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551"); - var h = BigInteger.ONE; - var curve = new ECCurveFp(p, a, b); - var G = curve.decodePointHex("04" - + "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296" - + "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5"); - return new X9ECParameters(curve, G, n, h); -} + start(); -// TODO: make this into a proper hashtable -function getSECCurveByName(name) { - if(name == "secp128r1") return secp128r1(); - if(name == "secp160k1") return secp160k1(); - if(name == "secp160r1") return secp160r1(); - if(name == "secp192k1") return secp192k1(); - if(name == "secp192r1") return secp192r1(); - if(name == "secp224r1") return secp224r1(); - if(name == "secp256r1") return secp256r1(); - return null; -} + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; -module.exports = { - "secp128r1":secp128r1, - "secp160k1":secp160k1, - "secp160r1":secp160r1, - "secp192k1":secp192k1, - "secp192r1":secp192r1, - "secp224r1":secp224r1, - "secp256r1":secp256r1 -} + // On windows, check that the root exists. On unix there is no need. + if (isWindows && !knownHard[base]) { + fs.lstatSync(base); + knownHard[base] = true; + } + } + // walk down the path, swapping out linked pathparts for their real + // values + // NB: p.length changes. + while (pos < p.length) { + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; -/***/ }), + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + continue; + } -/***/ 81205: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var resolvedLink; + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // some known symbolic link. no need to stat again. + resolvedLink = cache[base]; + } else { + var stat = fs.lstatSync(base); + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + continue; + } -var once = __nccwpck_require__(1223); + // read the link if it wasn't read before + // dev/ino always return 0 on windows, so skip the check. + var linkTarget = null; + if (!isWindows) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + linkTarget = seenLinks[id]; + } + } + if (linkTarget === null) { + fs.statSync(base); + linkTarget = fs.readlinkSync(base); + } + resolvedLink = pathModule.resolve(previous, linkTarget); + // track this, if given a cache. + if (cache) cache[base] = resolvedLink; + if (!isWindows) seenLinks[id] = linkTarget; + } -var noop = function() {}; + // resolve the link, then start over + p = pathModule.resolve(resolvedLink, p.slice(pos)); + start(); + } -var isRequest = function(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -}; + if (cache) cache[original] = p; -var isChildProcess = function(stream) { - return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 + return p; }; -var eos = function(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; - - callback = once(callback || noop); - - var ws = stream._writableState; - var rs = stream._readableState; - var readable = opts.readable || (opts.readable !== false && stream.readable); - var writable = opts.writable || (opts.writable !== false && stream.writable); - var cancelled = false; - var onlegacyfinish = function() { - if (!stream.writable) onfinish(); - }; +exports.realpath = function realpath(p, cache, cb) { + if (typeof cb !== 'function') { + cb = maybeCallback(cache); + cache = null; + } - var onfinish = function() { - writable = false; - if (!readable) callback.call(stream); - }; + // make p is absolute + p = pathModule.resolve(p); - var onend = function() { - readable = false; - if (!writable) callback.call(stream); - }; + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return process.nextTick(cb.bind(null, null, cache[p])); + } - var onexit = function(exitCode) { - callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); - }; + var original = p, + seenLinks = {}, + knownHard = {}; - var onerror = function(err) { - callback.call(stream, err); - }; + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; - var onclose = function() { - process.nextTick(onclosenexttick); - }; + start(); - var onclosenexttick = function() { - if (cancelled) return; - if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close')); - if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close')); - }; + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; - var onrequest = function() { - stream.req.on('finish', onfinish); - }; + // On windows, check that the root exists. On unix there is no need. + if (isWindows && !knownHard[base]) { + fs.lstat(base, function(err) { + if (err) return cb(err); + knownHard[base] = true; + LOOP(); + }); + } else { + process.nextTick(LOOP); + } + } - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest(); - else stream.on('request', onrequest); - } else if (writable && !ws) { // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } + // walk down the path, swapping out linked pathparts for their real + // values + function LOOP() { + // stop if scanned past end of path + if (pos >= p.length) { + if (cache) cache[original] = p; + return cb(null, p); + } - if (isChildProcess(stream)) stream.on('exit', onexit); + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + return process.nextTick(LOOP); + } - return function() { - cancelled = true; - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('exit', onexit); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; -}; + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // known symbolic link. no need to stat again. + return gotResolvedLink(cache[base]); + } -module.exports = eos; + return fs.lstat(base, gotStat); + } + function gotStat(err, stat) { + if (err) return cb(err); -/***/ }), + // if not a symlink, skip to the next path part + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + return process.nextTick(LOOP); + } -/***/ 6123: -/***/ ((module) => { + // stat & read the link if not read before + // call gotTarget as soon as the link target is known + // dev/ino always return 0 on windows, so skip the check. + if (!isWindows) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + return gotTarget(null, seenLinks[id], base); + } + } + fs.stat(base, function(err) { + if (err) return cb(err); -"use strict"; + fs.readlink(base, function(err, target) { + if (!isWindows) seenLinks[id] = target; + gotTarget(err, target); + }); + }); + } + function gotTarget(err, target, base) { + if (err) return cb(err); -/** @type {import('.')} */ -var $defineProperty = Object.defineProperty || false; -if ($defineProperty) { - try { - $defineProperty({}, 'a', { value: 1 }); - } catch (e) { - // IE 8 has a broken defineProperty - $defineProperty = false; - } -} + var resolvedLink = pathModule.resolve(previous, target); + if (cache) cache[base] = resolvedLink; + gotResolvedLink(resolvedLink); + } -module.exports = $defineProperty; + function gotResolvedLink(resolvedLink) { + // resolve the link, then start over + p = pathModule.resolve(resolvedLink, p.slice(pos)); + start(); + } +}; /***/ }), -/***/ 91933: -/***/ ((module) => { +/***/ 5045: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/** @type {import('./eval')} */ -module.exports = EvalError; +var $Object = __nccwpck_require__(78308); + +/** @type {import('./Object.getPrototypeOf')} */ +module.exports = $Object.getPrototypeOf || null; /***/ }), -/***/ 28015: +/***/ 78859: /***/ ((module) => { "use strict"; -/** @type {import('.')} */ -module.exports = Error; +/** @type {import('./Reflect.getPrototypeOf')} */ +module.exports = (typeof Reflect !== 'undefined' && Reflect.getPrototypeOf) || null; /***/ }), -/***/ 54415: -/***/ ((module) => { +/***/ 13592: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/** @type {import('./range')} */ -module.exports = RangeError; +var reflectGetProto = __nccwpck_require__(78859); +var originalGetProto = __nccwpck_require__(5045); + +var getDunderProto = __nccwpck_require__(62693); + +/** @type {import('.')} */ +module.exports = reflectGetProto + ? function getProto(O) { + // @ts-expect-error TS can't narrow inside a closure, for some reason + return reflectGetProto(O); + } + : originalGetProto + ? function getProto(O) { + if (!O || (typeof O !== 'object' && typeof O !== 'function')) { + throw new TypeError('getProto: not an object'); + } + // @ts-expect-error TS can't narrow inside a closure, for some reason + return originalGetProto(O); + } + : getDunderProto + ? function getProto(O) { + // @ts-expect-error TS can't narrow inside a closure, for some reason + return getDunderProto(O); + } + : null; /***/ }), -/***/ 46279: -/***/ ((module) => { +/***/ 91585: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +const {PassThrough: PassThroughStream} = __nccwpck_require__(12781); -/** @type {import('./ref')} */ -module.exports = ReferenceError; +module.exports = options => { + options = {...options}; + const {array} = options; + let {encoding} = options; + const isBuffer = encoding === 'buffer'; + let objectMode = false; -/***/ }), + if (array) { + objectMode = !(encoding || isBuffer); + } else { + encoding = encoding || 'utf8'; + } -/***/ 75474: -/***/ ((module) => { + if (isBuffer) { + encoding = null; + } -"use strict"; + const stream = new PassThroughStream({objectMode}); + if (encoding) { + stream.setEncoding(encoding); + } -/** @type {import('./syntax')} */ -module.exports = SyntaxError; + let length = 0; + const chunks = []; + stream.on('data', chunk => { + chunks.push(chunk); -/***/ }), + if (objectMode) { + length = chunks.length; + } else { + length += chunk.length; + } + }); -/***/ 6361: -/***/ ((module) => { + stream.getBufferedValue = () => { + if (array) { + return chunks; + } -"use strict"; + return isBuffer ? Buffer.concat(chunks, length) : chunks.join(''); + }; + stream.getBufferedLength = () => length; -/** @type {import('./type')} */ -module.exports = TypeError; + return stream; +}; /***/ }), -/***/ 5065: -/***/ ((module) => { +/***/ 21766: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +const {constants: BufferConstants} = __nccwpck_require__(14300); +const stream = __nccwpck_require__(12781); +const {promisify} = __nccwpck_require__(73837); +const bufferStream = __nccwpck_require__(91585); -/** @type {import('./uri')} */ -module.exports = URIError; +const streamPipelinePromisified = promisify(stream.pipeline); +class MaxBufferError extends Error { + constructor() { + super('maxBuffer exceeded'); + this.name = 'MaxBufferError'; + } +} -/***/ }), +async function getStream(inputStream, options) { + if (!inputStream) { + throw new Error('Expected a stream'); + } -/***/ 78308: -/***/ ((module) => { + options = { + maxBuffer: Infinity, + ...options + }; -"use strict"; + const {maxBuffer} = options; + const stream = bufferStream(options); + await new Promise((resolve, reject) => { + const rejectPromise = error => { + // Don't retrieve an oversized buffer. + if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) { + error.bufferedData = stream.getBufferedValue(); + } -/** @type {import('.')} */ -module.exports = Object; + reject(error); + }; + + (async () => { + try { + await streamPipelinePromisified(inputStream, stream); + resolve(); + } catch (error) { + rejectPromise(error); + } + })(); + + stream.on('data', () => { + if (stream.getBufferedLength() > maxBuffer) { + rejectPromise(new MaxBufferError()); + } + }); + }); + + return stream.getBufferedValue(); +} + +module.exports = getStream; +module.exports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'}); +module.exports.array = (stream, options) => getStream(stream, {...options, array: true}); +module.exports.MaxBufferError = MaxBufferError; /***/ }), -/***/ 11770: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 47625: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +exports.setopts = setopts +exports.ownProp = ownProp +exports.makeAbs = makeAbs +exports.finish = finish +exports.mark = mark +exports.isIgnored = isIgnored +exports.childrenIgnored = childrenIgnored +function ownProp (obj, field) { + return Object.prototype.hasOwnProperty.call(obj, field) +} -var GetIntrinsic = __nccwpck_require__(99276); +var fs = __nccwpck_require__(57147) +var path = __nccwpck_require__(71017) +var minimatch = __nccwpck_require__(83973) +var isAbsolute = __nccwpck_require__(38714) +var Minimatch = minimatch.Minimatch -var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); +function alphasort (a, b) { + return a.localeCompare(b, 'en') +} -var hasToStringTag = __nccwpck_require__(50499)(); -var hasOwn = __nccwpck_require__(62157); -var $TypeError = __nccwpck_require__(6361); +function setupIgnores (self, options) { + self.ignore = options.ignore || [] -var toStringTag = hasToStringTag ? Symbol.toStringTag : null; + if (!Array.isArray(self.ignore)) + self.ignore = [self.ignore] -/** @type {import('.')} */ -module.exports = function setToStringTag(object, value) { - var overrideIfSet = arguments.length > 2 && !!arguments[2] && arguments[2].force; - var nonConfigurable = arguments.length > 2 && !!arguments[2] && arguments[2].nonConfigurable; - if ( - (typeof overrideIfSet !== 'undefined' && typeof overrideIfSet !== 'boolean') - || (typeof nonConfigurable !== 'undefined' && typeof nonConfigurable !== 'boolean') - ) { - throw new $TypeError('if provided, the `overrideIfSet` and `nonConfigurable` options must be booleans'); - } - if (toStringTag && (overrideIfSet || !hasOwn(object, toStringTag))) { - if ($defineProperty) { - $defineProperty(object, toStringTag, { - configurable: !nonConfigurable, - enumerable: false, - value: value, - writable: false - }); - } else { - object[toStringTag] = value; // eslint-disable-line no-param-reassign - } - } -}; + if (self.ignore.length) { + self.ignore = self.ignore.map(ignoreMap) + } +} +// ignore patterns are always in dot:true mode. +function ignoreMap (pattern) { + var gmatcher = null + if (pattern.slice(-3) === '/**') { + var gpattern = pattern.replace(/(\/\*\*)+$/, '') + gmatcher = new Minimatch(gpattern, { dot: true }) + } -/***/ }), + return { + matcher: new Minimatch(pattern, { dot: true }), + gmatcher: gmatcher + } +} -/***/ 53325: -/***/ ((module) => { +function setopts (self, pattern, options) { + if (!options) + options = {} -"use strict"; + // base-matching: just use globstar for that. + if (options.matchBase && -1 === pattern.indexOf("/")) { + if (options.noglobstar) { + throw new Error("base matching requires globstar") + } + pattern = "**/" + pattern + } + + self.silent = !!options.silent + self.pattern = pattern + self.strict = options.strict !== false + self.realpath = !!options.realpath + self.realpathCache = options.realpathCache || Object.create(null) + self.follow = !!options.follow + self.dot = !!options.dot + self.mark = !!options.mark + self.nodir = !!options.nodir + if (self.nodir) + self.mark = true + self.sync = !!options.sync + self.nounique = !!options.nounique + self.nonull = !!options.nonull + self.nosort = !!options.nosort + self.nocase = !!options.nocase + self.stat = !!options.stat + self.noprocess = !!options.noprocess + self.absolute = !!options.absolute + self.fs = options.fs || fs + self.maxLength = options.maxLength || Infinity + self.cache = options.cache || Object.create(null) + self.statCache = options.statCache || Object.create(null) + self.symlinks = options.symlinks || Object.create(null) -/* eslint no-invalid-this: 1 */ + setupIgnores(self, options) -var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; -var toStr = Object.prototype.toString; -var max = Math.max; -var funcType = '[object Function]'; + self.changedCwd = false + var cwd = process.cwd() + if (!ownProp(options, "cwd")) + self.cwd = cwd + else { + self.cwd = path.resolve(options.cwd) + self.changedCwd = self.cwd !== cwd + } -var concatty = function concatty(a, b) { - var arr = []; + self.root = options.root || path.resolve(self.cwd, "/") + self.root = path.resolve(self.root) + if (process.platform === "win32") + self.root = self.root.replace(/\\/g, "/") - for (var i = 0; i < a.length; i += 1) { - arr[i] = a[i]; - } - for (var j = 0; j < b.length; j += 1) { - arr[j + a.length] = b[j]; - } + // TODO: is an absolute `cwd` supposed to be resolved against `root`? + // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') + self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd) + if (process.platform === "win32") + self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") + self.nomount = !!options.nomount - return arr; -}; + // disable comments and negation in Minimatch. + // Note that they are not supported in Glob itself anyway. + options.nonegate = true + options.nocomment = true + // always treat \ in patterns as escapes, not path separators + options.allowWindowsEscape = false -var slicy = function slicy(arrLike, offset) { - var arr = []; - for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { - arr[j] = arrLike[i]; - } - return arr; -}; + self.minimatch = new Minimatch(pattern, options) + self.options = self.minimatch.options +} -var joiny = function (arr, joiner) { - var str = ''; - for (var i = 0; i < arr.length; i += 1) { - str += arr[i]; - if (i + 1 < arr.length) { - str += joiner; - } - } - return str; -}; +function finish (self) { + var nou = self.nounique + var all = nou ? [] : Object.create(null) -module.exports = function bind(that) { - var target = this; - if (typeof target !== 'function' || toStr.apply(target) !== funcType) { - throw new TypeError(ERROR_MESSAGE + target); + for (var i = 0, l = self.matches.length; i < l; i ++) { + var matches = self.matches[i] + if (!matches || Object.keys(matches).length === 0) { + if (self.nonull) { + // do like the shell, and spit out the literal glob + var literal = self.minimatch.globSet[i] + if (nou) + all.push(literal) + else + all[literal] = true + } + } else { + // had matches + var m = Object.keys(matches) + if (nou) + all.push.apply(all, m) + else + m.forEach(function (m) { + all[m] = true + }) } - var args = slicy(arguments, 1); + } - var bound; - var binder = function () { - if (this instanceof bound) { - var result = target.apply( - this, - concatty(args, arguments) - ); - if (Object(result) === result) { - return result; - } - return this; - } - return target.apply( - that, - concatty(args, arguments) - ); + if (!nou) + all = Object.keys(all) - }; + if (!self.nosort) + all = all.sort(alphasort) - var boundLength = max(0, target.length - args.length); - var boundArgs = []; - for (var i = 0; i < boundLength; i++) { - boundArgs[i] = '$' + i; + // at *some* point we statted all of these + if (self.mark) { + for (var i = 0; i < all.length; i++) { + all[i] = self._mark(all[i]) + } + if (self.nodir) { + all = all.filter(function (e) { + var notDir = !(/\/$/.test(e)) + var c = self.cache[e] || self.cache[makeAbs(self, e)] + if (notDir && c) + notDir = c !== 'DIR' && !Array.isArray(c) + return notDir + }) } + } - bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); + if (self.ignore.length) + all = all.filter(function(m) { + return !isIgnored(self, m) + }) - if (target.prototype) { - var Empty = function Empty() {}; - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - Empty.prototype = null; + self.found = all +} + +function mark (self, p) { + var abs = makeAbs(self, p) + var c = self.cache[abs] + var m = p + if (c) { + var isDir = c === 'DIR' || Array.isArray(c) + var slash = p.slice(-1) === '/' + + if (isDir && !slash) + m += '/' + else if (!isDir && slash) + m = m.slice(0, -1) + + if (m !== p) { + var mabs = makeAbs(self, m) + self.statCache[mabs] = self.statCache[abs] + self.cache[mabs] = self.cache[abs] } + } - return bound; -}; + return m +} + +// lotta situps... +function makeAbs (self, f) { + var abs = f + if (f.charAt(0) === '/') { + abs = path.join(self.root, f) + } else if (isAbsolute(f) || f === '') { + abs = f + } else if (self.changedCwd) { + abs = path.resolve(self.cwd, f) + } else { + abs = path.resolve(f) + } + if (process.platform === 'win32') + abs = abs.replace(/\\/g, '/') -/***/ }), + return abs +} -/***/ 97257: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +// Return true, if pattern ends with globstar '**', for the accompanying parent directory. +// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents +function isIgnored (self, path) { + if (!self.ignore.length) + return false + return self.ignore.some(function(item) { + return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) + }) +} -var implementation = __nccwpck_require__(53325); +function childrenIgnored (self, path) { + if (!self.ignore.length) + return false -module.exports = Function.prototype.bind || implementation; + return self.ignore.some(function(item) { + return !!(item.gmatcher && item.gmatcher.match(path)) + }) +} /***/ }), -/***/ 99276: +/***/ 91957: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +// Approach: +// +// 1. Get the minimatch set +// 2. For each pattern in the set, PROCESS(pattern, false) +// 3. Store matches per-set, then uniq them +// +// PROCESS(pattern, inGlobStar) +// Get the first [n] items from pattern that are all strings +// Join these together. This is PREFIX. +// If there is no more remaining, then stat(PREFIX) and +// add to matches if it succeeds. END. +// +// If inGlobStar and PREFIX is symlink and points to dir +// set ENTRIES = [] +// else readdir(PREFIX) as ENTRIES +// If fail, END +// +// with ENTRIES +// If pattern[n] is GLOBSTAR +// // handle the case where the globstar match is empty +// // by pruning it out, and testing the resulting pattern +// PROCESS(pattern[0..n] + pattern[n+1 .. $], false) +// // handle other cases. +// for ENTRY in ENTRIES (not dotfiles) +// // attach globstar + tail onto the entry +// // Mark that this entry is a globstar match +// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) +// +// else // not globstar +// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) +// Test ENTRY against pattern[n] +// If fails, continue +// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) +// +// Caveat: +// Cache all stats and readdirs results to minimize syscall. Since all +// we ever care about is existence and directory-ness, we can just keep +// `true` for files, and [children,...] for directories, or `false` for +// things that don't exist. +module.exports = glob -var undefined; +var rp = __nccwpck_require__(46863) +var minimatch = __nccwpck_require__(83973) +var Minimatch = minimatch.Minimatch +var inherits = __nccwpck_require__(44124) +var EE = (__nccwpck_require__(82361).EventEmitter) +var path = __nccwpck_require__(71017) +var assert = __nccwpck_require__(39491) +var isAbsolute = __nccwpck_require__(38714) +var globSync = __nccwpck_require__(29010) +var common = __nccwpck_require__(47625) +var setopts = common.setopts +var ownProp = common.ownProp +var inflight = __nccwpck_require__(52492) +var util = __nccwpck_require__(73837) +var childrenIgnored = common.childrenIgnored +var isIgnored = common.isIgnored -var $Object = __nccwpck_require__(78308); +var once = __nccwpck_require__(1223) -var $Error = __nccwpck_require__(28015); -var $EvalError = __nccwpck_require__(91933); -var $RangeError = __nccwpck_require__(54415); -var $ReferenceError = __nccwpck_require__(46279); -var $SyntaxError = __nccwpck_require__(75474); -var $TypeError = __nccwpck_require__(6361); -var $URIError = __nccwpck_require__(5065); +function glob (pattern, options, cb) { + if (typeof options === 'function') cb = options, options = {} + if (!options) options = {} -var abs = __nccwpck_require__(19775); -var floor = __nccwpck_require__(60924); -var max = __nccwpck_require__(52419); -var min = __nccwpck_require__(73373); -var pow = __nccwpck_require__(78029); -var round = __nccwpck_require__(59396); -var sign = __nccwpck_require__(39091); + if (options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return globSync(pattern, options) + } -var $Function = Function; + return new Glob(pattern, options, cb) +} -// eslint-disable-next-line consistent-return -var getEvalledConstructor = function (expressionSyntax) { - try { - return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); - } catch (e) {} -}; +glob.sync = globSync +var GlobSync = glob.GlobSync = globSync.GlobSync -var $gOPD = __nccwpck_require__(64868); -var $defineProperty = __nccwpck_require__(6123); +// old api surface +glob.glob = glob -var throwTypeError = function () { - throw new $TypeError(); -}; -var ThrowTypeError = $gOPD - ? (function () { - try { - // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties - arguments.callee; // IE 8 does not throw here - return throwTypeError; - } catch (calleeThrows) { - try { - // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') - return $gOPD(arguments, 'callee').get; - } catch (gOPDthrows) { - return throwTypeError; - } - } - }()) - : throwTypeError; +function extend (origin, add) { + if (add === null || typeof add !== 'object') { + return origin + } -var hasSymbols = __nccwpck_require__(36546)(); + var keys = Object.keys(add) + var i = keys.length + while (i--) { + origin[keys[i]] = add[keys[i]] + } + return origin +} -var getProto = __nccwpck_require__(13592); -var $ObjectGPO = __nccwpck_require__(5045); -var $ReflectGPO = __nccwpck_require__(78859); +glob.hasMagic = function (pattern, options_) { + var options = extend({}, options_) + options.noprocess = true -var $apply = __nccwpck_require__(54177); -var $call = __nccwpck_require__(2808); + var g = new Glob(pattern, options) + var set = g.minimatch.set -var needsEval = {}; + if (!pattern) + return false -var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array); + if (set.length > 1) + return true -var INTRINSICS = { - __proto__: null, - '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, - '%Array%': Array, - '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, - '%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined, - '%AsyncFromSyncIteratorPrototype%': undefined, - '%AsyncFunction%': needsEval, - '%AsyncGenerator%': needsEval, - '%AsyncGeneratorFunction%': needsEval, - '%AsyncIteratorPrototype%': needsEval, - '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, - '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, - '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array, - '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array, - '%Boolean%': Boolean, - '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, - '%Date%': Date, - '%decodeURI%': decodeURI, - '%decodeURIComponent%': decodeURIComponent, - '%encodeURI%': encodeURI, - '%encodeURIComponent%': encodeURIComponent, - '%Error%': $Error, - '%eval%': eval, // eslint-disable-line no-eval - '%EvalError%': $EvalError, - '%Float16Array%': typeof Float16Array === 'undefined' ? undefined : Float16Array, - '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, - '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, - '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, - '%Function%': $Function, - '%GeneratorFunction%': needsEval, - '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, - '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, - '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, - '%isFinite%': isFinite, - '%isNaN%': isNaN, - '%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined, - '%JSON%': typeof JSON === 'object' ? JSON : undefined, - '%Map%': typeof Map === 'undefined' ? undefined : Map, - '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()), - '%Math%': Math, - '%Number%': Number, - '%Object%': $Object, - '%Object.getOwnPropertyDescriptor%': $gOPD, - '%parseFloat%': parseFloat, - '%parseInt%': parseInt, - '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, - '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, - '%RangeError%': $RangeError, - '%ReferenceError%': $ReferenceError, - '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, - '%RegExp%': RegExp, - '%Set%': typeof Set === 'undefined' ? undefined : Set, - '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()), - '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, - '%String%': String, - '%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined, - '%Symbol%': hasSymbols ? Symbol : undefined, - '%SyntaxError%': $SyntaxError, - '%ThrowTypeError%': ThrowTypeError, - '%TypedArray%': TypedArray, - '%TypeError%': $TypeError, - '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, - '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, - '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, - '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, - '%URIError%': $URIError, - '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, - '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, - '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet, + for (var j = 0; j < set[0].length; j++) { + if (typeof set[0][j] !== 'string') + return true + } - '%Function.prototype.call%': $call, - '%Function.prototype.apply%': $apply, - '%Object.defineProperty%': $defineProperty, - '%Object.getPrototypeOf%': $ObjectGPO, - '%Math.abs%': abs, - '%Math.floor%': floor, - '%Math.max%': max, - '%Math.min%': min, - '%Math.pow%': pow, - '%Math.round%': round, - '%Math.sign%': sign, - '%Reflect.getPrototypeOf%': $ReflectGPO -}; + return false +} -if (getProto) { - try { - null.error; // eslint-disable-line no-unused-expressions - } catch (e) { - // https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229 - var errorProto = getProto(getProto(e)); - INTRINSICS['%Error.prototype%'] = errorProto; - } +glob.Glob = Glob +inherits(Glob, EE) +function Glob (pattern, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } + + if (options && options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return new GlobSync(pattern, options) + } + + if (!(this instanceof Glob)) + return new Glob(pattern, options, cb) + + setopts(this, pattern, options) + this._didRealPath = false + + // process each pattern in the minimatch set + var n = this.minimatch.set.length + + // The matches are stored as {: true,...} so that + // duplicates are automagically pruned. + // Later, we do an Object.keys() on these. + // Keep them as a list so we can fill in when nonull is set. + this.matches = new Array(n) + + if (typeof cb === 'function') { + cb = once(cb) + this.on('error', cb) + this.on('end', function (matches) { + cb(null, matches) + }) + } + + var self = this + this._processing = 0 + + this._emitQueue = [] + this._processQueue = [] + this.paused = false + + if (this.noprocess) + return this + + if (n === 0) + return done() + + var sync = true + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false, done) + } + sync = false + + function done () { + --self._processing + if (self._processing <= 0) { + if (sync) { + process.nextTick(function () { + self._finish() + }) + } else { + self._finish() + } + } + } } -var doEval = function doEval(name) { - var value; - if (name === '%AsyncFunction%') { - value = getEvalledConstructor('async function () {}'); - } else if (name === '%GeneratorFunction%') { - value = getEvalledConstructor('function* () {}'); - } else if (name === '%AsyncGeneratorFunction%') { - value = getEvalledConstructor('async function* () {}'); - } else if (name === '%AsyncGenerator%') { - var fn = doEval('%AsyncGeneratorFunction%'); - if (fn) { - value = fn.prototype; - } - } else if (name === '%AsyncIteratorPrototype%') { - var gen = doEval('%AsyncGenerator%'); - if (gen && getProto) { - value = getProto(gen.prototype); - } - } +Glob.prototype._finish = function () { + assert(this instanceof Glob) + if (this.aborted) + return - INTRINSICS[name] = value; + if (this.realpath && !this._didRealpath) + return this._realpath() - return value; -}; + common.finish(this) + this.emit('end', this.found) +} -var LEGACY_ALIASES = { - __proto__: null, - '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], - '%ArrayPrototype%': ['Array', 'prototype'], - '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], - '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], - '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], - '%ArrayProto_values%': ['Array', 'prototype', 'values'], - '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], - '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], - '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], - '%BooleanPrototype%': ['Boolean', 'prototype'], - '%DataViewPrototype%': ['DataView', 'prototype'], - '%DatePrototype%': ['Date', 'prototype'], - '%ErrorPrototype%': ['Error', 'prototype'], - '%EvalErrorPrototype%': ['EvalError', 'prototype'], - '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], - '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], - '%FunctionPrototype%': ['Function', 'prototype'], - '%Generator%': ['GeneratorFunction', 'prototype'], - '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], - '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], - '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], - '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], - '%JSONParse%': ['JSON', 'parse'], - '%JSONStringify%': ['JSON', 'stringify'], - '%MapPrototype%': ['Map', 'prototype'], - '%NumberPrototype%': ['Number', 'prototype'], - '%ObjectPrototype%': ['Object', 'prototype'], - '%ObjProto_toString%': ['Object', 'prototype', 'toString'], - '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], - '%PromisePrototype%': ['Promise', 'prototype'], - '%PromiseProto_then%': ['Promise', 'prototype', 'then'], - '%Promise_all%': ['Promise', 'all'], - '%Promise_reject%': ['Promise', 'reject'], - '%Promise_resolve%': ['Promise', 'resolve'], - '%RangeErrorPrototype%': ['RangeError', 'prototype'], - '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], - '%RegExpPrototype%': ['RegExp', 'prototype'], - '%SetPrototype%': ['Set', 'prototype'], - '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], - '%StringPrototype%': ['String', 'prototype'], - '%SymbolPrototype%': ['Symbol', 'prototype'], - '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], - '%TypedArrayPrototype%': ['TypedArray', 'prototype'], - '%TypeErrorPrototype%': ['TypeError', 'prototype'], - '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], - '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], - '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], - '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], - '%URIErrorPrototype%': ['URIError', 'prototype'], - '%WeakMapPrototype%': ['WeakMap', 'prototype'], - '%WeakSetPrototype%': ['WeakSet', 'prototype'] -}; +Glob.prototype._realpath = function () { + if (this._didRealpath) + return -var bind = __nccwpck_require__(97257); -var hasOwn = __nccwpck_require__(62157); -var $concat = bind.call($call, Array.prototype.concat); -var $spliceApply = bind.call($apply, Array.prototype.splice); -var $replace = bind.call($call, String.prototype.replace); -var $strSlice = bind.call($call, String.prototype.slice); -var $exec = bind.call($call, RegExp.prototype.exec); + this._didRealpath = true -/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ -var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; -var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ -var stringToPath = function stringToPath(string) { - var first = $strSlice(string, 0, 1); - var last = $strSlice(string, -1); - if (first === '%' && last !== '%') { - throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); - } else if (last === '%' && first !== '%') { - throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); - } - var result = []; - $replace(string, rePropName, function (match, number, quote, subString) { - result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; - }); - return result; -}; -/* end adaptation */ + var n = this.matches.length + if (n === 0) + return this._finish() -var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { - var intrinsicName = name; - var alias; - if (hasOwn(LEGACY_ALIASES, intrinsicName)) { - alias = LEGACY_ALIASES[intrinsicName]; - intrinsicName = '%' + alias[0] + '%'; - } + var self = this + for (var i = 0; i < this.matches.length; i++) + this._realpathSet(i, next) - if (hasOwn(INTRINSICS, intrinsicName)) { - var value = INTRINSICS[intrinsicName]; - if (value === needsEval) { - value = doEval(intrinsicName); - } - if (typeof value === 'undefined' && !allowMissing) { - throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); - } + function next () { + if (--n === 0) + self._finish() + } +} - return { - alias: alias, - name: intrinsicName, - value: value - }; - } +Glob.prototype._realpathSet = function (index, cb) { + var matchset = this.matches[index] + if (!matchset) + return cb() + + var found = Object.keys(matchset) + var self = this + var n = found.length + + if (n === 0) + return cb() + + var set = this.matches[index] = Object.create(null) + found.forEach(function (p, i) { + // If there's a problem with the stat, then it means that + // one or more of the links in the realpath couldn't be + // resolved. just return the abs value in that case. + p = self._makeAbs(p) + rp.realpath(p, self.realpathCache, function (er, real) { + if (!er) + set[real] = true + else if (er.syscall === 'stat') + set[p] = true + else + self.emit('error', er) // srsly wtf right here + + if (--n === 0) { + self.matches[index] = set + cb() + } + }) + }) +} + +Glob.prototype._mark = function (p) { + return common.mark(this, p) +} + +Glob.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) +} + +Glob.prototype.abort = function () { + this.aborted = true + this.emit('abort') +} + +Glob.prototype.pause = function () { + if (!this.paused) { + this.paused = true + this.emit('pause') + } +} + +Glob.prototype.resume = function () { + if (this.paused) { + this.emit('resume') + this.paused = false + if (this._emitQueue.length) { + var eq = this._emitQueue.slice(0) + this._emitQueue.length = 0 + for (var i = 0; i < eq.length; i ++) { + var e = eq[i] + this._emitMatch(e[0], e[1]) + } + } + if (this._processQueue.length) { + var pq = this._processQueue.slice(0) + this._processQueue.length = 0 + for (var i = 0; i < pq.length; i ++) { + var p = pq[i] + this._processing-- + this._process(p[0], p[1], p[2], p[3]) + } + } + } +} + +Glob.prototype._process = function (pattern, index, inGlobStar, cb) { + assert(this instanceof Glob) + assert(typeof cb === 'function') + + if (this.aborted) + return + + this._processing++ + if (this.paused) { + this._processQueue.push([pattern, index, inGlobStar, cb]) + return + } - throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); -}; + //console.error('PROCESS %d', this._processing, pattern) -module.exports = function GetIntrinsic(name, allowMissing) { - if (typeof name !== 'string' || name.length === 0) { - throw new $TypeError('intrinsic name must be a non-empty string'); - } - if (arguments.length > 1 && typeof allowMissing !== 'boolean') { - throw new $TypeError('"allowMissing" argument must be a boolean'); - } + // Get the first [n] parts of pattern that are all strings. + var n = 0 + while (typeof pattern[n] === 'string') { + n ++ + } + // now n is the index of the first one that is *not* a string. - if ($exec(/^%?[^%]*%?$/, name) === null) { - throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); - } - var parts = stringToPath(name); - var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; + // see if there's anything else + var prefix + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index, cb) + return - var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); - var intrinsicRealName = intrinsic.name; - var value = intrinsic.value; - var skipFurtherCaching = false; + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null + break - var alias = intrinsic.alias; - if (alias) { - intrinsicBaseName = alias[0]; - $spliceApply(parts, $concat([0, 1], alias)); - } + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/') + break + } - for (var i = 1, isOwn = true; i < parts.length; i += 1) { - var part = parts[i]; - var first = $strSlice(part, 0, 1); - var last = $strSlice(part, -1); - if ( - ( - (first === '"' || first === "'" || first === '`') - || (last === '"' || last === "'" || last === '`') - ) - && first !== last - ) { - throw new $SyntaxError('property names with quotes must have matching quotes'); - } - if (part === 'constructor' || !isOwn) { - skipFurtherCaching = true; - } + var remain = pattern.slice(n) - intrinsicBaseName += '.' + part; - intrinsicRealName = '%' + intrinsicBaseName + '%'; + // get the list of entries. + var read + if (prefix === null) + read = '.' + else if (isAbsolute(prefix) || + isAbsolute(pattern.map(function (p) { + return typeof p === 'string' ? p : '[*]' + }).join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix + read = prefix + } else + read = prefix - if (hasOwn(INTRINSICS, intrinsicRealName)) { - value = INTRINSICS[intrinsicRealName]; - } else if (value != null) { - if (!(part in value)) { - if (!allowMissing) { - throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); - } - return void undefined; - } - if ($gOPD && (i + 1) >= parts.length) { - var desc = $gOPD(value, part); - isOwn = !!desc; + var abs = this._makeAbs(read) - // By convention, when a data property is converted to an accessor - // property to emulate a data property that does not suffer from - // the override mistake, that accessor's getter is marked with - // an `originalValue` property. Here, when we detect this, we - // uphold the illusion by pretending to see that original data - // property, i.e., returning the value rather than the getter - // itself. - if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { - value = desc.get; - } else { - value = value[part]; - } - } else { - isOwn = hasOwn(value, part); - value = value[part]; - } + //if ignored, skip _processing + if (childrenIgnored(this, read)) + return cb() - if (isOwn && !skipFurtherCaching) { - INTRINSICS[intrinsicRealName] = value; - } - } - } - return value; -}; + var isGlobStar = remain[0] === minimatch.GLOBSTAR + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) +} +Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this + this._readdir(abs, inGlobStar, function (er, entries) { + return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }) +} -/***/ }), +Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { -/***/ 36546: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // if the abs isn't a dir, then nothing can match! + if (!entries) + return cb() -"use strict"; + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0] + var negate = !!this.minimatch.negate + var rawGlob = pn._glob + var dotOk = this.dot || rawGlob.charAt(0) === '.' + var matchedEntries = [] + for (var i = 0; i < entries.length; i++) { + var e = entries[i] + if (e.charAt(0) !== '.' || dotOk) { + var m + if (negate && !prefix) { + m = !e.match(pn) + } else { + m = e.match(pn) + } + if (m) + matchedEntries.push(e) + } + } -var origSymbol = typeof Symbol !== 'undefined' && Symbol; -var hasSymbolSham = __nccwpck_require__(85968); + //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) -/** @type {import('.')} */ -module.exports = function hasNativeSymbols() { - if (typeof origSymbol !== 'function') { return false; } - if (typeof Symbol !== 'function') { return false; } - if (typeof origSymbol('foo') !== 'symbol') { return false; } - if (typeof Symbol('bar') !== 'symbol') { return false; } + var len = matchedEntries.length + // If there are no matched entries, then nothing matches. + if (len === 0) + return cb() - return hasSymbolSham(); -}; + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null) -/***/ }), + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e + else + e = prefix + e + } -/***/ 85968: -/***/ ((module) => { + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e) + } + this._emitMatch(index, e) + } + // This was the last one, and no stats were needed + return cb() + } -"use strict"; + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift() + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + var newPattern + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + this._process([e].concat(remain), index, inGlobStar, cb) + } + cb() +} +Glob.prototype._emitMatch = function (index, e) { + if (this.aborted) + return -/** @type {import('./shams')} */ -/* eslint complexity: [2, 18], max-statements: [2, 33] */ -module.exports = function hasSymbols() { - if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } - if (typeof Symbol.iterator === 'symbol') { return true; } + if (isIgnored(this, e)) + return - /** @type {{ [k in symbol]?: unknown }} */ - var obj = {}; - var sym = Symbol('test'); - var symObj = Object(sym); - if (typeof sym === 'string') { return false; } + if (this.paused) { + this._emitQueue.push([index, e]) + return + } - if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } - if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } + var abs = isAbsolute(e) ? e : this._makeAbs(e) - // temp disabled per https://github.com/ljharb/object.assign/issues/17 - // if (sym instanceof Symbol) { return false; } - // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 - // if (!(symObj instanceof Symbol)) { return false; } + if (this.mark) + e = this._mark(e) - // if (typeof Symbol.prototype.toString !== 'function') { return false; } - // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } + if (this.absolute) + e = abs - var symVal = 42; - obj[sym] = symVal; - for (var _ in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop - if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } + if (this.matches[index][e]) + return - if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } + if (this.nodir) { + var c = this.cache[abs] + if (c === 'DIR' || Array.isArray(c)) + return + } - var syms = Object.getOwnPropertySymbols(obj); - if (syms.length !== 1 || syms[0] !== sym) { return false; } + this.matches[index][e] = true - if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } + var st = this.statCache[abs] + if (st) + this.emit('stat', e, st) - if (typeof Object.getOwnPropertyDescriptor === 'function') { - // eslint-disable-next-line no-extra-parens - var descriptor = /** @type {PropertyDescriptor} */ (Object.getOwnPropertyDescriptor(obj, sym)); - if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } - } + this.emit('match', e) +} - return true; -}; +Glob.prototype._readdirInGlobStar = function (abs, cb) { + if (this.aborted) + return + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false, cb) -/***/ }), + var lstatkey = 'lstat\0' + abs + var self = this + var lstatcb = inflight(lstatkey, lstatcb_) -/***/ 13752: -/***/ ((module) => { + if (lstatcb) + self.fs.lstat(abs, lstatcb) -"use strict"; + function lstatcb_ (er, lstat) { + if (er && er.code === 'ENOENT') + return cb() + var isSym = lstat && lstat.isSymbolicLink() + self.symlinks[abs] = isSym -/** @type {import('./gOPD')} */ -module.exports = Object.getOwnPropertyDescriptor; + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) { + self.cache[abs] = 'FILE' + cb() + } else + self._readdir(abs, false, cb) + } +} +Glob.prototype._readdir = function (abs, inGlobStar, cb) { + if (this.aborted) + return -/***/ }), + cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) + if (!cb) + return -/***/ 64868: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + //console.error('RD %j %j', +inGlobStar, abs) + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs, cb) -"use strict"; + if (ownProp(this.cache, abs)) { + var c = this.cache[abs] + if (!c || c === 'FILE') + return cb() + if (Array.isArray(c)) + return cb(null, c) + } -/** @type {import('.')} */ -var $gOPD = __nccwpck_require__(13752); + var self = this + self.fs.readdir(abs, readdirCb(this, abs, cb)) +} -if ($gOPD) { - try { - $gOPD([], 'length'); - } catch (e) { - // IE 8 has a broken gOPD - $gOPD = null; - } +function readdirCb (self, abs, cb) { + return function (er, entries) { + if (er) + self._readdirError(abs, er, cb) + else + self._readdirEntries(abs, entries, cb) + } } -module.exports = $gOPD; +Glob.prototype._readdirEntries = function (abs, entries, cb) { + if (this.aborted) + return + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i] + if (abs === '/') + e = abs + e + else + e = abs + '/' + e + this.cache[e] = true + } + } -/***/ }), + this.cache[abs] = entries + return cb(null, entries) +} -/***/ 50499: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +Glob.prototype._readdirError = function (f, er, cb) { + if (this.aborted) + return -"use strict"; + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f) + this.cache[abs] = 'FILE' + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd) + error.path = this.cwd + error.code = er.code + this.emit('error', error) + this.abort() + } + break + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false + break -var hasSymbols = __nccwpck_require__(57747); + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false + if (this.strict) { + this.emit('error', er) + // If the error is handled, then we abort + // if not, we threw out of here + this.abort() + } + if (!this.silent) + console.error('glob error', er) + break + } -/** @type {import('.')} */ -module.exports = function hasToStringTagShams() { - return hasSymbols() && !!Symbol.toStringTag; -}; + return cb() +} +Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this + this._readdir(abs, inGlobStar, function (er, entries) { + self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }) +} -/***/ }), -/***/ 38171: -/***/ ((module) => { +Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + //console.error('pgs2', prefix, remain[0], entries) -"use strict"; + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return cb() + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1) + var gspref = prefix ? [ prefix ] : [] + var noGlobStar = gspref.concat(remainWithoutGlobStar) -var hasOwn = Object.prototype.hasOwnProperty; -var toStr = Object.prototype.toString; -var defineProperty = Object.defineProperty; -var gOPD = Object.getOwnPropertyDescriptor; + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false, cb) -var isArray = function isArray(arr) { - if (typeof Array.isArray === 'function') { - return Array.isArray(arr); - } + var isSym = this.symlinks[abs] + var len = entries.length - return toStr.call(arr) === '[object Array]'; -}; + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return cb() -var isPlainObject = function isPlainObject(obj) { - if (!obj || toStr.call(obj) !== '[object Object]') { - return false; - } + for (var i = 0; i < len; i++) { + var e = entries[i] + if (e.charAt(0) === '.' && !this.dot) + continue - var hasOwnConstructor = hasOwn.call(obj, 'constructor'); - var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); - // Not own constructor property must be Object - if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { - return false; - } + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar) + this._process(instead, index, true, cb) - // Own properties are enumerated firstly, so to speed up, - // if last one is own, then all properties are own. - var key; - for (key in obj) { /**/ } + var below = gspref.concat(entries[i], remain) + this._process(below, index, true, cb) + } - return typeof key === 'undefined' || hasOwn.call(obj, key); -}; + cb() +} -// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target -var setProperty = function setProperty(target, options) { - if (defineProperty && options.name === '__proto__') { - defineProperty(target, options.name, { - enumerable: true, - configurable: true, - value: options.newValue, - writable: true - }); - } else { - target[options.name] = options.newValue; - } -}; +Glob.prototype._processSimple = function (prefix, index, cb) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var self = this + this._stat(prefix, function (er, exists) { + self._processSimple2(prefix, index, er, exists, cb) + }) +} +Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { -// Return undefined instead of __proto__ if '__proto__' is not an own property -var getProperty = function getProperty(obj, name) { - if (name === '__proto__') { - if (!hasOwn.call(obj, name)) { - return void 0; - } else if (gOPD) { - // In early versions of node, obj['__proto__'] is buggy when obj has - // __proto__ as an own property. Object.getOwnPropertyDescriptor() works. - return gOPD(obj, name).value; - } - } + //console.error('ps2', prefix, exists) - return obj[name]; -}; + if (!this.matches[index]) + this.matches[index] = Object.create(null) -module.exports = function extend() { - var options, name, src, copy, copyIsArray, clone; - var target = arguments[0]; - var i = 1; - var length = arguments.length; - var deep = false; + // If it doesn't exist, then just mark the lack of results + if (!exists) + return cb() - // Handle a deep copy situation - if (typeof target === 'boolean') { - deep = target; - target = arguments[1] || {}; - // skip the boolean and the target - i = 2; - } - if (target == null || (typeof target !== 'object' && typeof target !== 'function')) { - target = {}; - } + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix) + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix) + } else { + prefix = path.resolve(this.root, prefix) + if (trail) + prefix += '/' + } + } - for (; i < length; ++i) { - options = arguments[i]; - // Only deal with non-null/undefined values - if (options != null) { - // Extend the base object - for (name in options) { - src = getProperty(target, name); - copy = getProperty(options, name); + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/') - // Prevent never-ending loop - if (target !== copy) { - // Recurse if we're merging plain objects or arrays - if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { - if (copyIsArray) { - copyIsArray = false; - clone = src && isArray(src) ? src : []; - } else { - clone = src && isPlainObject(src) ? src : {}; - } + // Mark this as a match + this._emitMatch(index, prefix) + cb() +} - // Never move original objects, clone them - setProperty(target, { name: name, newValue: extend(deep, clone, copy) }); +// Returns either 'DIR', 'FILE', or false +Glob.prototype._stat = function (f, cb) { + var abs = this._makeAbs(f) + var needDir = f.slice(-1) === '/' - // Don't bring in undefined values - } else if (typeof copy !== 'undefined') { - setProperty(target, { name: name, newValue: copy }); - } - } - } - } - } + if (f.length > this.maxLength) + return cb() - // Return the modified object - return target; -}; + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs] + if (Array.isArray(c)) + c = 'DIR' -/***/ }), + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return cb(null, c) -/***/ 87264: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (needDir && c === 'FILE') + return cb() -/* - * extsprintf.js: extended POSIX-style sprintf - */ + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } -var mod_assert = __nccwpck_require__(39491); -var mod_util = __nccwpck_require__(73837); + var exists + var stat = this.statCache[abs] + if (stat !== undefined) { + if (stat === false) + return cb(null, stat) + else { + var type = stat.isDirectory() ? 'DIR' : 'FILE' + if (needDir && type === 'FILE') + return cb() + else + return cb(null, type, stat) + } + } -/* - * Public interface - */ -exports.sprintf = jsSprintf; -exports.printf = jsPrintf; -exports.fprintf = jsFprintf; + var self = this + var statcb = inflight('stat\0' + abs, lstatcb_) + if (statcb) + self.fs.lstat(abs, statcb) -/* - * Stripped down version of s[n]printf(3c). We make a best effort to throw an - * exception when given a format string we don't understand, rather than - * ignoring it, so that we won't break existing programs if/when we go implement - * the rest of this. - * - * This implementation currently supports specifying - * - field alignment ('-' flag), - * - zero-pad ('0' flag) - * - always show numeric sign ('+' flag), - * - field width - * - conversions for strings, decimal integers, and floats (numbers). - * - argument size specifiers. These are all accepted but ignored, since - * Javascript has no notion of the physical size of an argument. - * - * Everything else is currently unsupported, most notably precision, unsigned - * numbers, non-decimal numbers, and characters. - */ -function jsSprintf(fmt) -{ - var regex = [ - '([^%]*)', /* normal text */ - '%', /* start of format */ - '([\'\\-+ #0]*?)', /* flags (optional) */ - '([1-9]\\d*)?', /* width (optional) */ - '(\\.([1-9]\\d*))?', /* precision (optional) */ - '[lhjztL]*?', /* length mods (ignored) */ - '([diouxXfFeEgGaAcCsSp%jr])' /* conversion */ - ].join(''); + function lstatcb_ (er, lstat) { + if (lstat && lstat.isSymbolicLink()) { + // If it's a symlink, then treat it as the target, unless + // the target does not exist, then treat it as a file. + return self.fs.stat(abs, function (er, stat) { + if (er) + self._stat2(f, abs, null, lstat, cb) + else + self._stat2(f, abs, er, stat, cb) + }) + } else { + self._stat2(f, abs, er, lstat, cb) + } + } +} - var re = new RegExp(regex); - var args = Array.prototype.slice.call(arguments, 1); - var flags, width, precision, conversion; - var left, pad, sign, arg, match; - var ret = ''; - var argn = 1; +Glob.prototype._stat2 = function (f, abs, er, stat, cb) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false + return cb() + } - mod_assert.equal('string', typeof (fmt)); + var needDir = f.slice(-1) === '/' + this.statCache[abs] = stat - while ((match = re.exec(fmt)) !== null) { - ret += match[1]; - fmt = fmt.substring(match[0].length); + if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) + return cb(null, false, stat) - flags = match[2] || ''; - width = match[3] || 0; - precision = match[4] || ''; - conversion = match[6]; - left = false; - sign = false; - pad = ' '; + var c = true + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE' + this.cache[abs] = this.cache[abs] || c - if (conversion == '%') { - ret += '%'; - continue; - } + if (needDir && c === 'FILE') + return cb() - if (args.length === 0) - throw (new Error('too few args to sprintf')); + return cb(null, c, stat) +} - arg = args.shift(); - argn++; - if (flags.match(/[\' #]/)) - throw (new Error( - 'unsupported flags: ' + flags)); +/***/ }), - if (precision.length > 0) - throw (new Error( - 'non-zero precision not supported')); +/***/ 29010: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (flags.match(/-/)) - left = true; +module.exports = globSync +globSync.GlobSync = GlobSync - if (flags.match(/0/)) - pad = '0'; +var rp = __nccwpck_require__(46863) +var minimatch = __nccwpck_require__(83973) +var Minimatch = minimatch.Minimatch +var Glob = (__nccwpck_require__(91957).Glob) +var util = __nccwpck_require__(73837) +var path = __nccwpck_require__(71017) +var assert = __nccwpck_require__(39491) +var isAbsolute = __nccwpck_require__(38714) +var common = __nccwpck_require__(47625) +var setopts = common.setopts +var ownProp = common.ownProp +var childrenIgnored = common.childrenIgnored +var isIgnored = common.isIgnored - if (flags.match(/\+/)) - sign = true; +function globSync (pattern, options) { + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') - switch (conversion) { - case 's': - if (arg === undefined || arg === null) - throw (new Error('argument ' + argn + - ': attempted to print undefined or null ' + - 'as a string')); - ret += doPad(pad, width, left, arg.toString()); - break; + return new GlobSync(pattern, options).found +} - case 'd': - arg = Math.floor(arg); - /*jsl:fallthru*/ - case 'f': - sign = sign && arg > 0 ? '+' : ''; - ret += sign + doPad(pad, width, left, - arg.toString()); - break; +function GlobSync (pattern, options) { + if (!pattern) + throw new Error('must provide pattern') - case 'x': - ret += doPad(pad, width, left, arg.toString(16)); - break; + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') - case 'j': /* non-standard */ - if (width === 0) - width = 10; - ret += mod_util.inspect(arg, false, width); - break; + if (!(this instanceof GlobSync)) + return new GlobSync(pattern, options) - case 'r': /* non-standard */ - ret += dumpException(arg); - break; + setopts(this, pattern, options) - default: - throw (new Error('unsupported conversion: ' + - conversion)); - } - } + if (this.noprocess) + return this - ret += fmt; - return (ret); + var n = this.minimatch.set.length + this.matches = new Array(n) + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false) + } + this._finish() } -function jsPrintf() { - var args = Array.prototype.slice.call(arguments); - args.unshift(process.stdout); - jsFprintf.apply(null, args); +GlobSync.prototype._finish = function () { + assert.ok(this instanceof GlobSync) + if (this.realpath) { + var self = this + this.matches.forEach(function (matchset, index) { + var set = self.matches[index] = Object.create(null) + for (var p in matchset) { + try { + p = self._makeAbs(p) + var real = rp.realpathSync(p, self.realpathCache) + set[real] = true + } catch (er) { + if (er.syscall === 'stat') + set[self._makeAbs(p)] = true + else + throw er + } + } + }) + } + common.finish(this) } -function jsFprintf(stream) { - var args = Array.prototype.slice.call(arguments, 1); - return (stream.write(jsSprintf.apply(this, args))); -} -function doPad(chr, width, left, str) -{ - var ret = str; +GlobSync.prototype._process = function (pattern, index, inGlobStar) { + assert.ok(this instanceof GlobSync) - while (ret.length < width) { - if (left) - ret += chr; - else - ret = chr + ret; - } + // Get the first [n] parts of pattern that are all strings. + var n = 0 + while (typeof pattern[n] === 'string') { + n ++ + } + // now n is the index of the first one that is *not* a string. - return (ret); -} + // See if there's anything else + var prefix + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index) + return -/* - * This function dumps long stack traces for exceptions having a cause() method. - * See node-verror for an example. - */ -function dumpException(ex) -{ - var ret; + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null + break - if (!(ex instanceof Error)) - throw (new Error(jsSprintf('invalid type for %%r: %j', ex))); + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/') + break + } - /* Note that V8 prepends "ex.stack" with ex.toString(). */ - ret = 'EXCEPTION: ' + ex.constructor.name + ': ' + ex.stack; + var remain = pattern.slice(n) - if (ex.cause && typeof (ex.cause) === 'function') { - var cex = ex.cause(); - if (cex) { - ret += '\nCaused by: ' + dumpException(cex); - } - } + // get the list of entries. + var read + if (prefix === null) + read = '.' + else if (isAbsolute(prefix) || + isAbsolute(pattern.map(function (p) { + return typeof p === 'string' ? p : '[*]' + }).join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix + read = prefix + } else + read = prefix - return (ret); -} + var abs = this._makeAbs(read) + //if ignored, skip processing + if (childrenIgnored(this, read)) + return -/***/ }), + var isGlobStar = remain[0] === minimatch.GLOBSTAR + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar) +} -/***/ 28206: -/***/ ((module) => { -"use strict"; +GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { + var entries = this._readdir(abs, inGlobStar) + // if the abs isn't a dir, then nothing can match! + if (!entries) + return -// do not edit .js files directly - edit src/index.jst + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0] + var negate = !!this.minimatch.negate + var rawGlob = pn._glob + var dotOk = this.dot || rawGlob.charAt(0) === '.' + var matchedEntries = [] + for (var i = 0; i < entries.length; i++) { + var e = entries[i] + if (e.charAt(0) !== '.' || dotOk) { + var m + if (negate && !prefix) { + m = !e.match(pn) + } else { + m = e.match(pn) + } + if (m) + matchedEntries.push(e) + } + } + var len = matchedEntries.length + // If there are no matched entries, then nothing matches. + if (len === 0) + return -module.exports = function equal(a, b) { - if (a === b) return true; + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. - if (a && b && typeof a == 'object' && typeof b == 'object') { - if (a.constructor !== b.constructor) return false; + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null) - var length, i, keys; - if (Array.isArray(a)) { - length = a.length; - if (length != b.length) return false; - for (i = length; i-- !== 0;) - if (!equal(a[i], b[i])) return false; - return true; + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + if (prefix) { + if (prefix.slice(-1) !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e) + } + this._emitMatch(index, e) } + // This was the last one, and no stats were needed + return + } + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift() + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + var newPattern + if (prefix) + newPattern = [prefix, e] + else + newPattern = [e] + this._process(newPattern.concat(remain), index, inGlobStar) + } +} - if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; - if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); - if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); +GlobSync.prototype._emitMatch = function (index, e) { + if (isIgnored(this, e)) + return - keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) return false; + var abs = this._makeAbs(e) - for (i = length; i-- !== 0;) - if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + if (this.mark) + e = this._mark(e) - for (i = length; i-- !== 0;) { - var key = keys[i]; + if (this.absolute) { + e = abs + } - if (!equal(a[key], b[key])) return false; - } + if (this.matches[index][e]) + return - return true; + if (this.nodir) { + var c = this.cache[abs] + if (c === 'DIR' || Array.isArray(c)) + return } - // true if both NaN, false otherwise - return a!==a && b!==b; -}; + this.matches[index][e] = true + if (this.stat) + this._stat(e) +} -/***/ }), -/***/ 30969: -/***/ ((module) => { +GlobSync.prototype._readdirInGlobStar = function (abs) { + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false) -"use strict"; + var entries + var lstat + var stat + try { + lstat = this.fs.lstatSync(abs) + } catch (er) { + if (er.code === 'ENOENT') { + // lstat failed, doesn't exist + return null + } + } + var isSym = lstat && lstat.isSymbolicLink() + this.symlinks[abs] = isSym -module.exports = function (data, opts) { - if (!opts) opts = {}; - if (typeof opts === 'function') opts = { cmp: opts }; - var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false; + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) + this.cache[abs] = 'FILE' + else + entries = this._readdir(abs, false) - var cmp = opts.cmp && (function (f) { - return function (node) { - return function (a, b) { - var aobj = { key: a, value: node[a] }; - var bobj = { key: b, value: node[b] }; - return f(aobj, bobj); - }; - }; - })(opts.cmp); + return entries +} - var seen = []; - return (function stringify (node) { - if (node && node.toJSON && typeof node.toJSON === 'function') { - node = node.toJSON(); - } +GlobSync.prototype._readdir = function (abs, inGlobStar) { + var entries - if (node === undefined) return; - if (typeof node == 'number') return isFinite(node) ? '' + node : 'null'; - if (typeof node !== 'object') return JSON.stringify(node); + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs) - var i, out; - if (Array.isArray(node)) { - out = '['; - for (i = 0; i < node.length; i++) { - if (i) out += ','; - out += stringify(node[i]) || 'null'; - } - return out + ']'; - } + if (ownProp(this.cache, abs)) { + var c = this.cache[abs] + if (!c || c === 'FILE') + return null - if (node === null) return 'null'; + if (Array.isArray(c)) + return c + } - if (seen.indexOf(node) !== -1) { - if (cycles) return JSON.stringify('__cycle__'); - throw new TypeError('Converting circular structure to JSON'); - } + try { + return this._readdirEntries(abs, this.fs.readdirSync(abs)) + } catch (er) { + this._readdirError(abs, er) + return null + } +} - var seenIndex = seen.push(node) - 1; - var keys = Object.keys(node).sort(cmp && cmp(node)); - out = ''; - for (i = 0; i < keys.length; i++) { - var key = keys[i]; - var value = stringify(node[key]); +GlobSync.prototype._readdirEntries = function (abs, entries) { + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i] + if (abs === '/') + e = abs + e + else + e = abs + '/' + e + this.cache[e] = true + } + } - if (!value) continue; - if (out) out += ','; - out += JSON.stringify(key) + ':' + value; - } - seen.splice(seenIndex, 1); - return '{' + out + '}'; - })(data); -}; + this.cache[abs] = entries + + // mark and cache dir-ness + return entries +} +GlobSync.prototype._readdirError = function (f, er) { + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f) + this.cache[abs] = 'FILE' + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd) + error.path = this.cwd + error.code = er.code + throw error + } + break -/***/ }), + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false + break -/***/ 12603: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false + if (this.strict) + throw er + if (!this.silent) + console.error('glob error', er) + break + } +} -"use strict"; +GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { + var entries = this._readdir(abs, inGlobStar) -const validator = __nccwpck_require__(61739); -const XMLParser = __nccwpck_require__(42380); -const XMLBuilder = __nccwpck_require__(80660); + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return -module.exports = { - XMLParser: XMLParser, - XMLValidator: validator, - XMLBuilder: XMLBuilder -} + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1) + var gspref = prefix ? [ prefix ] : [] + var noGlobStar = gspref.concat(remainWithoutGlobStar) -/***/ }), + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false) -/***/ 38280: -/***/ ((__unused_webpack_module, exports) => { + var len = entries.length + var isSym = this.symlinks[abs] -"use strict"; + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return + for (var i = 0; i < len; i++) { + var e = entries[i] + if (e.charAt(0) === '.' && !this.dot) + continue -const nameStartChar = ':A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD'; -const nameChar = nameStartChar + '\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040'; -const nameRegexp = '[' + nameStartChar + '][' + nameChar + ']*' -const regexName = new RegExp('^' + nameRegexp + '$'); + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar) + this._process(instead, index, true) -const getAllMatches = function(string, regex) { - const matches = []; - let match = regex.exec(string); - while (match) { - const allmatches = []; - allmatches.startIndex = regex.lastIndex - match[0].length; - const len = match.length; - for (let index = 0; index < len; index++) { - allmatches.push(match[index]); - } - matches.push(allmatches); - match = regex.exec(string); + var below = gspref.concat(entries[i], remain) + this._process(below, index, true) } - return matches; -}; +} -const isName = function(string) { - const match = regexName.exec(string); - return !(match === null || typeof match === 'undefined'); -}; +GlobSync.prototype._processSimple = function (prefix, index) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var exists = this._stat(prefix) -exports.isExist = function(v) { - return typeof v !== 'undefined'; -}; + if (!this.matches[index]) + this.matches[index] = Object.create(null) -exports.isEmptyObject = function(obj) { - return Object.keys(obj).length === 0; -}; + // If it doesn't exist, then just mark the lack of results + if (!exists) + return -/** - * Copy all the properties of a into b. - * @param {*} target - * @param {*} a - */ -exports.merge = function(target, a, arrayMode) { - if (a) { - const keys = Object.keys(a); // will return an array of own properties - const len = keys.length; //don't make it inline - for (let i = 0; i < len; i++) { - if (arrayMode === 'strict') { - target[keys[i]] = [ a[keys[i]] ]; - } else { - target[keys[i]] = a[keys[i]]; - } + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix) + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix) + } else { + prefix = path.resolve(this.root, prefix) + if (trail) + prefix += '/' } } -}; -/* exports.merge =function (b,a){ - return Object.assign(b,a); -} */ -exports.getValue = function(v) { - if (exports.isExist(v)) { - return v; - } else { - return ''; - } -}; + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/') -// const fakeCall = function(a) {return a;}; -// const fakeCallNoReturn = function() {}; + // Mark this as a match + this._emitMatch(index, prefix) +} -exports.isName = isName; -exports.getAllMatches = getAllMatches; -exports.nameRegexp = nameRegexp; +// Returns either 'DIR', 'FILE', or false +GlobSync.prototype._stat = function (f) { + var abs = this._makeAbs(f) + var needDir = f.slice(-1) === '/' + if (f.length > this.maxLength) + return false -/***/ }), + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs] -/***/ 61739: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (Array.isArray(c)) + c = 'DIR' -"use strict"; + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return c + if (needDir && c === 'FILE') + return false -const util = __nccwpck_require__(38280); + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } -const defaultOptions = { - allowBooleanAttributes: false, //A tag can have attributes without any value - unpairedTags: [] -}; + var exists + var stat = this.statCache[abs] + if (!stat) { + var lstat + try { + lstat = this.fs.lstatSync(abs) + } catch (er) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false + return false + } + } -//const tagsPattern = new RegExp("<\\/?([\\w:\\-_\.]+)\\s*\/?>","g"); -exports.validate = function (xmlData, options) { - options = Object.assign({}, defaultOptions, options); + if (lstat && lstat.isSymbolicLink()) { + try { + stat = this.fs.statSync(abs) + } catch (er) { + stat = lstat + } + } else { + stat = lstat + } + } - //xmlData = xmlData.replace(/(\r\n|\n|\r)/gm,"");//make it single line - //xmlData = xmlData.replace(/(^\s*<\?xml.*?\?>)/g,"");//Remove XML starting tag - //xmlData = xmlData.replace(/()/g,"");//Remove DOCTYPE - const tags = []; - let tagFound = false; + this.statCache[abs] = stat - //indicates that the root tag has been closed (aka. depth 0 has been reached) - let reachedRoot = false; + var c = true + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE' - if (xmlData[0] === '\ufeff') { - // check for byte order mark (BOM) - xmlData = xmlData.substr(1); - } - - for (let i = 0; i < xmlData.length; i++) { + this.cache[abs] = this.cache[abs] || c - if (xmlData[i] === '<' && xmlData[i+1] === '?') { - i+=2; - i = readPI(xmlData,i); - if (i.err) return i; - }else if (xmlData[i] === '<') { - //starting of tag - //read until you reach to '>' avoiding any '>' in attribute value - let tagStartPos = i; - i++; - - if (xmlData[i] === '!') { - i = readCommentAndCDATA(xmlData, i); - continue; - } else { - let closingTag = false; - if (xmlData[i] === '/') { - //closing tag - closingTag = true; - i++; - } - //read tagname - let tagName = ''; - for (; i < xmlData.length && - xmlData[i] !== '>' && - xmlData[i] !== ' ' && - xmlData[i] !== '\t' && - xmlData[i] !== '\n' && - xmlData[i] !== '\r'; i++ - ) { - tagName += xmlData[i]; - } - tagName = tagName.trim(); - //console.log(tagName); + if (needDir && c === 'FILE') + return false - if (tagName[tagName.length - 1] === '/') { - //self closing tag without attributes - tagName = tagName.substring(0, tagName.length - 1); - //continue; - i--; - } - if (!validateTagName(tagName)) { - let msg; - if (tagName.trim().length === 0) { - msg = "Invalid space after '<'."; - } else { - msg = "Tag '"+tagName+"' is an invalid name."; - } - return getErrorObject('InvalidTag', msg, getLineNumberForPosition(xmlData, i)); - } + return c +} - const result = readAttributeStr(xmlData, i); - if (result === false) { - return getErrorObject('InvalidAttr', "Attributes for '"+tagName+"' have open quote.", getLineNumberForPosition(xmlData, i)); - } - let attrStr = result.value; - i = result.index; +GlobSync.prototype._mark = function (p) { + return common.mark(this, p) +} - if (attrStr[attrStr.length - 1] === '/') { - //self closing tag - const attrStrStart = i - attrStr.length; - attrStr = attrStr.substring(0, attrStr.length - 1); - const isValid = validateAttributeString(attrStr, options); - if (isValid === true) { - tagFound = true; - //continue; //text may presents after self closing tag - } else { - //the result from the nested function returns the position of the error within the attribute - //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute - //this gives us the absolute index in the entire xml, which we can use to find the line at last - return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line)); - } - } else if (closingTag) { - if (!result.tagClosed) { - return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' doesn't have proper closing.", getLineNumberForPosition(xmlData, i)); - } else if (attrStr.trim().length > 0) { - return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos)); - } else if (tags.length === 0) { - return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos)); - } else { - const otg = tags.pop(); - if (tagName !== otg.tagName) { - let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos); - return getErrorObject('InvalidTag', - "Expected closing tag '"+otg.tagName+"' (opened in line "+openPos.line+", col "+openPos.col+") instead of closing tag '"+tagName+"'.", - getLineNumberForPosition(xmlData, tagStartPos)); - } +GlobSync.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) +} - //when there are no more tags, we reached the root level. - if (tags.length == 0) { - reachedRoot = true; - } - } - } else { - const isValid = validateAttributeString(attrStr, options); - if (isValid !== true) { - //the result from the nested function returns the position of the error within the attribute - //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute - //this gives us the absolute index in the entire xml, which we can use to find the line at last - return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line)); - } - //if the root level has been reached before ... - if (reachedRoot === true) { - return getErrorObject('InvalidXml', 'Multiple possible root nodes found.', getLineNumberForPosition(xmlData, i)); - } else if(options.unpairedTags.indexOf(tagName) !== -1){ - //don't push into stack - } else { - tags.push({tagName, tagStartPos}); - } - tagFound = true; - } +/***/ }), - //skip tag text value - //It may include comments and CDATA value - for (i++; i < xmlData.length; i++) { - if (xmlData[i] === '<') { - if (xmlData[i + 1] === '!') { - //comment or CADATA - i++; - i = readCommentAndCDATA(xmlData, i); - continue; - } else if (xmlData[i+1] === '?') { - i = readPI(xmlData, ++i); - if (i.err) return i; - } else{ - break; +/***/ 26457: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const types_1 = __nccwpck_require__(64597); +function createRejection(error, ...beforeErrorGroups) { + const promise = (async () => { + if (error instanceof types_1.RequestError) { + try { + for (const hooks of beforeErrorGroups) { + if (hooks) { + for (const hook of hooks) { + // eslint-disable-next-line no-await-in-loop + error = await hook(error); + } + } + } } - } else if (xmlData[i] === '&') { - const afterAmp = validateAmpersand(xmlData, i); - if (afterAmp == -1) - return getErrorObject('InvalidChar', "char '&' is not expected.", getLineNumberForPosition(xmlData, i)); - i = afterAmp; - }else{ - if (reachedRoot === true && !isWhiteSpace(xmlData[i])) { - return getErrorObject('InvalidXml', "Extra text at the end", getLineNumberForPosition(xmlData, i)); + catch (error_) { + error = error_; } - } - } //end of reading tag text value - if (xmlData[i] === '<') { - i--; } - } - } else { - if ( isWhiteSpace(xmlData[i])) { - continue; - } - return getErrorObject('InvalidChar', "char '"+xmlData[i]+"' is not expected.", getLineNumberForPosition(xmlData, i)); - } - } - - if (!tagFound) { - return getErrorObject('InvalidXml', 'Start tag expected.', 1); - }else if (tags.length == 1) { - return getErrorObject('InvalidTag', "Unclosed tag '"+tags[0].tagName+"'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos)); - }else if (tags.length > 0) { - return getErrorObject('InvalidXml', "Invalid '"+ - JSON.stringify(tags.map(t => t.tagName), null, 4).replace(/\r?\n/g, '')+ - "' found.", {line: 1, col: 1}); - } - - return true; -}; - -function isWhiteSpace(char){ - return char === ' ' || char === '\t' || char === '\n' || char === '\r'; -} -/** - * Read Processing insstructions and skip - * @param {*} xmlData - * @param {*} i - */ -function readPI(xmlData, i) { - const start = i; - for (; i < xmlData.length; i++) { - if (xmlData[i] == '?' || xmlData[i] == ' ') { - //tagname - const tagname = xmlData.substr(start, i - start); - if (i > 5 && tagname === 'xml') { - return getErrorObject('InvalidXml', 'XML declaration allowed only at the start of the document.', getLineNumberForPosition(xmlData, i)); - } else if (xmlData[i] == '?' && xmlData[i + 1] == '>') { - //check if valid attribut string - i++; - break; - } else { - continue; - } - } - } - return i; + throw error; + })(); + const returnPromise = () => promise; + promise.json = returnPromise; + promise.text = returnPromise; + promise.buffer = returnPromise; + promise.on = returnPromise; + return promise; } +exports["default"] = createRejection; -function readCommentAndCDATA(xmlData, i) { - if (xmlData.length > i + 5 && xmlData[i + 1] === '-' && xmlData[i + 2] === '-') { - //comment - for (i += 3; i < xmlData.length; i++) { - if (xmlData[i] === '-' && xmlData[i + 1] === '-' && xmlData[i + 2] === '>') { - i += 2; - break; - } - } - } else if ( - xmlData.length > i + 8 && - xmlData[i + 1] === 'D' && - xmlData[i + 2] === 'O' && - xmlData[i + 3] === 'C' && - xmlData[i + 4] === 'T' && - xmlData[i + 5] === 'Y' && - xmlData[i + 6] === 'P' && - xmlData[i + 7] === 'E' - ) { - let angleBracketsCount = 1; - for (i += 8; i < xmlData.length; i++) { - if (xmlData[i] === '<') { - angleBracketsCount++; - } else if (xmlData[i] === '>') { - angleBracketsCount--; - if (angleBracketsCount === 0) { - break; - } - } - } - } else if ( - xmlData.length > i + 9 && - xmlData[i + 1] === '[' && - xmlData[i + 2] === 'C' && - xmlData[i + 3] === 'D' && - xmlData[i + 4] === 'A' && - xmlData[i + 5] === 'T' && - xmlData[i + 6] === 'A' && - xmlData[i + 7] === '[' - ) { - for (i += 8; i < xmlData.length; i++) { - if (xmlData[i] === ']' && xmlData[i + 1] === ']' && xmlData[i + 2] === '>') { - i += 2; - break; - } - } - } - return i; -} +/***/ }), -const doubleQuote = '"'; -const singleQuote = "'"; +/***/ 36056: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -/** - * Keep reading xmlData until '<' is found outside the attribute value. - * @param {string} xmlData - * @param {number} i - */ -function readAttributeStr(xmlData, i) { - let attrStr = ''; - let startChar = ''; - let tagClosed = false; - for (; i < xmlData.length; i++) { - if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) { - if (startChar === '') { - startChar = xmlData[i]; - } else if (startChar !== xmlData[i]) { - //if vaue is enclosed with double quote then single quotes are allowed inside the value and vice versa - } else { - startChar = ''; - } - } else if (xmlData[i] === '>') { - if (startChar === '') { - tagClosed = true; - break; - } - } - attrStr += xmlData[i]; - } - if (startChar !== '') { - return false; - } +"use strict"; - return { - value: attrStr, - index: i, - tagClosed: tagClosed - }; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (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 })); +const events_1 = __nccwpck_require__(82361); +const is_1 = __nccwpck_require__(7678); +const PCancelable = __nccwpck_require__(19072); +const types_1 = __nccwpck_require__(64597); +const parse_body_1 = __nccwpck_require__(88220); +const core_1 = __nccwpck_require__(60094); +const proxy_events_1 = __nccwpck_require__(53021); +const get_buffer_1 = __nccwpck_require__(34500); +const is_response_ok_1 = __nccwpck_require__(49298); +const proxiedRequestEvents = [ + 'request', + 'response', + 'redirect', + 'uploadProgress', + 'downloadProgress' +]; +function asPromise(normalizedOptions) { + let globalRequest; + let globalResponse; + const emitter = new events_1.EventEmitter(); + const promise = new PCancelable((resolve, reject, onCancel) => { + const makeRequest = (retryCount) => { + const request = new core_1.default(undefined, normalizedOptions); + request.retryCount = retryCount; + request._noPipe = true; + onCancel(() => request.destroy()); + onCancel.shouldReject = false; + onCancel(() => reject(new types_1.CancelError(request))); + globalRequest = request; + request.once('response', async (response) => { + var _a; + response.retryCount = retryCount; + if (response.request.aborted) { + // Canceled while downloading - will throw a `CancelError` or `TimeoutError` error + return; + } + // Download body + let rawBody; + try { + rawBody = await get_buffer_1.default(request); + response.rawBody = rawBody; + } + catch (_b) { + // The same error is caught below. + // See request.once('error') + return; + } + if (request._isAboutToError) { + return; + } + // Parse body + const contentEncoding = ((_a = response.headers['content-encoding']) !== null && _a !== void 0 ? _a : '').toLowerCase(); + const isCompressed = ['gzip', 'deflate', 'br'].includes(contentEncoding); + const { options } = request; + if (isCompressed && !options.decompress) { + response.body = rawBody; + } + else { + try { + response.body = parse_body_1.default(response, options.responseType, options.parseJson, options.encoding); + } + catch (error) { + // Fallback to `utf8` + response.body = rawBody.toString(); + if (is_response_ok_1.isResponseOk(response)) { + request._beforeError(error); + return; + } + } + } + try { + for (const [index, hook] of options.hooks.afterResponse.entries()) { + // @ts-expect-error TS doesn't notice that CancelableRequest is a Promise + // eslint-disable-next-line no-await-in-loop + response = await hook(response, async (updatedOptions) => { + const typedOptions = core_1.default.normalizeArguments(undefined, { + ...updatedOptions, + retry: { + calculateDelay: () => 0 + }, + throwHttpErrors: false, + resolveBodyOnly: false + }, options); + // Remove any further hooks for that request, because we'll call them anyway. + // The loop continues. We don't want duplicates (asPromise recursion). + typedOptions.hooks.afterResponse = typedOptions.hooks.afterResponse.slice(0, index); + for (const hook of typedOptions.hooks.beforeRetry) { + // eslint-disable-next-line no-await-in-loop + await hook(typedOptions); + } + const promise = asPromise(typedOptions); + onCancel(() => { + promise.catch(() => { }); + promise.cancel(); + }); + return promise; + }); + } + } + catch (error) { + request._beforeError(new types_1.RequestError(error.message, error, request)); + return; + } + globalResponse = response; + if (!is_response_ok_1.isResponseOk(response)) { + request._beforeError(new types_1.HTTPError(response)); + return; + } + request.destroy(); + resolve(request.options.resolveBodyOnly ? response.body : response); + }); + const onError = (error) => { + if (promise.isCanceled) { + return; + } + const { options } = request; + if (error instanceof types_1.HTTPError && !options.throwHttpErrors) { + const { response } = error; + resolve(request.options.resolveBodyOnly ? response.body : response); + return; + } + reject(error); + }; + request.once('error', onError); + const previousBody = request.options.body; + request.once('retry', (newRetryCount, error) => { + var _a, _b; + if (previousBody === ((_a = error.request) === null || _a === void 0 ? void 0 : _a.options.body) && is_1.default.nodeStream((_b = error.request) === null || _b === void 0 ? void 0 : _b.options.body)) { + onError(error); + return; + } + makeRequest(newRetryCount); + }); + proxy_events_1.default(request, emitter, proxiedRequestEvents); + }; + makeRequest(0); + }); + promise.on = (event, fn) => { + emitter.on(event, fn); + return promise; + }; + const shortcut = (responseType) => { + const newPromise = (async () => { + // Wait until downloading has ended + await promise; + const { options } = globalResponse.request; + return parse_body_1.default(globalResponse, responseType, options.parseJson, options.encoding); + })(); + Object.defineProperties(newPromise, Object.getOwnPropertyDescriptors(promise)); + return newPromise; + }; + promise.json = () => { + const { headers } = globalRequest.options; + if (!globalRequest.writableFinished && headers.accept === undefined) { + headers.accept = 'application/json'; + } + return shortcut('json'); + }; + promise.buffer = () => shortcut('buffer'); + promise.text = () => shortcut('text'); + return promise; } +exports["default"] = asPromise; +__exportStar(__nccwpck_require__(64597), exports); -/** - * Select all the attributes whether valid or invalid. - */ -const validAttrStrRegxp = new RegExp('(\\s*)([^\\s=]+)(\\s*=)?(\\s*([\'"])(([\\s\\S])*?)\\5)?', 'g'); - -//attr, ="sd", a="amit's", a="sd"b="saf", ab cd="" -function validateAttributeString(attrStr, options) { - //console.log("start:"+attrStr+":end"); +/***/ }), - //if(attrStr.trim().length === 0) return true; //empty string +/***/ 41048: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const matches = util.getAllMatches(attrStr, validAttrStrRegxp); - const attrNames = {}; +"use strict"; - for (let i = 0; i < matches.length; i++) { - if (matches[i][1].length === 0) { - //nospace before attribute name: a="sd"b="saf" - return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' has no space in starting.", getPositionFromMatch(matches[i])) - } else if (matches[i][3] !== undefined && matches[i][4] === undefined) { - return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' is without value.", getPositionFromMatch(matches[i])); - } else if (matches[i][3] === undefined && !options.allowBooleanAttributes) { - //independent attribute: ab - return getErrorObject('InvalidAttr', "boolean attribute '"+matches[i][2]+"' is not allowed.", getPositionFromMatch(matches[i])); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const is_1 = __nccwpck_require__(7678); +const normalizeArguments = (options, defaults) => { + if (is_1.default.null_(options.encoding)) { + throw new TypeError('To get a Buffer, set `options.responseType` to `buffer` instead'); } - /* else if(matches[i][6] === undefined){//attribute without value: ab= - return { err: { code:"InvalidAttr",msg:"attribute " + matches[i][2] + " has no value assigned."}}; - } */ - const attrName = matches[i][2]; - if (!validateAttrName(attrName)) { - return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is an invalid name.", getPositionFromMatch(matches[i])); + is_1.assert.any([is_1.default.string, is_1.default.undefined], options.encoding); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.resolveBodyOnly); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.methodRewriting); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.isStream); + is_1.assert.any([is_1.default.string, is_1.default.undefined], options.responseType); + // `options.responseType` + if (options.responseType === undefined) { + options.responseType = 'text'; } - if (!attrNames.hasOwnProperty(attrName)) { - //check for duplicate attribute. - attrNames[attrName] = 1; - } else { - return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is repeated.", getPositionFromMatch(matches[i])); + // `options.retry` + const { retry } = options; + if (defaults) { + options.retry = { ...defaults.retry }; } - } + else { + options.retry = { + calculateDelay: retryObject => retryObject.computedValue, + limit: 0, + methods: [], + statusCodes: [], + errorCodes: [], + maxRetryAfter: undefined + }; + } + if (is_1.default.object(retry)) { + options.retry = { + ...options.retry, + ...retry + }; + options.retry.methods = [...new Set(options.retry.methods.map(method => method.toUpperCase()))]; + options.retry.statusCodes = [...new Set(options.retry.statusCodes)]; + options.retry.errorCodes = [...new Set(options.retry.errorCodes)]; + } + else if (is_1.default.number(retry)) { + options.retry.limit = retry; + } + if (is_1.default.undefined(options.retry.maxRetryAfter)) { + options.retry.maxRetryAfter = Math.min( + // TypeScript is not smart enough to handle `.filter(x => is.number(x))`. + // eslint-disable-next-line unicorn/no-fn-reference-in-iterator + ...[options.timeout.request, options.timeout.connect].filter(is_1.default.number)); + } + // `options.pagination` + if (is_1.default.object(options.pagination)) { + if (defaults) { + options.pagination = { + ...defaults.pagination, + ...options.pagination + }; + } + const { pagination } = options; + if (!is_1.default.function_(pagination.transform)) { + throw new Error('`options.pagination.transform` must be implemented'); + } + if (!is_1.default.function_(pagination.shouldContinue)) { + throw new Error('`options.pagination.shouldContinue` must be implemented'); + } + if (!is_1.default.function_(pagination.filter)) { + throw new TypeError('`options.pagination.filter` must be implemented'); + } + if (!is_1.default.function_(pagination.paginate)) { + throw new Error('`options.pagination.paginate` must be implemented'); + } + } + // JSON mode + if (options.responseType === 'json' && options.headers.accept === undefined) { + options.headers.accept = 'application/json'; + } + return options; +}; +exports["default"] = normalizeArguments; - return true; -} -function validateNumberAmpersand(xmlData, i) { - let re = /\d/; - if (xmlData[i] === 'x') { - i++; - re = /[\da-fA-F]/; - } - for (; i < xmlData.length; i++) { - if (xmlData[i] === ';') - return i; - if (!xmlData[i].match(re)) - break; - } - return -1; -} +/***/ }), -function validateAmpersand(xmlData, i) { - // https://www.w3.org/TR/xml/#dt-charref - i++; - if (xmlData[i] === ';') - return -1; - if (xmlData[i] === '#') { - i++; - return validateNumberAmpersand(xmlData, i); - } - let count = 0; - for (; i < xmlData.length; i++, count++) { - if (xmlData[i].match(/\w/) && count < 20) - continue; - if (xmlData[i] === ';') - break; - return -1; - } - return i; -} +/***/ 88220: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function getErrorObject(code, message, lineNumber) { - return { - err: { - code: code, - msg: message, - line: lineNumber.line || lineNumber, - col: lineNumber.col, - }, - }; -} +"use strict"; -function validateAttrName(attrName) { - return util.isName(attrName); -} +Object.defineProperty(exports, "__esModule", ({ value: true })); +const types_1 = __nccwpck_require__(64597); +const parseBody = (response, responseType, parseJson, encoding) => { + const { rawBody } = response; + try { + if (responseType === 'text') { + return rawBody.toString(encoding); + } + if (responseType === 'json') { + return rawBody.length === 0 ? '' : parseJson(rawBody.toString()); + } + if (responseType === 'buffer') { + return rawBody; + } + throw new types_1.ParseError({ + message: `Unknown body type '${responseType}'`, + name: 'Error' + }, response); + } + catch (error) { + throw new types_1.ParseError(error, response); + } +}; +exports["default"] = parseBody; -// const startsWithXML = /^xml/i; -function validateTagName(tagname) { - return util.isName(tagname) /* && !tagname.match(startsWithXML) */; -} +/***/ }), + +/***/ 64597: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -//this function returns the line number for the character at the given index -function getLineNumberForPosition(xmlData, index) { - const lines = xmlData.substring(0, index).split(/\r?\n/); - return { - line: lines.length, +"use strict"; - // column number is last line's length + 1, because column numbering starts at 1: - col: lines[lines.length - 1].length + 1 - }; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (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 })); +exports.CancelError = exports.ParseError = void 0; +const core_1 = __nccwpck_require__(60094); +/** +An error to be thrown when server response code is 2xx, and parsing body fails. +Includes a `response` property. +*/ +class ParseError extends core_1.RequestError { + constructor(error, response) { + const { options } = response.request; + super(`${error.message} in "${options.url.toString()}"`, error, response.request); + this.name = 'ParseError'; + this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_BODY_PARSE_FAILURE' : this.code; + } } - -//this function returns the position of the first character of match within attrStr -function getPositionFromMatch(match) { - return match.startIndex + match[1].length; +exports.ParseError = ParseError; +/** +An error to be thrown when the request is aborted with `.cancel()`. +*/ +class CancelError extends core_1.RequestError { + constructor(request) { + super('Promise was canceled', {}, request); + this.name = 'CancelError'; + this.code = 'ERR_CANCELED'; + } + get isCanceled() { + return true; + } } +exports.CancelError = CancelError; +__exportStar(__nccwpck_require__(60094), exports); /***/ }), -/***/ 80660: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 93462: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -//parse Empty Node as self closing node -const buildFromOrderedJs = __nccwpck_require__(72462); - -const defaultOptions = { - attributeNamePrefix: '@_', - attributesGroupName: false, - textNodeName: '#text', - ignoreAttributes: true, - cdataPropName: false, - format: false, - indentBy: ' ', - suppressEmptyNode: false, - suppressUnpairedNode: true, - suppressBooleanAttributes: true, - tagValueProcessor: function(key, a) { - return a; - }, - attributeValueProcessor: function(attrName, a) { - return a; - }, - preserveOrder: false, - commentPropName: false, - unpairedTags: [], - entities: [ - { regex: new RegExp("&", "g"), val: "&" },//it must be on top - { regex: new RegExp(">", "g"), val: ">" }, - { regex: new RegExp("<", "g"), val: "<" }, - { regex: new RegExp("\'", "g"), val: "'" }, - { regex: new RegExp("\"", "g"), val: """ } - ], - processEntities: true, - stopNodes: [], - // transformTagName: false, - // transformAttributeName: false, - oneListGroup: false +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.retryAfterStatusCodes = void 0; +exports.retryAfterStatusCodes = new Set([413, 429, 503]); +const calculateRetryDelay = ({ attemptCount, retryOptions, error, retryAfter }) => { + if (attemptCount > retryOptions.limit) { + return 0; + } + const hasMethod = retryOptions.methods.includes(error.options.method); + const hasErrorCode = retryOptions.errorCodes.includes(error.code); + const hasStatusCode = error.response && retryOptions.statusCodes.includes(error.response.statusCode); + if (!hasMethod || (!hasErrorCode && !hasStatusCode)) { + return 0; + } + if (error.response) { + if (retryAfter) { + if (retryOptions.maxRetryAfter === undefined || retryAfter > retryOptions.maxRetryAfter) { + return 0; + } + return retryAfter; + } + if (error.response.statusCode === 413) { + return 0; + } + } + const noise = Math.random() * 100; + return ((2 ** (attemptCount - 1)) * 1000) + noise; }; +exports["default"] = calculateRetryDelay; -function Builder(options) { - this.options = Object.assign({}, defaultOptions, options); - if (this.options.ignoreAttributes || this.options.attributesGroupName) { - this.isAttribute = function(/*a*/) { - return false; - }; - } else { - this.attrPrefixLen = this.options.attributeNamePrefix.length; - this.isAttribute = isAttribute; - } - this.processTextOrObjNode = processTextOrObjNode +/***/ }), - if (this.options.format) { - this.indentate = indentate; - this.tagEndChar = '>\n'; - this.newLine = '\n'; - } else { - this.indentate = function() { - return ''; - }; - this.tagEndChar = '>'; - this.newLine = ''; - } -} +/***/ 60094: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -Builder.prototype.build = function(jObj) { - if(this.options.preserveOrder){ - return buildFromOrderedJs(jObj, this.options); - }else { - if(Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1){ - jObj = { - [this.options.arrayNodeName] : jObj - } - } - return this.j2x(jObj, 0).val; - } -}; +"use strict"; -Builder.prototype.j2x = function(jObj, level) { - let attrStr = ''; - let val = ''; - for (let key in jObj) { - if(!Object.prototype.hasOwnProperty.call(jObj, key)) continue; - if (typeof jObj[key] === 'undefined') { - // supress undefined node only if it is not an attribute - if (this.isAttribute(key)) { - val += ''; - } - } else if (jObj[key] === null) { - // null attribute should be ignored by the attribute list, but should not cause the tag closing - if (this.isAttribute(key)) { - val += ''; - } else if (key[0] === '?') { - val += this.indentate(level) + '<' + key + '?' + this.tagEndChar; - } else { - val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; - } - // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; - } else if (jObj[key] instanceof Date) { - val += this.buildTextValNode(jObj[key], key, '', level); - } else if (typeof jObj[key] !== 'object') { - //premitive type - const attr = this.isAttribute(key); - if (attr) { - attrStr += this.buildAttrPairStr(attr, '' + jObj[key]); - }else { - //tag value - if (key === this.options.textNodeName) { - let newval = this.options.tagValueProcessor(key, '' + jObj[key]); - val += this.replaceEntitiesValue(newval); - } else { - val += this.buildTextValNode(jObj[key], key, '', level); - } - } - } else if (Array.isArray(jObj[key])) { - //repeated nodes - const arrLen = jObj[key].length; - let listTagVal = ""; - let listTagAttr = ""; - for (let j = 0; j < arrLen; j++) { - const item = jObj[key][j]; - if (typeof item === 'undefined') { - // supress undefined node - } else if (item === null) { - if(key[0] === "?") val += this.indentate(level) + '<' + key + '?' + this.tagEndChar; - else val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; - // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; - } else if (typeof item === 'object') { - if(this.options.oneListGroup){ - const result = this.j2x(item, level + 1); - listTagVal += result.val; - if (this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName)) { - listTagAttr += result.attrStr - } - }else{ - listTagVal += this.processTextOrObjNode(item, key, level) - } - } else { - if (this.options.oneListGroup) { - let textValue = this.options.tagValueProcessor(key, item); - textValue = this.replaceEntitiesValue(textValue); - listTagVal += textValue; - } else { - listTagVal += this.buildTextValNode(item, key, '', level); - } - } - } - if(this.options.oneListGroup){ - listTagVal = this.buildObjectNode(listTagVal, key, listTagAttr, level); - } - val += listTagVal; - } else { - //nested node - if (this.options.attributesGroupName && key === this.options.attributesGroupName) { - const Ks = Object.keys(jObj[key]); - const L = Ks.length; - for (let j = 0; j < L; j++) { - attrStr += this.buildAttrPairStr(Ks[j], '' + jObj[key][Ks[j]]); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.UnsupportedProtocolError = exports.ReadError = exports.TimeoutError = exports.UploadError = exports.CacheError = exports.HTTPError = exports.MaxRedirectsError = exports.RequestError = exports.setNonEnumerableProperties = exports.knownHookEvents = exports.withoutBody = exports.kIsNormalizedAlready = void 0; +const util_1 = __nccwpck_require__(73837); +const stream_1 = __nccwpck_require__(12781); +const fs_1 = __nccwpck_require__(57147); +const url_1 = __nccwpck_require__(57310); +const http = __nccwpck_require__(13685); +const http_1 = __nccwpck_require__(13685); +const https = __nccwpck_require__(95687); +const http_timer_1 = __nccwpck_require__(48097); +const cacheable_lookup_1 = __nccwpck_require__(2286); +const CacheableRequest = __nccwpck_require__(78116); +const decompressResponse = __nccwpck_require__(82391); +// @ts-expect-error Missing types +const http2wrapper = __nccwpck_require__(54645); +const lowercaseKeys = __nccwpck_require__(9662); +const is_1 = __nccwpck_require__(7678); +const get_body_size_1 = __nccwpck_require__(94564); +const is_form_data_1 = __nccwpck_require__(90040); +const proxy_events_1 = __nccwpck_require__(53021); +const timed_out_1 = __nccwpck_require__(52454); +const url_to_options_1 = __nccwpck_require__(8026); +const options_to_url_1 = __nccwpck_require__(9219); +const weakable_map_1 = __nccwpck_require__(7288); +const get_buffer_1 = __nccwpck_require__(34500); +const dns_ip_version_1 = __nccwpck_require__(94993); +const is_response_ok_1 = __nccwpck_require__(49298); +const deprecation_warning_1 = __nccwpck_require__(397); +const normalize_arguments_1 = __nccwpck_require__(41048); +const calculate_retry_delay_1 = __nccwpck_require__(93462); +let globalDnsCache; +const kRequest = Symbol('request'); +const kResponse = Symbol('response'); +const kResponseSize = Symbol('responseSize'); +const kDownloadedSize = Symbol('downloadedSize'); +const kBodySize = Symbol('bodySize'); +const kUploadedSize = Symbol('uploadedSize'); +const kServerResponsesPiped = Symbol('serverResponsesPiped'); +const kUnproxyEvents = Symbol('unproxyEvents'); +const kIsFromCache = Symbol('isFromCache'); +const kCancelTimeouts = Symbol('cancelTimeouts'); +const kStartedReading = Symbol('startedReading'); +const kStopReading = Symbol('stopReading'); +const kTriggerRead = Symbol('triggerRead'); +const kBody = Symbol('body'); +const kJobs = Symbol('jobs'); +const kOriginalResponse = Symbol('originalResponse'); +const kRetryTimeout = Symbol('retryTimeout'); +exports.kIsNormalizedAlready = Symbol('isNormalizedAlready'); +const supportsBrotli = is_1.default.string(process.versions.brotli); +exports.withoutBody = new Set(['GET', 'HEAD']); +exports.knownHookEvents = [ + 'init', + 'beforeRequest', + 'beforeRedirect', + 'beforeError', + 'beforeRetry', + // Promise-Only + 'afterResponse' +]; +function validateSearchParameters(searchParameters) { + // eslint-disable-next-line guard-for-in + for (const key in searchParameters) { + const value = searchParameters[key]; + if (!is_1.default.string(value) && !is_1.default.number(value) && !is_1.default.boolean(value) && !is_1.default.null_(value) && !is_1.default.undefined(value)) { + throw new TypeError(`The \`searchParams\` value '${String(value)}' must be a string, number, boolean or null`); } - } else { - val += this.processTextOrObjNode(jObj[key], key, level) - } } - } - return {attrStr: attrStr, val: val}; -}; - -Builder.prototype.buildAttrPairStr = function(attrName, val){ - val = this.options.attributeValueProcessor(attrName, '' + val); - val = this.replaceEntitiesValue(val); - if (this.options.suppressBooleanAttributes && val === "true") { - return ' ' + attrName; - } else return ' ' + attrName + '="' + val + '"'; } - -function processTextOrObjNode (object, key, level) { - const result = this.j2x(object, level + 1); - if (object[this.options.textNodeName] !== undefined && Object.keys(object).length === 1) { - return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level); - } else { - return this.buildObjectNode(result.val, key, result.attrStr, level); - } +function isClientRequest(clientRequest) { + return is_1.default.object(clientRequest) && !('statusCode' in clientRequest); } - -Builder.prototype.buildObjectNode = function(val, key, attrStr, level) { - if(val === ""){ - if(key[0] === "?") return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar; - else { - return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar; +const cacheableStore = new weakable_map_1.default(); +const waitForOpenFile = async (file) => new Promise((resolve, reject) => { + const onError = (error) => { + reject(error); + }; + // Node.js 12 has incomplete types + if (!file.pending) { + resolve(); } - }else{ - - let tagEndExp = ' { + file.off('error', onError); + resolve(); + }); +}); +const redirectCodes = new Set([300, 301, 302, 303, 304, 307, 308]); +const nonEnumerableProperties = [ + 'context', + 'body', + 'json', + 'form' +]; +exports.setNonEnumerableProperties = (sources, to) => { + // Non enumerable properties shall not be merged + const properties = {}; + for (const source of sources) { + if (!source) { + continue; + } + for (const name of nonEnumerableProperties) { + if (!(name in source)) { + continue; + } + properties[name] = { + writable: true, + configurable: true, + enumerable: false, + // @ts-expect-error TS doesn't see the check above + value: source[name] + }; + } } - - // attrStr is an empty string in case the attribute came as undefined or null - if ((attrStr || attrStr === '') && val.indexOf('<') === -1) { - return ( this.indentate(level) + '<' + key + attrStr + piClosingChar + '>' + val + tagEndExp ); - } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) { - return this.indentate(level) + `` + this.newLine; - }else { - return ( - this.indentate(level) + '<' + key + attrStr + piClosingChar + this.tagEndChar + - val + - this.indentate(level) + tagEndExp ); + Object.defineProperties(to, properties); +}; +/** +An error to be thrown when a request fails. +Contains a `code` property with error class code, like `ECONNREFUSED`. +*/ +class RequestError extends Error { + constructor(message, error, self) { + var _a, _b; + super(message); + Error.captureStackTrace(this, this.constructor); + this.name = 'RequestError'; + this.code = (_a = error.code) !== null && _a !== void 0 ? _a : 'ERR_GOT_REQUEST_ERROR'; + if (self instanceof Request) { + Object.defineProperty(this, 'request', { + enumerable: false, + value: self + }); + Object.defineProperty(this, 'response', { + enumerable: false, + value: self[kResponse] + }); + Object.defineProperty(this, 'options', { + // This fails because of TS 3.7.2 useDefineForClassFields + // Ref: https://github.com/microsoft/TypeScript/issues/34972 + enumerable: false, + value: self.options + }); + } + else { + Object.defineProperty(this, 'options', { + // This fails because of TS 3.7.2 useDefineForClassFields + // Ref: https://github.com/microsoft/TypeScript/issues/34972 + enumerable: false, + value: self + }); + } + this.timings = (_b = this.request) === null || _b === void 0 ? void 0 : _b.timings; + // Recover the original stacktrace + if (is_1.default.string(error.stack) && is_1.default.string(this.stack)) { + const indexOfMessage = this.stack.indexOf(this.message) + this.message.length; + const thisStackTrace = this.stack.slice(indexOfMessage).split('\n').reverse(); + const errorStackTrace = error.stack.slice(error.stack.indexOf(error.message) + error.message.length).split('\n').reverse(); + // Remove duplicated traces + while (errorStackTrace.length !== 0 && errorStackTrace[0] === thisStackTrace[0]) { + thisStackTrace.shift(); + } + this.stack = `${this.stack.slice(0, indexOfMessage)}${thisStackTrace.reverse().join('\n')}${errorStackTrace.reverse().join('\n')}`; + } } - } } - -Builder.prototype.closeTag = function(key){ - let closeTag = ""; - if(this.options.unpairedTags.indexOf(key) !== -1){ //unpaired - if(!this.options.suppressUnpairedNode) closeTag = "/" - }else if(this.options.suppressEmptyNode){ //empty - closeTag = "/"; - }else{ - closeTag = `>` + this.newLine; - }else if (this.options.commentPropName !== false && key === this.options.commentPropName) { - return this.indentate(level) + `` + this.newLine; - }else if(key[0] === "?") {//PI tag - return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar; - }else{ - let textValue = this.options.tagValueProcessor(key, val); - textValue = this.replaceEntitiesValue(textValue); - - if( textValue === ''){ - return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar; - }else{ - return this.indentate(level) + '<' + key + attrStr + '>' + - textValue + - ' 0 && this.options.processEntities){ - for (let i=0; i { - -const EOL = "\n"; - +exports.ReadError = ReadError; /** - * - * @param {array} jArray - * @param {any} options - * @returns - */ -function toXml(jArray, options) { - let indentation = ""; - if (options.format && options.indentBy.length > 0) { - indentation = EOL; +An error to be thrown when given an unsupported protocol. +*/ +class UnsupportedProtocolError extends RequestError { + constructor(options) { + super(`Unsupported protocol "${options.url.protocol}"`, {}, options); + this.name = 'UnsupportedProtocolError'; + this.code = 'ERR_UNSUPPORTED_PROTOCOL'; } - return arrToStr(jArray, options, "", indentation); } - -function arrToStr(arr, options, jPath, indentation) { - let xmlStr = ""; - let isPreviousElementTag = false; - - for (let i = 0; i < arr.length; i++) { - const tagObj = arr[i]; - const tagName = propName(tagObj); - if(tagName === undefined) continue; - - let newJPath = ""; - if (jPath.length === 0) newJPath = tagName - else newJPath = `${jPath}.${tagName}`; - - if (tagName === options.textNodeName) { - let tagText = tagObj[tagName]; - if (!isStopNode(newJPath, options)) { - tagText = options.tagValueProcessor(tagName, tagText); - tagText = replaceEntitiesValue(tagText, options); +exports.UnsupportedProtocolError = UnsupportedProtocolError; +const proxiedRequestEvents = [ + 'socket', + 'connect', + 'continue', + 'information', + 'upgrade', + 'timeout' +]; +class Request extends stream_1.Duplex { + constructor(url, options = {}, defaults) { + super({ + // This must be false, to enable throwing after destroy + // It is used for retry logic in Promise API + autoDestroy: false, + // It needs to be zero because we're just proxying the data to another stream + highWaterMark: 0 + }); + this[kDownloadedSize] = 0; + this[kUploadedSize] = 0; + this.requestInitialized = false; + this[kServerResponsesPiped] = new Set(); + this.redirects = []; + this[kStopReading] = false; + this[kTriggerRead] = false; + this[kJobs] = []; + this.retryCount = 0; + // TODO: Remove this when targeting Node.js >= 12 + this._progressCallbacks = []; + const unlockWrite = () => this._unlockWrite(); + const lockWrite = () => this._lockWrite(); + this.on('pipe', (source) => { + source.prependListener('data', unlockWrite); + source.on('data', lockWrite); + source.prependListener('end', unlockWrite); + source.on('end', lockWrite); + }); + this.on('unpipe', (source) => { + source.off('data', unlockWrite); + source.off('data', lockWrite); + source.off('end', unlockWrite); + source.off('end', lockWrite); + }); + this.on('pipe', source => { + if (source instanceof http_1.IncomingMessage) { + this.options.headers = { + ...source.headers, + ...this.options.headers + }; } - if (isPreviousElementTag) { - xmlStr += indentation; + }); + const { json, body, form } = options; + if (json || body || form) { + this._lockWrite(); + } + if (exports.kIsNormalizedAlready in options) { + this.options = options; + } + else { + try { + // @ts-expect-error Common TypeScript bug saying that `this.constructor` is not accessible + this.options = this.constructor.normalizeArguments(url, options, defaults); } - xmlStr += tagText; - isPreviousElementTag = false; - continue; - } else if (tagName === options.cdataPropName) { - if (isPreviousElementTag) { - xmlStr += indentation; + catch (error) { + // TODO: Move this to `_destroy()` + if (is_1.default.nodeStream(options.body)) { + options.body.destroy(); + } + this.destroy(error); + return; + } + } + (async () => { + var _a; + try { + if (this.options.body instanceof fs_1.ReadStream) { + await waitForOpenFile(this.options.body); + } + const { url: normalizedURL } = this.options; + if (!normalizedURL) { + throw new TypeError('Missing `url` property'); + } + this.requestUrl = normalizedURL.toString(); + decodeURI(this.requestUrl); + await this._finalizeBody(); + await this._makeRequest(); + if (this.destroyed) { + (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.destroy(); + return; + } + // Queued writes etc. + for (const job of this[kJobs]) { + job(); + } + // Prevent memory leak + this[kJobs].length = 0; + this.requestInitialized = true; + } + catch (error) { + if (error instanceof RequestError) { + this._beforeError(error); + return; + } + // This is a workaround for https://github.com/nodejs/node/issues/33335 + if (!this.destroyed) { + this.destroy(error); + } + } + })(); + } + static normalizeArguments(url, options, defaults) { + var _a, _b, _c, _d, _e; + const rawOptions = options; + if (is_1.default.object(url) && !is_1.default.urlInstance(url)) { + options = { ...defaults, ...url, ...options }; + } + else { + if (url && options && options.url !== undefined) { + throw new TypeError('The `url` option is mutually exclusive with the `input` argument'); + } + options = { ...defaults, ...options }; + if (url !== undefined) { + options.url = url; + } + if (is_1.default.urlInstance(options.url)) { + options.url = new url_1.URL(options.url.toString()); + } + } + // TODO: Deprecate URL options in Got 12. + // Support extend-specific options + if (options.cache === false) { + options.cache = undefined; + } + if (options.dnsCache === false) { + options.dnsCache = undefined; + } + // Nice type assertions + is_1.assert.any([is_1.default.string, is_1.default.undefined], options.method); + is_1.assert.any([is_1.default.object, is_1.default.undefined], options.headers); + is_1.assert.any([is_1.default.string, is_1.default.urlInstance, is_1.default.undefined], options.prefixUrl); + is_1.assert.any([is_1.default.object, is_1.default.undefined], options.cookieJar); + is_1.assert.any([is_1.default.object, is_1.default.string, is_1.default.undefined], options.searchParams); + is_1.assert.any([is_1.default.object, is_1.default.string, is_1.default.undefined], options.cache); + is_1.assert.any([is_1.default.object, is_1.default.number, is_1.default.undefined], options.timeout); + is_1.assert.any([is_1.default.object, is_1.default.undefined], options.context); + is_1.assert.any([is_1.default.object, is_1.default.undefined], options.hooks); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.decompress); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.ignoreInvalidCookies); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.followRedirect); + is_1.assert.any([is_1.default.number, is_1.default.undefined], options.maxRedirects); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.throwHttpErrors); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.http2); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.allowGetBody); + is_1.assert.any([is_1.default.string, is_1.default.undefined], options.localAddress); + is_1.assert.any([dns_ip_version_1.isDnsLookupIpVersion, is_1.default.undefined], options.dnsLookupIpVersion); + is_1.assert.any([is_1.default.object, is_1.default.undefined], options.https); + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.rejectUnauthorized); + if (options.https) { + is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.https.rejectUnauthorized); + is_1.assert.any([is_1.default.function_, is_1.default.undefined], options.https.checkServerIdentity); + is_1.assert.any([is_1.default.string, is_1.default.object, is_1.default.array, is_1.default.undefined], options.https.certificateAuthority); + is_1.assert.any([is_1.default.string, is_1.default.object, is_1.default.array, is_1.default.undefined], options.https.key); + is_1.assert.any([is_1.default.string, is_1.default.object, is_1.default.array, is_1.default.undefined], options.https.certificate); + is_1.assert.any([is_1.default.string, is_1.default.undefined], options.https.passphrase); + is_1.assert.any([is_1.default.string, is_1.default.buffer, is_1.default.array, is_1.default.undefined], options.https.pfx); + } + is_1.assert.any([is_1.default.object, is_1.default.undefined], options.cacheOptions); + // `options.method` + if (is_1.default.string(options.method)) { + options.method = options.method.toUpperCase(); + } + else { + options.method = 'GET'; + } + // `options.headers` + if (options.headers === (defaults === null || defaults === void 0 ? void 0 : defaults.headers)) { + options.headers = { ...options.headers }; + } + else { + options.headers = lowercaseKeys({ ...(defaults === null || defaults === void 0 ? void 0 : defaults.headers), ...options.headers }); + } + // Disallow legacy `url.Url` + if ('slashes' in options) { + throw new TypeError('The legacy `url.Url` has been deprecated. Use `URL` instead.'); + } + // `options.auth` + if ('auth' in options) { + throw new TypeError('Parameter `auth` is deprecated. Use `username` / `password` instead.'); + } + // `options.searchParams` + if ('searchParams' in options) { + if (options.searchParams && options.searchParams !== (defaults === null || defaults === void 0 ? void 0 : defaults.searchParams)) { + let searchParameters; + if (is_1.default.string(options.searchParams) || (options.searchParams instanceof url_1.URLSearchParams)) { + searchParameters = new url_1.URLSearchParams(options.searchParams); + } + else { + validateSearchParameters(options.searchParams); + searchParameters = new url_1.URLSearchParams(); + // eslint-disable-next-line guard-for-in + for (const key in options.searchParams) { + const value = options.searchParams[key]; + if (value === null) { + searchParameters.append(key, ''); + } + else if (value !== undefined) { + searchParameters.append(key, value); + } + } + } + // `normalizeArguments()` is also used to merge options + (_a = defaults === null || defaults === void 0 ? void 0 : defaults.searchParams) === null || _a === void 0 ? void 0 : _a.forEach((value, key) => { + // Only use default if one isn't already defined + if (!searchParameters.has(key)) { + searchParameters.append(key, value); + } + }); + options.searchParams = searchParameters; + } + } + // `options.username` & `options.password` + options.username = (_b = options.username) !== null && _b !== void 0 ? _b : ''; + options.password = (_c = options.password) !== null && _c !== void 0 ? _c : ''; + // `options.prefixUrl` & `options.url` + if (is_1.default.undefined(options.prefixUrl)) { + options.prefixUrl = (_d = defaults === null || defaults === void 0 ? void 0 : defaults.prefixUrl) !== null && _d !== void 0 ? _d : ''; + } + else { + options.prefixUrl = options.prefixUrl.toString(); + if (options.prefixUrl !== '' && !options.prefixUrl.endsWith('/')) { + options.prefixUrl += '/'; + } + } + if (is_1.default.string(options.url)) { + if (options.url.startsWith('/')) { + throw new Error('`input` must not start with a slash when using `prefixUrl`'); + } + options.url = options_to_url_1.default(options.prefixUrl + options.url, options); + } + else if ((is_1.default.undefined(options.url) && options.prefixUrl !== '') || options.protocol) { + options.url = options_to_url_1.default(options.prefixUrl, options); + } + if (options.url) { + if ('port' in options) { + delete options.port; + } + // Make it possible to change `options.prefixUrl` + let { prefixUrl } = options; + Object.defineProperty(options, 'prefixUrl', { + set: (value) => { + const url = options.url; + if (!url.href.startsWith(value)) { + throw new Error(`Cannot change \`prefixUrl\` from ${prefixUrl} to ${value}: ${url.href}`); + } + options.url = new url_1.URL(value + url.href.slice(prefixUrl.length)); + prefixUrl = value; + }, + get: () => prefixUrl + }); + // Support UNIX sockets + let { protocol } = options.url; + if (protocol === 'unix:') { + protocol = 'http:'; + options.url = new url_1.URL(`http://unix${options.url.pathname}${options.url.search}`); + } + // Set search params + if (options.searchParams) { + // eslint-disable-next-line @typescript-eslint/no-base-to-string + options.url.search = options.searchParams.toString(); + } + // Protocol check + if (protocol !== 'http:' && protocol !== 'https:') { + throw new UnsupportedProtocolError(options); + } + // Update `username` + if (options.username === '') { + options.username = options.url.username; + } + else { + options.url.username = options.username; + } + // Update `password` + if (options.password === '') { + options.password = options.url.password; + } + else { + options.url.password = options.password; + } + } + // `options.cookieJar` + const { cookieJar } = options; + if (cookieJar) { + let { setCookie, getCookieString } = cookieJar; + is_1.assert.function_(setCookie); + is_1.assert.function_(getCookieString); + /* istanbul ignore next: Horrible `tough-cookie` v3 check */ + if (setCookie.length === 4 && getCookieString.length === 0) { + setCookie = util_1.promisify(setCookie.bind(options.cookieJar)); + getCookieString = util_1.promisify(getCookieString.bind(options.cookieJar)); + options.cookieJar = { + setCookie, + getCookieString: getCookieString + }; + } + } + // `options.cache` + const { cache } = options; + if (cache) { + if (!cacheableStore.has(cache)) { + cacheableStore.set(cache, new CacheableRequest(((requestOptions, handler) => { + const result = requestOptions[kRequest](requestOptions, handler); + // TODO: remove this when `cacheable-request` supports async request functions. + if (is_1.default.promise(result)) { + // @ts-expect-error + // We only need to implement the error handler in order to support HTTP2 caching. + // The result will be a promise anyway. + result.once = (event, handler) => { + if (event === 'error') { + result.catch(handler); + } + else if (event === 'abort') { + // The empty catch is needed here in case when + // it rejects before it's `await`ed in `_makeRequest`. + (async () => { + try { + const request = (await result); + request.once('abort', handler); + } + catch (_a) { } + })(); + } + else { + /* istanbul ignore next: safety check */ + throw new Error(`Unknown HTTP2 promise event: ${event}`); + } + return result; + }; + } + return result; + }), cache)); + } + } + // `options.cacheOptions` + options.cacheOptions = { ...options.cacheOptions }; + // `options.dnsCache` + if (options.dnsCache === true) { + if (!globalDnsCache) { + globalDnsCache = new cacheable_lookup_1.default(); + } + options.dnsCache = globalDnsCache; + } + else if (!is_1.default.undefined(options.dnsCache) && !options.dnsCache.lookup) { + throw new TypeError(`Parameter \`dnsCache\` must be a CacheableLookup instance or a boolean, got ${is_1.default(options.dnsCache)}`); + } + // `options.timeout` + if (is_1.default.number(options.timeout)) { + options.timeout = { request: options.timeout }; + } + else if (defaults && options.timeout !== defaults.timeout) { + options.timeout = { + ...defaults.timeout, + ...options.timeout + }; + } + else { + options.timeout = { ...options.timeout }; + } + // `options.context` + if (!options.context) { + options.context = {}; + } + // `options.hooks` + const areHooksDefault = options.hooks === (defaults === null || defaults === void 0 ? void 0 : defaults.hooks); + options.hooks = { ...options.hooks }; + for (const event of exports.knownHookEvents) { + if (event in options.hooks) { + if (is_1.default.array(options.hooks[event])) { + // See https://github.com/microsoft/TypeScript/issues/31445#issuecomment-576929044 + options.hooks[event] = [...options.hooks[event]]; + } + else { + throw new TypeError(`Parameter \`${event}\` must be an Array, got ${is_1.default(options.hooks[event])}`); + } + } + else { + options.hooks[event] = []; + } + } + if (defaults && !areHooksDefault) { + for (const event of exports.knownHookEvents) { + const defaultHooks = defaults.hooks[event]; + if (defaultHooks.length > 0) { + // See https://github.com/microsoft/TypeScript/issues/31445#issuecomment-576929044 + options.hooks[event] = [ + ...defaults.hooks[event], + ...options.hooks[event] + ]; + } } - xmlStr += ``; - isPreviousElementTag = false; - continue; - } else if (tagName === options.commentPropName) { - xmlStr += indentation + ``; - isPreviousElementTag = true; - continue; - } else if (tagName[0] === "?") { - const attStr = attr_to_str(tagObj[":@"], options); - const tempInd = tagName === "?xml" ? "" : indentation; - let piTextNodeName = tagObj[tagName][0][options.textNodeName]; - piTextNodeName = piTextNodeName.length !== 0 ? " " + piTextNodeName : ""; //remove extra spacing - xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr}?>`; - isPreviousElementTag = true; - continue; } - let newIdentation = indentation; - if (newIdentation !== "") { - newIdentation += options.indentBy; + // DNS options + if ('family' in options) { + deprecation_warning_1.default('"options.family" was never documented, please use "options.dnsLookupIpVersion"'); } - const attStr = attr_to_str(tagObj[":@"], options); - const tagStart = indentation + `<${tagName}${attStr}`; - const tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation); - if (options.unpairedTags.indexOf(tagName) !== -1) { - if (options.suppressUnpairedNode) xmlStr += tagStart + ">"; - else xmlStr += tagStart + "/>"; - } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) { - xmlStr += tagStart + "/>"; - } else if (tagValue && tagValue.endsWith(">")) { - xmlStr += tagStart + `>${tagValue}${indentation}`; - } else { - xmlStr += tagStart + ">"; - if (tagValue && indentation !== "" && (tagValue.includes("/>") || tagValue.includes("`; } - isPreviousElementTag = true; + options.maxRedirects = (_e = options.maxRedirects) !== null && _e !== void 0 ? _e : 0; + // Set non-enumerable properties + exports.setNonEnumerableProperties([defaults, rawOptions], options); + return normalize_arguments_1.default(options, defaults); } - - return xmlStr; -} - -function propName(obj) { - const keys = Object.keys(obj); - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; - if(!obj.hasOwnProperty(key)) continue; - if (key !== ":@") return key; + _lockWrite() { + const onLockedWrite = () => { + throw new TypeError('The payload has been already provided'); + }; + this.write = onLockedWrite; + this.end = onLockedWrite; } -} - -function attr_to_str(attrMap, options) { - let attrStr = ""; - if (attrMap && !options.ignoreAttributes) { - for (let attr in attrMap) { - if(!attrMap.hasOwnProperty(attr)) continue; - let attrVal = options.attributeValueProcessor(attr, attrMap[attr]); - attrVal = replaceEntitiesValue(attrVal, options); - if (attrVal === true && options.suppressBooleanAttributes) { - attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`; - } else { - attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${attrVal}"`; + _unlockWrite() { + this.write = super.write; + this.end = super.end; + } + async _finalizeBody() { + const { options } = this; + const { headers } = options; + const isForm = !is_1.default.undefined(options.form); + const isJSON = !is_1.default.undefined(options.json); + const isBody = !is_1.default.undefined(options.body); + const hasPayload = isForm || isJSON || isBody; + const cannotHaveBody = exports.withoutBody.has(options.method) && !(options.method === 'GET' && options.allowGetBody); + this._cannotHaveBody = cannotHaveBody; + if (hasPayload) { + if (cannotHaveBody) { + throw new TypeError(`The \`${options.method}\` method cannot be used with a body`); + } + if ([isBody, isForm, isJSON].filter(isTrue => isTrue).length > 1) { + throw new TypeError('The `body`, `json` and `form` options are mutually exclusive'); + } + if (isBody && + !(options.body instanceof stream_1.Readable) && + !is_1.default.string(options.body) && + !is_1.default.buffer(options.body) && + !is_form_data_1.default(options.body)) { + throw new TypeError('The `body` option must be a stream.Readable, string or Buffer'); + } + if (isForm && !is_1.default.object(options.form)) { + throw new TypeError('The `form` option must be an Object'); + } + { + // Serialize body + const noContentType = !is_1.default.string(headers['content-type']); + if (isBody) { + // Special case for https://github.com/form-data/form-data + if (is_form_data_1.default(options.body) && noContentType) { + headers['content-type'] = `multipart/form-data; boundary=${options.body.getBoundary()}`; + } + this[kBody] = options.body; + } + else if (isForm) { + if (noContentType) { + headers['content-type'] = 'application/x-www-form-urlencoded'; + } + this[kBody] = (new url_1.URLSearchParams(options.form)).toString(); + } + else { + if (noContentType) { + headers['content-type'] = 'application/json'; + } + this[kBody] = options.stringifyJson(options.json); + } + const uploadBodySize = await get_body_size_1.default(this[kBody], options.headers); + // See https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD send a Content-Length in a request message when + // no Transfer-Encoding is sent and the request method defines a meaning + // for an enclosed payload body. For example, a Content-Length header + // field is normally sent in a POST request even when the value is 0 + // (indicating an empty payload body). A user agent SHOULD NOT send a + // Content-Length header field when the request message does not contain + // a payload body and the method semantics do not anticipate such a + // body. + if (is_1.default.undefined(headers['content-length']) && is_1.default.undefined(headers['transfer-encoding'])) { + if (!cannotHaveBody && !is_1.default.undefined(uploadBodySize)) { + headers['content-length'] = String(uploadBodySize); + } + } } } - } - return attrStr; -} - -function isStopNode(jPath, options) { - jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1); - let tagName = jPath.substr(jPath.lastIndexOf(".") + 1); - for (let index in options.stopNodes) { - if (options.stopNodes[index] === jPath || options.stopNodes[index] === "*." + tagName) return true; - } - return false; -} - -function replaceEntitiesValue(textValue, options) { - if (textValue && textValue.length > 0 && options.processEntities) { - for (let i = 0; i < options.entities.length; i++) { - const entity = options.entities[i]; - textValue = textValue.replace(entity.regex, entity.val); + else if (cannotHaveBody) { + this._lockWrite(); } + else { + this._unlockWrite(); + } + this[kBodySize] = Number(headers['content-length']) || undefined; } - return textValue; -} -module.exports = toXml; - - -/***/ }), - -/***/ 6072: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const util = __nccwpck_require__(38280); - -//TODO: handle comments -function readDocType(xmlData, i){ - - const entities = {}; - if( xmlData[i + 3] === 'O' && - xmlData[i + 4] === 'C' && - xmlData[i + 5] === 'T' && - xmlData[i + 6] === 'Y' && - xmlData[i + 7] === 'P' && - xmlData[i + 8] === 'E') - { - i = i+9; - let angleBracketsCount = 1; - let hasBody = false, comment = false; - let exp = ""; - for(;i { + this[kResponseSize] = this[kDownloadedSize]; + this.emit('downloadProgress', this.downloadProgress); + }); + response.once('error', (error) => { + // Force clean-up, because some packages don't do this. + // TODO: Fix decompress-response + response.destroy(); + this._beforeError(new ReadError(error, this)); + }); + response.once('aborted', () => { + this._beforeError(new ReadError({ + name: 'Error', + message: 'The server aborted pending request', + code: 'ECONNRESET' + }, this)); + }); + this.emit('downloadProgress', this.downloadProgress); + const rawCookies = response.headers['set-cookie']; + if (is_1.default.object(options.cookieJar) && rawCookies) { + let promises = rawCookies.map(async (rawCookie) => options.cookieJar.setCookie(rawCookie, url.toString())); + if (options.ignoreInvalidCookies) { + promises = promises.map(async (p) => p.catch(() => { })); + } + try { + await Promise.all(promises); + } + catch (error) { + this._beforeError(error); + return; + } + } + if (options.followRedirect && response.headers.location && redirectCodes.has(statusCode)) { + // We're being redirected, we don't care about the response. + // It'd be best to abort the request, but we can't because + // we would have to sacrifice the TCP connection. We don't want that. + response.resume(); + if (this[kRequest]) { + this[kCancelTimeouts](); + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete this[kRequest]; + this[kUnproxyEvents](); + } + const shouldBeGet = statusCode === 303 && options.method !== 'GET' && options.method !== 'HEAD'; + if (shouldBeGet || !options.methodRewriting) { + // Server responded with "see other", indicating that the resource exists at another location, + // and the client should request it from that location via GET or HEAD. + options.method = 'GET'; + if ('body' in options) { + delete options.body; } - else if( hasBody && isElement(xmlData, i)) i += 8;//Not supported - else if( hasBody && isAttlist(xmlData, i)) i += 8;//Not supported - else if( hasBody && isNotation(xmlData, i)) i += 9;//Not supported - else if( isComment) comment = true; - else throw new Error("Invalid DOCTYPE"); - - angleBracketsCount++; - exp = ""; - } else if (xmlData[i] === '>') { //Read tag content - if(comment){ - if( xmlData[i - 1] === "-" && xmlData[i - 2] === "-"){ - comment = false; - angleBracketsCount--; + if ('json' in options) { + delete options.json; + } + if ('form' in options) { + delete options.form; + } + this[kBody] = undefined; + delete options.headers['content-length']; + } + if (this.redirects.length >= options.maxRedirects) { + this._beforeError(new MaxRedirectsError(this)); + return; + } + try { + // Do not remove. See https://github.com/sindresorhus/got/pull/214 + const redirectBuffer = Buffer.from(response.headers.location, 'binary').toString(); + // Handles invalid URLs. See https://github.com/sindresorhus/got/issues/604 + const redirectUrl = new url_1.URL(redirectBuffer, url); + const redirectString = redirectUrl.toString(); + decodeURI(redirectString); + // eslint-disable-next-line no-inner-declarations + function isUnixSocketURL(url) { + return url.protocol === 'unix:' || url.hostname === 'unix'; + } + if (!isUnixSocketURL(url) && isUnixSocketURL(redirectUrl)) { + this._beforeError(new RequestError('Cannot redirect to UNIX socket', {}, this)); + return; + } + // Redirecting to a different site, clear sensitive data. + if (redirectUrl.hostname !== url.hostname || redirectUrl.port !== url.port) { + if ('host' in options.headers) { + delete options.headers.host; + } + if ('cookie' in options.headers) { + delete options.headers.cookie; + } + if ('authorization' in options.headers) { + delete options.headers.authorization; + } + if (options.username || options.password) { + options.username = ''; + options.password = ''; } - }else{ - angleBracketsCount--; } - if (angleBracketsCount === 0) { - break; + else { + redirectUrl.username = options.username; + redirectUrl.password = options.password; } - }else if( xmlData[i] === '['){ - hasBody = true; - }else{ - exp += xmlData[i]; + this.redirects.push(redirectString); + options.url = redirectUrl; + for (const hook of options.hooks.beforeRedirect) { + // eslint-disable-next-line no-await-in-loop + await hook(options, typedResponse); + } + this.emit('redirect', typedResponse, options); + await this._makeRequest(); + } + catch (error) { + this._beforeError(error); + return; } + return; } - if(angleBracketsCount !== 0){ - throw new Error(`Unclosed DOCTYPE`); + if (options.isStream && options.throwHttpErrors && !is_response_ok_1.isResponseOk(typedResponse)) { + this._beforeError(new HTTPError(typedResponse)); + return; } - }else{ - throw new Error(`Invalid Tag instead of DOCTYPE`); - } - return {entities, i}; -} - -function readEntityExp(xmlData,i){ - //External entities are not supported - // - - //Parameter entities are not supported - // - - //Internal entities are supported - // - - //read EntityName - let entityName = ""; - for (; i < xmlData.length && (xmlData[i] !== "'" && xmlData[i] !== '"' ); i++) { - // if(xmlData[i] === " ") continue; - // else - entityName += xmlData[i]; - } - entityName = entityName.trim(); - if(entityName.indexOf(" ") !== -1) throw new Error("External entites are not supported"); - - //read Entity Value - const startChar = xmlData[i++]; - let val = "" - for (; i < xmlData.length && xmlData[i] !== startChar ; i++) { - val += xmlData[i]; - } - return [entityName, val, i]; -} - -function isComment(xmlData, i){ - if(xmlData[i+1] === '!' && - xmlData[i+2] === '-' && - xmlData[i+3] === '-') return true - return false -} -function isEntity(xmlData, i){ - if(xmlData[i+1] === '!' && - xmlData[i+2] === 'E' && - xmlData[i+3] === 'N' && - xmlData[i+4] === 'T' && - xmlData[i+5] === 'I' && - xmlData[i+6] === 'T' && - xmlData[i+7] === 'Y') return true - return false -} -function isElement(xmlData, i){ - if(xmlData[i+1] === '!' && - xmlData[i+2] === 'E' && - xmlData[i+3] === 'L' && - xmlData[i+4] === 'E' && - xmlData[i+5] === 'M' && - xmlData[i+6] === 'E' && - xmlData[i+7] === 'N' && - xmlData[i+8] === 'T') return true - return false -} - -function isAttlist(xmlData, i){ - if(xmlData[i+1] === '!' && - xmlData[i+2] === 'A' && - xmlData[i+3] === 'T' && - xmlData[i+4] === 'T' && - xmlData[i+5] === 'L' && - xmlData[i+6] === 'I' && - xmlData[i+7] === 'S' && - xmlData[i+8] === 'T') return true - return false -} -function isNotation(xmlData, i){ - if(xmlData[i+1] === '!' && - xmlData[i+2] === 'N' && - xmlData[i+3] === 'O' && - xmlData[i+4] === 'T' && - xmlData[i+5] === 'A' && - xmlData[i+6] === 'T' && - xmlData[i+7] === 'I' && - xmlData[i+8] === 'O' && - xmlData[i+9] === 'N') return true - return false -} - -function validateEntityName(name){ - if (util.isName(name)) - return name; - else - throw new Error(`Invalid entity name ${name}`); -} - -module.exports = readDocType; - - -/***/ }), - -/***/ 86993: -/***/ ((__unused_webpack_module, exports) => { - - -const defaultOptions = { - preserveOrder: false, - attributeNamePrefix: '@_', - attributesGroupName: false, - textNodeName: '#text', - ignoreAttributes: true, - removeNSPrefix: false, // remove NS from tag name or attribute name if true - allowBooleanAttributes: false, //a tag can have attributes without any value - //ignoreRootElement : false, - parseTagValue: true, - parseAttributeValue: false, - trimValues: true, //Trim string values of tag and attributes - cdataPropName: false, - numberParseOptions: { - hex: true, - leadingZeros: true, - eNotation: true - }, - tagValueProcessor: function(tagName, val) { - return val; - }, - attributeValueProcessor: function(attrName, val) { - return val; - }, - stopNodes: [], //nested tags will not be parsed even for errors - alwaysCreateTextNode: false, - isArray: () => false, - commentPropName: false, - unpairedTags: [], - processEntities: true, - htmlEntities: false, - ignoreDeclaration: false, - ignorePiTags: false, - transformTagName: false, - transformAttributeName: false, - updateTag: function(tagName, jPath, attrs){ - return tagName - }, - // skipEmptyListItem: false -}; - -const buildOptions = function(options) { - return Object.assign({}, defaultOptions, options); -}; - -exports.buildOptions = buildOptions; -exports.defaultOptions = defaultOptions; - -/***/ }), - -/***/ 25832: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -///@ts-check - -const util = __nccwpck_require__(38280); -const xmlNode = __nccwpck_require__(7462); -const readDocType = __nccwpck_require__(6072); -const toNumber = __nccwpck_require__(14526); - -// const regx = -// '<((!\\[CDATA\\[([\\s\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\/)(NAME)\\s*>))([^<]*)' -// .replace(/NAME/g, util.nameRegexp); - -//const tagsRegx = new RegExp("<(\\/?[\\w:\\-\._]+)([^>]*)>(\\s*"+cdataRegx+")*([^<]+)?","g"); -//const tagsRegx = new RegExp("<(\\/?)((\\w*:)?([\\w:\\-\._]+))([^>]*)>([^<]*)("+cdataRegx+"([^<]*))*([^<]+)?","g"); - -class OrderedObjParser{ - constructor(options){ - this.options = options; - this.currentNode = null; - this.tagsNodeStack = []; - this.docTypeEntities = {}; - this.lastEntities = { - "apos" : { regex: /&(apos|#39|#x27);/g, val : "'"}, - "gt" : { regex: /&(gt|#62|#x3E);/g, val : ">"}, - "lt" : { regex: /&(lt|#60|#x3C);/g, val : "<"}, - "quot" : { regex: /&(quot|#34|#x22);/g, val : "\""}, - }; - this.ampEntity = { regex: /&(amp|#38|#x26);/g, val : "&"}; - this.htmlEntities = { - "space": { regex: /&(nbsp|#160);/g, val: " " }, - // "lt" : { regex: /&(lt|#60);/g, val: "<" }, - // "gt" : { regex: /&(gt|#62);/g, val: ">" }, - // "amp" : { regex: /&(amp|#38);/g, val: "&" }, - // "quot" : { regex: /&(quot|#34);/g, val: "\"" }, - // "apos" : { regex: /&(apos|#39);/g, val: "'" }, - "cent" : { regex: /&(cent|#162);/g, val: "¢" }, - "pound" : { regex: /&(pound|#163);/g, val: "£" }, - "yen" : { regex: /&(yen|#165);/g, val: "¥" }, - "euro" : { regex: /&(euro|#8364);/g, val: "€" }, - "copyright" : { regex: /&(copy|#169);/g, val: "©" }, - "reg" : { regex: /&(reg|#174);/g, val: "®" }, - "inr" : { regex: /&(inr|#8377);/g, val: "₹" }, - "num_dec": { regex: /&#([0-9]{1,7});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 10)) }, - "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 16)) }, - }; - this.addExternalEntities = addExternalEntities; - this.parseXml = parseXml; - this.parseTextData = parseTextData; - this.resolveNameSpace = resolveNameSpace; - this.buildAttributesMap = buildAttributesMap; - this.isItStopNode = isItStopNode; - this.replaceEntitiesValue = replaceEntitiesValue; - this.readStopNodeData = readStopNodeData; - this.saveTextToParentTag = saveTextToParentTag; - this.addChild = addChild; - } - -} - -function addExternalEntities(externalEntities){ - const entKeys = Object.keys(externalEntities); - for (let i = 0; i < entKeys.length; i++) { - const ent = entKeys[i]; - this.lastEntities[ent] = { - regex: new RegExp("&"+ent+";","g"), - val : externalEntities[ent] - } - } -} - -/** - * @param {string} val - * @param {string} tagName - * @param {string} jPath - * @param {boolean} dontTrim - * @param {boolean} hasAttributes - * @param {boolean} isLeafNode - * @param {boolean} escapeEntities - */ -function parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) { - if (val !== undefined) { - if (this.options.trimValues && !dontTrim) { - val = val.trim(); - } - if(val.length > 0){ - if(!escapeEntities) val = this.replaceEntitiesValue(val); - - const newval = this.options.tagValueProcessor(tagName, val, jPath, hasAttributes, isLeafNode); - if(newval === null || newval === undefined){ - //don't parse - return val; - }else if(typeof newval !== typeof val || newval !== val){ - //overwrite - return newval; - }else if(this.options.trimValues){ - return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions); - }else{ - const trimmedVal = val.trim(); - if(trimmedVal === val){ - return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions); - }else{ - return val; + response.on('readable', () => { + if (this[kTriggerRead]) { + this._read(); + } + }); + this.on('resume', () => { + response.resume(); + }); + this.on('pause', () => { + response.pause(); + }); + response.once('end', () => { + this.push(null); + }); + this.emit('response', response); + for (const destination of this[kServerResponsesPiped]) { + if (destination.headersSent) { + continue; + } + // eslint-disable-next-line guard-for-in + for (const key in response.headers) { + const isAllowed = options.decompress ? key !== 'content-encoding' : true; + const value = response.headers[key]; + if (isAllowed) { + destination.setHeader(key, value); + } + } + destination.statusCode = statusCode; } - } - } - } -} - -function resolveNameSpace(tagname) { - if (this.options.removeNSPrefix) { - const tags = tagname.split(':'); - const prefix = tagname.charAt(0) === '/' ? '/' : ''; - if (tags[0] === 'xmlns') { - return ''; - } - if (tags.length === 2) { - tagname = prefix + tags[1]; } - } - return tagname; -} - -//TODO: change regex to capture NS -//const attrsRegx = new RegExp("([\\w\\-\\.\\:]+)\\s*=\\s*(['\"])((.|\n)*?)\\2","gm"); -const attrsRegx = new RegExp('([^\\s=]+)\\s*(=\\s*([\'"])([\\s\\S]*?)\\3)?', 'gm'); - -function buildAttributesMap(attrStr, jPath, tagName) { - if (!this.options.ignoreAttributes && typeof attrStr === 'string') { - // attrStr = attrStr.replace(/\r?\n/g, ' '); - //attrStr = attrStr || attrStr.trim(); - - const matches = util.getAllMatches(attrStr, attrsRegx); - const len = matches.length; //don't make it inline - const attrs = {}; - for (let i = 0; i < len; i++) { - const attrName = this.resolveNameSpace(matches[i][1]); - let oldVal = matches[i][4]; - let aName = this.options.attributeNamePrefix + attrName; - if (attrName.length) { - if (this.options.transformAttributeName) { - aName = this.options.transformAttributeName(aName); + async _onResponse(response) { + try { + await this._onResponseBase(response); } - if(aName === "__proto__") aName = "#__proto__"; - if (oldVal !== undefined) { - if (this.options.trimValues) { - oldVal = oldVal.trim(); - } - oldVal = this.replaceEntitiesValue(oldVal); - const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath); - if(newVal === null || newVal === undefined){ - //don't parse - attrs[aName] = oldVal; - }else if(typeof newVal !== typeof oldVal || newVal !== oldVal){ - //overwrite - attrs[aName] = newVal; - }else{ - //parse - attrs[aName] = parseValue( - oldVal, - this.options.parseAttributeValue, - this.options.numberParseOptions - ); - } - } else if (this.options.allowBooleanAttributes) { - attrs[aName] = true; + catch (error) { + /* istanbul ignore next: better safe than sorry */ + this._beforeError(error); } - } } - if (!Object.keys(attrs).length) { - return; + _onRequest(request) { + const { options } = this; + const { timeout, url } = options; + http_timer_1.default(request); + this[kCancelTimeouts] = timed_out_1.default(request, timeout, url); + const responseEventName = options.cache ? 'cacheableResponse' : 'response'; + request.once(responseEventName, (response) => { + void this._onResponse(response); + }); + request.once('error', (error) => { + var _a; + // Force clean-up, because some packages (e.g. nock) don't do this. + request.destroy(); + // Node.js <= 12.18.2 mistakenly emits the response `end` first. + (_a = request.res) === null || _a === void 0 ? void 0 : _a.removeAllListeners('end'); + error = error instanceof timed_out_1.TimeoutError ? new TimeoutError(error, this.timings, this) : new RequestError(error.message, error, this); + this._beforeError(error); + }); + this[kUnproxyEvents] = proxy_events_1.default(request, this, proxiedRequestEvents); + this[kRequest] = request; + this.emit('uploadProgress', this.uploadProgress); + // Send body + const body = this[kBody]; + const currentRequest = this.redirects.length === 0 ? this : request; + if (is_1.default.nodeStream(body)) { + body.pipe(currentRequest); + body.once('error', (error) => { + this._beforeError(new UploadError(error, this)); + }); + } + else { + this._unlockWrite(); + if (!is_1.default.undefined(body)) { + this._writeRequest(body, undefined, () => { }); + currentRequest.end(); + this._lockWrite(); + } + else if (this._cannotHaveBody || this._noPipe) { + currentRequest.end(); + this._lockWrite(); + } + } + this.emit('request', request); } - if (this.options.attributesGroupName) { - const attrCollection = {}; - attrCollection[this.options.attributesGroupName] = attrs; - return attrCollection; + async _createCacheableRequest(url, options) { + return new Promise((resolve, reject) => { + // TODO: Remove `utils/url-to-options.ts` when `cacheable-request` is fixed + Object.assign(options, url_to_options_1.default(url)); + // `http-cache-semantics` checks this + // TODO: Fix this ignore. + // @ts-expect-error + delete options.url; + let request; + // This is ugly + const cacheRequest = cacheableStore.get(options.cache)(options, async (response) => { + // TODO: Fix `cacheable-response` + response._readableState.autoDestroy = false; + if (request) { + (await request).emit('cacheableResponse', response); + } + resolve(response); + }); + // Restore options + options.url = url; + cacheRequest.once('error', reject); + cacheRequest.once('request', async (requestOrPromise) => { + request = requestOrPromise; + resolve(request); + }); + }); } - return attrs - } -} - -const parseXml = function(xmlData) { - xmlData = xmlData.replace(/\r\n?/g, "\n"); //TODO: remove this line - const xmlObj = new xmlNode('!xml'); - let currentNode = xmlObj; - let textData = ""; - let jPath = ""; - for(let i=0; i< xmlData.length; i++){//for each char in XML data - const ch = xmlData[i]; - if(ch === '<'){ - // const nextIndex = i+1; - // const _2ndChar = xmlData[nextIndex]; - if( xmlData[i+1] === '/') {//Closing Tag - const closeIndex = findClosingIndex(xmlData, ">", i, "Closing Tag is not closed.") - let tagName = xmlData.substring(i+2,closeIndex).trim(); - - if(this.options.removeNSPrefix){ - const colonIndex = tagName.indexOf(":"); - if(colonIndex !== -1){ - tagName = tagName.substr(colonIndex+1); - } + async _makeRequest() { + var _a, _b, _c, _d, _e; + const { options } = this; + const { headers } = options; + for (const key in headers) { + if (is_1.default.undefined(headers[key])) { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete headers[key]; + } + else if (is_1.default.null_(headers[key])) { + throw new TypeError(`Use \`undefined\` instead of \`null\` to delete the \`${key}\` header`); + } } - - if(this.options.transformTagName) { - tagName = this.options.transformTagName(tagName); + if (options.decompress && is_1.default.undefined(headers['accept-encoding'])) { + headers['accept-encoding'] = supportsBrotli ? 'gzip, deflate, br' : 'gzip, deflate'; } - - if(currentNode){ - textData = this.saveTextToParentTag(textData, currentNode, jPath); + // Set cookies + if (options.cookieJar) { + const cookieString = await options.cookieJar.getCookieString(options.url.toString()); + if (is_1.default.nonEmptyString(cookieString)) { + options.headers.cookie = cookieString; + } } - - //check if last tag of nested tag was unpaired tag - const lastTagName = jPath.substring(jPath.lastIndexOf(".")+1); - if(tagName && this.options.unpairedTags.indexOf(tagName) !== -1 ){ - throw new Error(`Unpaired tag can not be used as closing tag: `); + for (const hook of options.hooks.beforeRequest) { + // eslint-disable-next-line no-await-in-loop + const result = await hook(options); + if (!is_1.default.undefined(result)) { + // @ts-expect-error Skip the type mismatch to support abstract responses + options.request = () => result; + break; + } } - let propIndex = 0 - if(lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1 ){ - propIndex = jPath.lastIndexOf('.', jPath.lastIndexOf('.')-1) - this.tagsNodeStack.pop(); - }else{ - propIndex = jPath.lastIndexOf("."); + if (options.body && this[kBody] !== options.body) { + this[kBody] = options.body; } - jPath = jPath.substring(0, propIndex); - - currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope - textData = ""; - i = closeIndex; - } else if( xmlData[i+1] === '?') { - - let tagData = readTagExp(xmlData,i, false, "?>"); - if(!tagData) throw new Error("Pi Tag is not closed."); - - textData = this.saveTextToParentTag(textData, currentNode, jPath); - if( (this.options.ignoreDeclaration && tagData.tagName === "?xml") || this.options.ignorePiTags){ - - }else{ - - const childNode = new xmlNode(tagData.tagName); - childNode.add(this.options.textNodeName, ""); - - if(tagData.tagName !== tagData.tagExp && tagData.attrExpPresent){ - childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName); - } - this.addChild(currentNode, childNode, jPath) - + const { agent, request, timeout, url } = options; + if (options.dnsCache && !('lookup' in options)) { + options.lookup = options.dnsCache.lookup; + } + // UNIX sockets + if (url.hostname === 'unix') { + const matches = /(?.+?):(?.+)/.exec(`${url.pathname}${url.search}`); + if (matches === null || matches === void 0 ? void 0 : matches.groups) { + const { socketPath, path } = matches.groups; + Object.assign(options, { + socketPath, + path, + host: '' + }); + } + } + const isHttps = url.protocol === 'https:'; + // Fallback function + let fallbackFn; + if (options.http2) { + fallbackFn = http2wrapper.auto; + } + else { + fallbackFn = isHttps ? https.request : http.request; + } + const realFn = (_a = options.request) !== null && _a !== void 0 ? _a : fallbackFn; + // Cache support + const fn = options.cache ? this._createCacheableRequest : realFn; + // Pass an agent directly when HTTP2 is disabled + if (agent && !options.http2) { + options.agent = agent[isHttps ? 'https' : 'http']; + } + // Prepare plain HTTP request options + options[kRequest] = realFn; + delete options.request; + // TODO: Fix this ignore. + // @ts-expect-error + delete options.timeout; + const requestOptions = options; + requestOptions.shared = (_b = options.cacheOptions) === null || _b === void 0 ? void 0 : _b.shared; + requestOptions.cacheHeuristic = (_c = options.cacheOptions) === null || _c === void 0 ? void 0 : _c.cacheHeuristic; + requestOptions.immutableMinTimeToLive = (_d = options.cacheOptions) === null || _d === void 0 ? void 0 : _d.immutableMinTimeToLive; + requestOptions.ignoreCargoCult = (_e = options.cacheOptions) === null || _e === void 0 ? void 0 : _e.ignoreCargoCult; + // If `dnsLookupIpVersion` is not present do not override `family` + if (options.dnsLookupIpVersion !== undefined) { + try { + requestOptions.family = dns_ip_version_1.dnsLookupIpVersionToFamily(options.dnsLookupIpVersion); + } + catch (_f) { + throw new Error('Invalid `dnsLookupIpVersion` option value'); + } + } + // HTTPS options remapping + if (options.https) { + if ('rejectUnauthorized' in options.https) { + requestOptions.rejectUnauthorized = options.https.rejectUnauthorized; + } + if (options.https.checkServerIdentity) { + requestOptions.checkServerIdentity = options.https.checkServerIdentity; + } + if (options.https.certificateAuthority) { + requestOptions.ca = options.https.certificateAuthority; + } + if (options.https.certificate) { + requestOptions.cert = options.https.certificate; + } + if (options.https.key) { + requestOptions.key = options.https.key; + } + if (options.https.passphrase) { + requestOptions.passphrase = options.https.passphrase; + } + if (options.https.pfx) { + requestOptions.pfx = options.https.pfx; + } + } + try { + let requestOrResponse = await fn(url, requestOptions); + if (is_1.default.undefined(requestOrResponse)) { + requestOrResponse = fallbackFn(url, requestOptions); + } + // Restore options + options.request = request; + options.timeout = timeout; + options.agent = agent; + // HTTPS options restore + if (options.https) { + if ('rejectUnauthorized' in options.https) { + delete requestOptions.rejectUnauthorized; + } + if (options.https.checkServerIdentity) { + // @ts-expect-error - This one will be removed when we remove the alias. + delete requestOptions.checkServerIdentity; + } + if (options.https.certificateAuthority) { + delete requestOptions.ca; + } + if (options.https.certificate) { + delete requestOptions.cert; + } + if (options.https.key) { + delete requestOptions.key; + } + if (options.https.passphrase) { + delete requestOptions.passphrase; + } + if (options.https.pfx) { + delete requestOptions.pfx; + } + } + if (isClientRequest(requestOrResponse)) { + this._onRequest(requestOrResponse); + // Emit the response after the stream has been ended + } + else if (this.writable) { + this.once('finish', () => { + void this._onResponse(requestOrResponse); + }); + this._unlockWrite(); + this.end(); + this._lockWrite(); + } + else { + void this._onResponse(requestOrResponse); + } } - - - i = tagData.closeIndex + 1; - } else if(xmlData.substr(i + 1, 3) === '!--') { - const endIndex = findClosingIndex(xmlData, "-->", i+4, "Comment is not closed.") - if(this.options.commentPropName){ - const comment = xmlData.substring(i + 4, endIndex - 2); - - textData = this.saveTextToParentTag(textData, currentNode, jPath); - - currentNode.add(this.options.commentPropName, [ { [this.options.textNodeName] : comment } ]); + catch (error) { + if (error instanceof CacheableRequest.CacheError) { + throw new CacheError(error, this); + } + throw new RequestError(error.message, error, this); } - i = endIndex; - } else if( xmlData.substr(i + 1, 2) === '!D') { - const result = readDocType(xmlData, i); - this.docTypeEntities = result.entities; - i = result.i; - }else if(xmlData.substr(i + 1, 2) === '![') { - const closeIndex = findClosingIndex(xmlData, "]]>", i, "CDATA is not closed.") - 2; - const tagExp = xmlData.substring(i + 9,closeIndex); - - textData = this.saveTextToParentTag(textData, currentNode, jPath); - - let val = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true); - if(val == undefined) val = ""; - - //cdata should be set even if it is 0 length string - if(this.options.cdataPropName){ - currentNode.add(this.options.cdataPropName, [ { [this.options.textNodeName] : tagExp } ]); - }else{ - currentNode.add(this.options.textNodeName, val); + } + async _error(error) { + try { + for (const hook of this.options.hooks.beforeError) { + // eslint-disable-next-line no-await-in-loop + error = await hook(error); + } } - - i = closeIndex + 2; - }else {//Opening tag - let result = readTagExp(xmlData,i, this.options.removeNSPrefix); - let tagName= result.tagName; - const rawTagName = result.rawTagName; - let tagExp = result.tagExp; - let attrExpPresent = result.attrExpPresent; - let closeIndex = result.closeIndex; - - if (this.options.transformTagName) { - tagName = this.options.transformTagName(tagName); + catch (error_) { + error = new RequestError(error_.message, error_, this); } - - //save text as child node - if (currentNode && textData) { - if(currentNode.tagname !== '!xml'){ - //when nested tag is found - textData = this.saveTextToParentTag(textData, currentNode, jPath, false); - } + this.destroy(error); + } + _beforeError(error) { + if (this[kStopReading]) { + return; } - - //check if last tag was unpaired tag - const lastTag = currentNode; - if(lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1 ){ - currentNode = this.tagsNodeStack.pop(); - jPath = jPath.substring(0, jPath.lastIndexOf(".")); + const { options } = this; + const retryCount = this.retryCount + 1; + this[kStopReading] = true; + if (!(error instanceof RequestError)) { + error = new RequestError(error.message, error, this); } - if(tagName !== xmlObj.tagname){ - jPath += jPath ? "." + tagName : tagName; + const typedError = error; + const { response } = typedError; + void (async () => { + if (response && !response.body) { + response.setEncoding(this._readableState.encoding); + try { + response.rawBody = await get_buffer_1.default(response); + response.body = response.rawBody.toString(); + } + catch (_a) { } + } + if (this.listenerCount('retry') !== 0) { + let backoff; + try { + let retryAfter; + if (response && 'retry-after' in response.headers) { + retryAfter = Number(response.headers['retry-after']); + if (Number.isNaN(retryAfter)) { + retryAfter = Date.parse(response.headers['retry-after']) - Date.now(); + if (retryAfter <= 0) { + retryAfter = 1; + } + } + else { + retryAfter *= 1000; + } + } + backoff = await options.retry.calculateDelay({ + attemptCount: retryCount, + retryOptions: options.retry, + error: typedError, + retryAfter, + computedValue: calculate_retry_delay_1.default({ + attemptCount: retryCount, + retryOptions: options.retry, + error: typedError, + retryAfter, + computedValue: 0 + }) + }); + } + catch (error_) { + void this._error(new RequestError(error_.message, error_, this)); + return; + } + if (backoff) { + const retry = async () => { + try { + for (const hook of this.options.hooks.beforeRetry) { + // eslint-disable-next-line no-await-in-loop + await hook(this.options, typedError, retryCount); + } + } + catch (error_) { + void this._error(new RequestError(error_.message, error, this)); + return; + } + // Something forced us to abort the retry + if (this.destroyed) { + return; + } + this.destroy(); + this.emit('retry', retryCount, error); + }; + this[kRetryTimeout] = setTimeout(retry, backoff); + return; + } + } + void this._error(typedError); + })(); + } + _read() { + this[kTriggerRead] = true; + const response = this[kResponse]; + if (response && !this[kStopReading]) { + // We cannot put this in the `if` above + // because `.read()` also triggers the `end` event + if (response.readableLength) { + this[kTriggerRead] = false; + } + let data; + while ((data = response.read()) !== null) { + this[kDownloadedSize] += data.length; + this[kStartedReading] = true; + const progress = this.downloadProgress; + if (progress.percent < 1) { + this.emit('downloadProgress', progress); + } + this.push(data); + } } - if (this.isItStopNode(this.options.stopNodes, jPath, tagName)) { - let tagContent = ""; - //self-closing tag - if(tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1){ - if(tagName[tagName.length - 1] === "/"){ //remove trailing '/' - tagName = tagName.substr(0, tagName.length - 1); - jPath = jPath.substr(0, jPath.length - 1); - tagExp = tagName; - }else{ - tagExp = tagExp.substr(0, tagExp.length - 1); + } + // Node.js 12 has incorrect types, so the encoding must be a string + _write(chunk, encoding, callback) { + const write = () => { + this._writeRequest(chunk, encoding, callback); + }; + if (this.requestInitialized) { + write(); + } + else { + this[kJobs].push(write); + } + } + _writeRequest(chunk, encoding, callback) { + if (this[kRequest].destroyed) { + // Probably the `ClientRequest` instance will throw + return; + } + this._progressCallbacks.push(() => { + this[kUploadedSize] += Buffer.byteLength(chunk, encoding); + const progress = this.uploadProgress; + if (progress.percent < 1) { + this.emit('uploadProgress', progress); } - i = result.closeIndex; - } - //unpaired tag - else if(this.options.unpairedTags.indexOf(tagName) !== -1){ - - i = result.closeIndex; - } - //normal tag - else{ - //read until closing tag is found - const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1); - if(!result) throw new Error(`Unexpected end of ${rawTagName}`); - i = result.i; - tagContent = result.tagContent; - } - - const childNode = new xmlNode(tagName); - if(tagName !== tagExp && attrExpPresent){ - childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); - } - if(tagContent) { - tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true); - } - - jPath = jPath.substr(0, jPath.lastIndexOf(".")); - childNode.add(this.options.textNodeName, tagContent); - - this.addChild(currentNode, childNode, jPath) - }else{ - //selfClosing tag - if(tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1){ - if(tagName[tagName.length - 1] === "/"){ //remove trailing '/' - tagName = tagName.substr(0, tagName.length - 1); - jPath = jPath.substr(0, jPath.length - 1); - tagExp = tagName; - }else{ - tagExp = tagExp.substr(0, tagExp.length - 1); + }); + // TODO: What happens if it's from cache? Then this[kRequest] won't be defined. + this[kRequest].write(chunk, encoding, (error) => { + if (!error && this._progressCallbacks.length > 0) { + this._progressCallbacks.shift()(); } - - if(this.options.transformTagName) { - tagName = this.options.transformTagName(tagName); + callback(error); + }); + } + _final(callback) { + const endRequest = () => { + // FIX: Node.js 10 calls the write callback AFTER the end callback! + while (this._progressCallbacks.length !== 0) { + this._progressCallbacks.shift()(); } - - const childNode = new xmlNode(tagName); - if(tagName !== tagExp && attrExpPresent){ - childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); + // We need to check if `this[kRequest]` is present, + // because it isn't when we use cache. + if (!(kRequest in this)) { + callback(); + return; } - this.addChild(currentNode, childNode, jPath) - jPath = jPath.substr(0, jPath.lastIndexOf(".")); - } - //opening tag - else{ - const childNode = new xmlNode( tagName); - this.tagsNodeStack.push(currentNode); - - if(tagName !== tagExp && attrExpPresent){ - childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); + if (this[kRequest].destroyed) { + callback(); + return; } - this.addChild(currentNode, childNode, jPath) - currentNode = childNode; - } - textData = ""; - i = closeIndex; + this[kRequest].end((error) => { + if (!error) { + this[kBodySize] = this[kUploadedSize]; + this.emit('uploadProgress', this.uploadProgress); + this[kRequest].emit('upload-complete'); + } + callback(error); + }); + }; + if (this.requestInitialized) { + endRequest(); + } + else { + this[kJobs].push(endRequest); } - } - }else{ - textData += xmlData[i]; } - } - return xmlObj.child; -} - -function addChild(currentNode, childNode, jPath){ - const result = this.options.updateTag(childNode.tagname, jPath, childNode[":@"]) - if(result === false){ - }else if(typeof result === "string"){ - childNode.tagname = result - currentNode.addChild(childNode); - }else{ - currentNode.addChild(childNode); - } -} - -const replaceEntitiesValue = function(val){ - - if(this.options.processEntities){ - for(let entityName in this.docTypeEntities){ - const entity = this.docTypeEntities[entityName]; - val = val.replace( entity.regx, entity.val); + _destroy(error, callback) { + var _a; + this[kStopReading] = true; + // Prevent further retries + clearTimeout(this[kRetryTimeout]); + if (kRequest in this) { + this[kCancelTimeouts](); + // TODO: Remove the next `if` when these get fixed: + // - https://github.com/nodejs/node/issues/32851 + if (!((_a = this[kResponse]) === null || _a === void 0 ? void 0 : _a.complete)) { + this[kRequest].destroy(); + } + } + if (error !== null && !is_1.default.undefined(error) && !(error instanceof RequestError)) { + error = new RequestError(error.message, error, this); + } + callback(error); } - for(let entityName in this.lastEntities){ - const entity = this.lastEntities[entityName]; - val = val.replace( entity.regex, entity.val); + get _isAboutToError() { + return this[kStopReading]; } - if(this.options.htmlEntities){ - for(let entityName in this.htmlEntities){ - const entity = this.htmlEntities[entityName]; - val = val.replace( entity.regex, entity.val); - } + /** + The remote IP address. + */ + get ip() { + var _a; + return (_a = this.socket) === null || _a === void 0 ? void 0 : _a.remoteAddress; } - val = val.replace( this.ampEntity.regex, this.ampEntity.val); - } - return val; -} -function saveTextToParentTag(textData, currentNode, jPath, isLeafNode) { - if (textData) { //store previously collected data as textNode - if(isLeafNode === undefined) isLeafNode = Object.keys(currentNode.child).length === 0 - - textData = this.parseTextData(textData, - currentNode.tagname, - jPath, - false, - currentNode[":@"] ? Object.keys(currentNode[":@"]).length !== 0 : false, - isLeafNode); - - if (textData !== undefined && textData !== "") - currentNode.add(this.options.textNodeName, textData); - textData = ""; - } - return textData; -} - -//TODO: use jPath to simplify the logic -/** - * - * @param {string[]} stopNodes - * @param {string} jPath - * @param {string} currentTagName - */ -function isItStopNode(stopNodes, jPath, currentTagName){ - const allNodesExp = "*." + currentTagName; - for (const stopNodePath in stopNodes) { - const stopNodeExp = stopNodes[stopNodePath]; - if( allNodesExp === stopNodeExp || jPath === stopNodeExp ) return true; - } - return false; -} - -/** - * Returns the tag Expression and where it is ending handling single-double quotes situation - * @param {string} xmlData - * @param {number} i starting index - * @returns - */ -function tagExpWithClosingIndex(xmlData, i, closingChar = ">"){ - let attrBoundary; - let tagExp = ""; - for (let index = i; index < xmlData.length; index++) { - let ch = xmlData[index]; - if (attrBoundary) { - if (ch === attrBoundary) attrBoundary = "";//reset - } else if (ch === '"' || ch === "'") { - attrBoundary = ch; - } else if (ch === closingChar[0]) { - if(closingChar[1]){ - if(xmlData[index + 1] === closingChar[1]){ - return { - data: tagExp, - index: index - } + /** + Indicates whether the request has been aborted or not. + */ + get aborted() { + var _a, _b, _c; + return ((_b = (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.destroyed) !== null && _b !== void 0 ? _b : this.destroyed) && !((_c = this[kOriginalResponse]) === null || _c === void 0 ? void 0 : _c.complete); + } + get socket() { + var _a, _b; + return (_b = (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.socket) !== null && _b !== void 0 ? _b : undefined; + } + /** + Progress event for downloading (receiving a response). + */ + get downloadProgress() { + let percent; + if (this[kResponseSize]) { + percent = this[kDownloadedSize] / this[kResponseSize]; } - }else{ - return { - data: tagExp, - index: index + else if (this[kResponseSize] === this[kDownloadedSize]) { + percent = 1; } - } - } else if (ch === '\t') { - ch = " " - } - tagExp += ch; - } -} - -function findClosingIndex(xmlData, str, i, errMsg){ - const closingIndex = xmlData.indexOf(str, i); - if(closingIndex === -1){ - throw new Error(errMsg) - }else{ - return closingIndex + str.length - 1; - } -} - -function readTagExp(xmlData,i, removeNSPrefix, closingChar = ">"){ - const result = tagExpWithClosingIndex(xmlData, i+1, closingChar); - if(!result) return; - let tagExp = result.data; - const closeIndex = result.index; - const separatorIndex = tagExp.search(/\s/); - let tagName = tagExp; - let attrExpPresent = true; - if(separatorIndex !== -1){//separate tag name and attributes expression - tagName = tagExp.substring(0, separatorIndex); - tagExp = tagExp.substring(separatorIndex + 1).trimStart(); - } - - const rawTagName = tagName; - if(removeNSPrefix){ - const colonIndex = tagName.indexOf(":"); - if(colonIndex !== -1){ - tagName = tagName.substr(colonIndex+1); - attrExpPresent = tagName !== result.data.substr(colonIndex + 1); + else { + percent = 0; + } + return { + percent, + transferred: this[kDownloadedSize], + total: this[kResponseSize] + }; } - } - - return { - tagName: tagName, - tagExp: tagExp, - closeIndex: closeIndex, - attrExpPresent: attrExpPresent, - rawTagName: rawTagName, - } -} -/** - * find paired tag for a stop node - * @param {string} xmlData - * @param {string} tagName - * @param {number} i - */ -function readStopNodeData(xmlData, tagName, i){ - const startIndex = i; - // Starting at 1 since we already have an open tag - let openTagCount = 1; - - for (; i < xmlData.length; i++) { - if( xmlData[i] === "<"){ - if (xmlData[i+1] === "/") {//close tag - const closeIndex = findClosingIndex(xmlData, ">", i, `${tagName} is not closed`); - let closeTagName = xmlData.substring(i+2,closeIndex).trim(); - if(closeTagName === tagName){ - openTagCount--; - if (openTagCount === 0) { - return { - tagContent: xmlData.substring(startIndex, i), - i : closeIndex - } - } - } - i=closeIndex; - } else if(xmlData[i+1] === '?') { - const closeIndex = findClosingIndex(xmlData, "?>", i+1, "StopNode is not closed.") - i=closeIndex; - } else if(xmlData.substr(i + 1, 3) === '!--') { - const closeIndex = findClosingIndex(xmlData, "-->", i+3, "StopNode is not closed.") - i=closeIndex; - } else if(xmlData.substr(i + 1, 2) === '![') { - const closeIndex = findClosingIndex(xmlData, "]]>", i, "StopNode is not closed.") - 2; - i=closeIndex; - } else { - const tagData = readTagExp(xmlData, i, '>') - - if (tagData) { - const openTagName = tagData && tagData.tagName; - if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length-1] !== "/") { - openTagCount++; - } - i=tagData.closeIndex; - } + /** + Progress event for uploading (sending a request). + */ + get uploadProgress() { + let percent; + if (this[kBodySize]) { + percent = this[kUploadedSize] / this[kBodySize]; } - } - }//end for loop -} - -function parseValue(val, shouldParse, options) { - if (shouldParse && typeof val === 'string') { - //console.log(options) - const newval = val.trim(); - if(newval === 'true' ) return true; - else if(newval === 'false' ) return false; - else return toNumber(val, options); - } else { - if (util.isExist(val)) { - return val; - } else { - return ''; + else if (this[kBodySize] === this[kUploadedSize]) { + percent = 1; + } + else { + percent = 0; + } + return { + percent, + transferred: this[kUploadedSize], + total: this[kBodySize] + }; } - } -} - - -module.exports = OrderedObjParser; - - -/***/ }), + /** + The object contains the following properties: -/***/ 42380: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + - `start` - Time when the request started. + - `socket` - Time when a socket was assigned to the request. + - `lookup` - Time when the DNS lookup finished. + - `connect` - Time when the socket successfully connected. + - `secureConnect` - Time when the socket securely connected. + - `upload` - Time when the request finished uploading. + - `response` - Time when the request fired `response` event. + - `end` - Time when the response fired `end` event. + - `error` - Time when the request fired `error` event. + - `abort` - Time when the request fired `abort` event. + - `phases` + - `wait` - `timings.socket - timings.start` + - `dns` - `timings.lookup - timings.socket` + - `tcp` - `timings.connect - timings.lookup` + - `tls` - `timings.secureConnect - timings.connect` + - `request` - `timings.upload - (timings.secureConnect || timings.connect)` + - `firstByte` - `timings.response - timings.upload` + - `download` - `timings.end - timings.response` + - `total` - `(timings.end || timings.error || timings.abort) - timings.start` -const { buildOptions} = __nccwpck_require__(86993); -const OrderedObjParser = __nccwpck_require__(25832); -const { prettify} = __nccwpck_require__(42882); -const validator = __nccwpck_require__(61739); + If something has not been measured yet, it will be `undefined`. -class XMLParser{ - - constructor(options){ - this.externalEntities = {}; - this.options = buildOptions(options); - + __Note__: The time is a `number` representing the milliseconds elapsed since the UNIX epoch. + */ + get timings() { + var _a; + return (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.timings; } /** - * Parse XML dats to JS object - * @param {string|Buffer} xmlData - * @param {boolean|Object} validationOption - */ - parse(xmlData,validationOption){ - if(typeof xmlData === "string"){ - }else if( xmlData.toString){ - xmlData = xmlData.toString(); - }else{ - throw new Error("XML data is accepted in String or Bytes[] form.") + Whether the response was retrieved from the cache. + */ + get isFromCache() { + return this[kIsFromCache]; + } + pipe(destination, options) { + if (this[kStartedReading]) { + throw new Error('Failed to pipe. The response has been emitted already.'); } - if( validationOption){ - if(validationOption === true) validationOption = {}; //validate with default options - - const result = validator.validate(xmlData, validationOption); - if (result !== true) { - throw Error( `${result.err.msg}:${result.err.line}:${result.err.col}` ) - } - } - const orderedObjParser = new OrderedObjParser(this.options); - orderedObjParser.addExternalEntities(this.externalEntities); - const orderedResult = orderedObjParser.parseXml(xmlData); - if(this.options.preserveOrder || orderedResult === undefined) return orderedResult; - else return prettify(orderedResult, this.options); + if (destination instanceof http_1.ServerResponse) { + this[kServerResponsesPiped].add(destination); + } + return super.pipe(destination, options); } - - /** - * Add Entity which is not by default supported by this library - * @param {string} key - * @param {string} value - */ - addEntity(key, value){ - if(value.indexOf("&") !== -1){ - throw new Error("Entity value can't have '&'") - }else if(key.indexOf("&") !== -1 || key.indexOf(";") !== -1){ - throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for ' '") - }else if(value === "&"){ - throw new Error("An entity with value '&' is not permitted"); - }else{ - this.externalEntities[key] = value; + unpipe(destination) { + if (destination instanceof http_1.ServerResponse) { + this[kServerResponsesPiped].delete(destination); } + super.unpipe(destination); + return this; } } +exports["default"] = Request; -module.exports = XMLParser; /***/ }), -/***/ 42882: +/***/ 94993: /***/ ((__unused_webpack_module, exports) => { "use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.dnsLookupIpVersionToFamily = exports.isDnsLookupIpVersion = void 0; +const conversionTable = { + auto: 0, + ipv4: 4, + ipv6: 6 +}; +exports.isDnsLookupIpVersion = (value) => { + return value in conversionTable; +}; +exports.dnsLookupIpVersionToFamily = (dnsLookupIpVersion) => { + if (exports.isDnsLookupIpVersion(dnsLookupIpVersion)) { + return conversionTable[dnsLookupIpVersion]; + } + throw new Error('Invalid DNS lookup IP version'); +}; -/** - * - * @param {array} node - * @param {any} options - * @returns - */ -function prettify(node, options){ - return compress( node, options); -} -/** - * - * @param {array} arr - * @param {object} options - * @param {string} jPath - * @returns object - */ -function compress(arr, options, jPath){ - let text; - const compressedObj = {}; - for (let i = 0; i < arr.length; i++) { - const tagObj = arr[i]; - const property = propName(tagObj); - let newJpath = ""; - if(jPath === undefined) newJpath = property; - else newJpath = jPath + "." + property; +/***/ }), - if(property === options.textNodeName){ - if(text === undefined) text = tagObj[property]; - else text += "" + tagObj[property]; - }else if(property === undefined){ - continue; - }else if(tagObj[property]){ - - let val = compress(tagObj[property], options, newJpath); - const isLeaf = isLeafTag(val, options); +/***/ 94564: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if(tagObj[":@"]){ - assignAttributes( val, tagObj[":@"], newJpath, options); - }else if(Object.keys(val).length === 1 && val[options.textNodeName] !== undefined && !options.alwaysCreateTextNode){ - val = val[options.textNodeName]; - }else if(Object.keys(val).length === 0){ - if(options.alwaysCreateTextNode) val[options.textNodeName] = ""; - else val = ""; - } +"use strict"; - if(compressedObj[property] !== undefined && compressedObj.hasOwnProperty(property)) { - if(!Array.isArray(compressedObj[property])) { - compressedObj[property] = [ compressedObj[property] ]; - } - compressedObj[property].push(val); - }else{ - //TODO: if a node is not an array, then check if it should be an array - //also determine if it is a leaf node - if (options.isArray(property, newJpath, isLeaf )) { - compressedObj[property] = [val]; - }else{ - compressedObj[property] = val; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const fs_1 = __nccwpck_require__(57147); +const util_1 = __nccwpck_require__(73837); +const is_1 = __nccwpck_require__(7678); +const is_form_data_1 = __nccwpck_require__(90040); +const statAsync = util_1.promisify(fs_1.stat); +exports["default"] = async (body, headers) => { + if (headers && 'content-length' in headers) { + return Number(headers['content-length']); + } + if (!body) { + return 0; + } + if (is_1.default.string(body)) { + return Buffer.byteLength(body); + } + if (is_1.default.buffer(body)) { + return body.length; + } + if (is_form_data_1.default(body)) { + return util_1.promisify(body.getLength.bind(body))(); + } + if (body instanceof fs_1.ReadStream) { + const { size } = await statAsync(body.path); + if (size === 0) { + return undefined; } - } + return size; } - - } - // if(text && text.length > 0) compressedObj[options.textNodeName] = text; - if(typeof text === "string"){ - if(text.length > 0) compressedObj[options.textNodeName] = text; - }else if(text !== undefined) compressedObj[options.textNodeName] = text; - return compressedObj; -} + return undefined; +}; -function propName(obj){ - const keys = Object.keys(obj); - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; - if(key !== ":@") return key; - } -} -function assignAttributes(obj, attrMap, jpath, options){ - if (attrMap) { - const keys = Object.keys(attrMap); - const len = keys.length; //don't make it inline - for (let i = 0; i < len; i++) { - const atrrName = keys[i]; - if (options.isArray(atrrName, jpath + "." + atrrName, true, true)) { - obj[atrrName] = [ attrMap[atrrName] ]; - } else { - obj[atrrName] = attrMap[atrrName]; - } - } - } -} +/***/ }), -function isLeafTag(obj, options){ - const { textNodeName } = options; - const propCount = Object.keys(obj).length; - - if (propCount === 0) { - return true; - } +/***/ 34500: +/***/ ((__unused_webpack_module, exports) => { - if ( - propCount === 1 && - (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0) - ) { - return true; - } +"use strict"; - return false; -} -exports.prettify = prettify; +Object.defineProperty(exports, "__esModule", ({ value: true })); +// TODO: Update https://github.com/sindresorhus/get-stream +const getBuffer = async (stream) => { + const chunks = []; + let length = 0; + for await (const chunk of stream) { + chunks.push(chunk); + length += Buffer.byteLength(chunk); + } + if (Buffer.isBuffer(chunks[0])) { + return Buffer.concat(chunks, length); + } + return Buffer.from(chunks.join('')); +}; +exports["default"] = getBuffer; /***/ }), -/***/ 7462: -/***/ ((module) => { +/***/ 90040: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const is_1 = __nccwpck_require__(7678); +exports["default"] = (body) => is_1.default.nodeStream(body) && is_1.default.function_(body.getBoundary); -class XmlNode{ - constructor(tagname) { - this.tagname = tagname; - this.child = []; //nested tags, text, cdata, comments in order - this[":@"] = {}; //attributes map - } - add(key,val){ - // this.child.push( {name : key, val: val, isCdata: isCdata }); - if(key === "__proto__") key = "#__proto__"; - this.child.push( {[key]: val }); - } - addChild(node) { - if(node.tagname === "__proto__") node.tagname = "#__proto__"; - if(node[":@"] && Object.keys(node[":@"]).length > 0){ - this.child.push( { [node.tagname]: node.child, [":@"]: node[":@"] }); - }else{ - this.child.push( { [node.tagname]: node.child }); - } - }; -}; - - -module.exports = XmlNode; /***/ }), -/***/ 31133: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 49298: +/***/ ((__unused_webpack_module, exports) => { -var debug; +"use strict"; -module.exports = function () { - if (!debug) { - try { - /* eslint global-require: off */ - debug = __nccwpck_require__(38237)("follow-redirects"); - } - catch (error) { /* */ } - if (typeof debug !== "function") { - debug = function () { /* */ }; - } - } - debug.apply(null, arguments); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isResponseOk = void 0; +exports.isResponseOk = (response) => { + const { statusCode } = response; + const limitStatusCode = response.request.options.followRedirect ? 299 : 399; + return (statusCode >= 200 && statusCode <= limitStatusCode) || statusCode === 304; }; /***/ }), -/***/ 67707: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var url = __nccwpck_require__(57310); -var URL = url.URL; -var http = __nccwpck_require__(13685); -var https = __nccwpck_require__(95687); -var Writable = (__nccwpck_require__(12781).Writable); -var assert = __nccwpck_require__(39491); -var debug = __nccwpck_require__(31133); - -// Preventive platform detection -// istanbul ignore next -(function detectUnsupportedEnvironment() { - var looksLikeNode = typeof process !== "undefined"; - var looksLikeBrowser = typeof window !== "undefined" && typeof document !== "undefined"; - var looksLikeV8 = isFunction(Error.captureStackTrace); - if (!looksLikeNode && (looksLikeBrowser || !looksLikeV8)) { - console.warn("The follow-redirects package should be excluded from browser builds."); - } -}()); +/***/ 9219: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// Whether to use the native URL object or the legacy url module -var useNativeURL = false; -try { - assert(new URL("")); -} -catch (error) { - useNativeURL = error.code === "ERR_INVALID_URL"; -} +"use strict"; -// URL fields to preserve in copy operations -var preservedUrlFields = [ - "auth", - "host", - "hostname", - "href", - "path", - "pathname", - "port", - "protocol", - "query", - "search", - "hash", +Object.defineProperty(exports, "__esModule", ({ value: true })); +/* istanbul ignore file: deprecated */ +const url_1 = __nccwpck_require__(57310); +const keys = [ + 'protocol', + 'host', + 'hostname', + 'port', + 'pathname', + 'search' ]; +exports["default"] = (origin, options) => { + var _a, _b; + if (options.path) { + if (options.pathname) { + throw new TypeError('Parameters `path` and `pathname` are mutually exclusive.'); + } + if (options.search) { + throw new TypeError('Parameters `path` and `search` are mutually exclusive.'); + } + if (options.searchParams) { + throw new TypeError('Parameters `path` and `searchParams` are mutually exclusive.'); + } + } + if (options.search && options.searchParams) { + throw new TypeError('Parameters `search` and `searchParams` are mutually exclusive.'); + } + if (!origin) { + if (!options.protocol) { + throw new TypeError('No URL protocol specified'); + } + origin = `${options.protocol}//${(_b = (_a = options.hostname) !== null && _a !== void 0 ? _a : options.host) !== null && _b !== void 0 ? _b : ''}`; + } + const url = new url_1.URL(origin); + if (options.path) { + const searchIndex = options.path.indexOf('?'); + if (searchIndex === -1) { + options.pathname = options.path; + } + else { + options.pathname = options.path.slice(0, searchIndex); + options.search = options.path.slice(searchIndex + 1); + } + delete options.path; + } + for (const key of keys) { + if (options[key]) { + url[key] = options[key].toString(); + } + } + return url; +}; -// Create handlers that pass events from native requests -var events = ["abort", "aborted", "connect", "error", "socket", "timeout"]; -var eventHandlers = Object.create(null); -events.forEach(function (event) { - eventHandlers[event] = function (arg1, arg2, arg3) { - this._redirectable.emit(event, arg1, arg2, arg3); - }; -}); - -// Error types with codes -var InvalidUrlError = createErrorType( - "ERR_INVALID_URL", - "Invalid URL", - TypeError -); -var RedirectionError = createErrorType( - "ERR_FR_REDIRECTION_FAILURE", - "Redirected request failed" -); -var TooManyRedirectsError = createErrorType( - "ERR_FR_TOO_MANY_REDIRECTS", - "Maximum number of redirects exceeded", - RedirectionError -); -var MaxBodyLengthExceededError = createErrorType( - "ERR_FR_MAX_BODY_LENGTH_EXCEEDED", - "Request body larger than maxBodyLength limit" -); -var WriteAfterEndError = createErrorType( - "ERR_STREAM_WRITE_AFTER_END", - "write after end" -); - -// istanbul ignore next -var destroy = Writable.prototype.destroy || noop; -// An HTTP(S) request that can be redirected -function RedirectableRequest(options, responseCallback) { - // Initialize the request - Writable.call(this); - this._sanitizeOptions(options); - this._options = options; - this._ended = false; - this._ending = false; - this._redirectCount = 0; - this._redirects = []; - this._requestBodyLength = 0; - this._requestBodyBuffers = []; +/***/ }), - // Attach a callback if passed - if (responseCallback) { - this.on("response", responseCallback); - } +/***/ 53021: +/***/ ((__unused_webpack_module, exports) => { - // React to responses of native requests - var self = this; - this._onNativeResponse = function (response) { - try { - self._processResponse(response); - } - catch (cause) { - self.emit("error", cause instanceof RedirectionError ? - cause : new RedirectionError({ cause: cause })); - } - }; +"use strict"; - // Perform the first request - this._performRequest(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +function default_1(from, to, events) { + const fns = {}; + for (const event of events) { + fns[event] = (...args) => { + to.emit(event, ...args); + }; + from.on(event, fns[event]); + } + return () => { + for (const event of events) { + from.off(event, fns[event]); + } + }; } -RedirectableRequest.prototype = Object.create(Writable.prototype); +exports["default"] = default_1; -RedirectableRequest.prototype.abort = function () { - destroyRequest(this._currentRequest); - this._currentRequest.abort(); - this.emit("abort"); -}; -RedirectableRequest.prototype.destroy = function (error) { - destroyRequest(this._currentRequest, error); - destroy.call(this, error); - return this; -}; +/***/ }), -// Writes buffered data to the current native request -RedirectableRequest.prototype.write = function (data, encoding, callback) { - // Writing is not allowed if end has been called - if (this._ending) { - throw new WriteAfterEndError(); - } +/***/ 52454: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // Validate input and shift parameters if necessary - if (!isString(data) && !isBuffer(data)) { - throw new TypeError("data should be a string, Buffer or Uint8Array"); - } - if (isFunction(encoding)) { - callback = encoding; - encoding = null; - } +"use strict"; - // Ignore empty buffers, since writing them doesn't invoke the callback - // https://github.com/nodejs/node/issues/22066 - if (data.length === 0) { - if (callback) { - callback(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TimeoutError = void 0; +const net = __nccwpck_require__(41808); +const unhandle_1 = __nccwpck_require__(81593); +const reentry = Symbol('reentry'); +const noop = () => { }; +class TimeoutError extends Error { + constructor(threshold, event) { + super(`Timeout awaiting '${event}' for ${threshold}ms`); + this.event = event; + this.name = 'TimeoutError'; + this.code = 'ETIMEDOUT'; } - return; - } - // Only write when we don't exceed the maximum body length - if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { - this._requestBodyLength += data.length; - this._requestBodyBuffers.push({ data: data, encoding: encoding }); - this._currentRequest.write(data, encoding, callback); - } - // Error when we exceed the maximum body length - else { - this.emit("error", new MaxBodyLengthExceededError()); - this.abort(); - } +} +exports.TimeoutError = TimeoutError; +exports["default"] = (request, delays, options) => { + if (reentry in request) { + return noop; + } + request[reentry] = true; + const cancelers = []; + const { once, unhandleAll } = unhandle_1.default(); + const addTimeout = (delay, callback, event) => { + var _a; + const timeout = setTimeout(callback, delay, delay, event); + (_a = timeout.unref) === null || _a === void 0 ? void 0 : _a.call(timeout); + const cancel = () => { + clearTimeout(timeout); + }; + cancelers.push(cancel); + return cancel; + }; + const { host, hostname } = options; + const timeoutHandler = (delay, event) => { + request.destroy(new TimeoutError(delay, event)); + }; + const cancelTimeouts = () => { + for (const cancel of cancelers) { + cancel(); + } + unhandleAll(); + }; + request.once('error', error => { + cancelTimeouts(); + // Save original behavior + /* istanbul ignore next */ + if (request.listenerCount('error') === 0) { + throw error; + } + }); + request.once('close', cancelTimeouts); + once(request, 'response', (response) => { + once(response, 'end', cancelTimeouts); + }); + if (typeof delays.request !== 'undefined') { + addTimeout(delays.request, timeoutHandler, 'request'); + } + if (typeof delays.socket !== 'undefined') { + const socketTimeoutHandler = () => { + timeoutHandler(delays.socket, 'socket'); + }; + request.setTimeout(delays.socket, socketTimeoutHandler); + // `request.setTimeout(0)` causes a memory leak. + // We can just remove the listener and forget about the timer - it's unreffed. + // See https://github.com/sindresorhus/got/issues/690 + cancelers.push(() => { + request.removeListener('timeout', socketTimeoutHandler); + }); + } + once(request, 'socket', (socket) => { + var _a; + const { socketPath } = request; + /* istanbul ignore next: hard to test */ + if (socket.connecting) { + const hasPath = Boolean(socketPath !== null && socketPath !== void 0 ? socketPath : net.isIP((_a = hostname !== null && hostname !== void 0 ? hostname : host) !== null && _a !== void 0 ? _a : '') !== 0); + if (typeof delays.lookup !== 'undefined' && !hasPath && typeof socket.address().address === 'undefined') { + const cancelTimeout = addTimeout(delays.lookup, timeoutHandler, 'lookup'); + once(socket, 'lookup', cancelTimeout); + } + if (typeof delays.connect !== 'undefined') { + const timeConnect = () => addTimeout(delays.connect, timeoutHandler, 'connect'); + if (hasPath) { + once(socket, 'connect', timeConnect()); + } + else { + once(socket, 'lookup', (error) => { + if (error === null) { + once(socket, 'connect', timeConnect()); + } + }); + } + } + if (typeof delays.secureConnect !== 'undefined' && options.protocol === 'https:') { + once(socket, 'connect', () => { + const cancelTimeout = addTimeout(delays.secureConnect, timeoutHandler, 'secureConnect'); + once(socket, 'secureConnect', cancelTimeout); + }); + } + } + if (typeof delays.send !== 'undefined') { + const timeRequest = () => addTimeout(delays.send, timeoutHandler, 'send'); + /* istanbul ignore next: hard to test */ + if (socket.connecting) { + once(socket, 'connect', () => { + once(request, 'upload-complete', timeRequest()); + }); + } + else { + once(request, 'upload-complete', timeRequest()); + } + } + }); + if (typeof delays.response !== 'undefined') { + once(request, 'upload-complete', () => { + const cancelTimeout = addTimeout(delays.response, timeoutHandler, 'response'); + once(request, 'response', cancelTimeout); + }); + } + return cancelTimeouts; }; -// Ends the current native request -RedirectableRequest.prototype.end = function (data, encoding, callback) { - // Shift parameters if necessary - if (isFunction(data)) { - callback = data; - data = encoding = null; - } - else if (isFunction(encoding)) { - callback = encoding; - encoding = null; - } - // Write data if needed and end - if (!data) { - this._ended = this._ending = true; - this._currentRequest.end(null, null, callback); - } - else { - var self = this; - var currentRequest = this._currentRequest; - this.write(data, encoding, function () { - self._ended = true; - currentRequest.end(null, null, callback); - }); - this._ending = true; - } -}; +/***/ }), -// Sets a header value on the current native request -RedirectableRequest.prototype.setHeader = function (name, value) { - this._options.headers[name] = value; - this._currentRequest.setHeader(name, value); -}; +/***/ 81593: +/***/ ((__unused_webpack_module, exports) => { -// Clears a header value on the current native request -RedirectableRequest.prototype.removeHeader = function (name) { - delete this._options.headers[name]; - this._currentRequest.removeHeader(name); +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +// When attaching listeners, it's very easy to forget about them. +// Especially if you do error handling and set timeouts. +// So instead of checking if it's proper to throw an error on every timeout ever, +// use this simple tool which will remove all listeners you have attached. +exports["default"] = () => { + const handlers = []; + return { + once(origin, event, fn) { + origin.once(event, fn); + handlers.push({ origin, event, fn }); + }, + unhandleAll() { + for (const handler of handlers) { + const { origin, event, fn } = handler; + origin.removeListener(event, fn); + } + handlers.length = 0; + } + }; }; -// Global timeout for all underlying requests -RedirectableRequest.prototype.setTimeout = function (msecs, callback) { - var self = this; - // Destroys the socket on timeout - function destroyOnTimeout(socket) { - socket.setTimeout(msecs); - socket.removeListener("timeout", socket.destroy); - socket.addListener("timeout", socket.destroy); - } +/***/ }), - // Sets up a timer to trigger a timeout event - function startTimer(socket) { - if (self._timeout) { - clearTimeout(self._timeout); - } - self._timeout = setTimeout(function () { - self.emit("timeout"); - clearTimer(); - }, msecs); - destroyOnTimeout(socket); - } +/***/ 8026: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // Stops a timeout from triggering - function clearTimer() { - // Clear the timeout - if (self._timeout) { - clearTimeout(self._timeout); - self._timeout = null; - } +"use strict"; - // Clean up all attached listeners - self.removeListener("abort", clearTimer); - self.removeListener("error", clearTimer); - self.removeListener("response", clearTimer); - self.removeListener("close", clearTimer); - if (callback) { - self.removeListener("timeout", callback); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const is_1 = __nccwpck_require__(7678); +exports["default"] = (url) => { + // Cast to URL + url = url; + const options = { + protocol: url.protocol, + hostname: is_1.default.string(url.hostname) && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname, + host: url.host, + hash: url.hash, + search: url.search, + pathname: url.pathname, + href: url.href, + path: `${url.pathname || ''}${url.search || ''}` + }; + if (is_1.default.string(url.port) && url.port.length > 0) { + options.port = Number(url.port); } - if (!self.socket) { - self._currentRequest.removeListener("socket", startTimer); + if (url.username || url.password) { + options.auth = `${url.username || ''}:${url.password || ''}`; } - } - - // Attach callback if passed - if (callback) { - this.on("timeout", callback); - } - - // Start the timer if or when the socket is opened - if (this.socket) { - startTimer(this.socket); - } - else { - this._currentRequest.once("socket", startTimer); - } - - // Clean up on events - this.on("socket", destroyOnTimeout); - this.on("abort", clearTimer); - this.on("error", clearTimer); - this.on("response", clearTimer); - this.on("close", clearTimer); - - return this; + return options; }; -// Proxy all other public ClientRequest methods -[ - "flushHeaders", "getHeader", - "setNoDelay", "setSocketKeepAlive", -].forEach(function (method) { - RedirectableRequest.prototype[method] = function (a, b) { - return this._currentRequest[method](a, b); - }; -}); -// Proxy all public ClientRequest properties -["aborted", "connection", "socket"].forEach(function (property) { - Object.defineProperty(RedirectableRequest.prototype, property, { - get: function () { return this._currentRequest[property]; }, - }); -}); +/***/ }), -RedirectableRequest.prototype._sanitizeOptions = function (options) { - // Ensure headers are always present - if (!options.headers) { - options.headers = {}; - } +/***/ 7288: +/***/ ((__unused_webpack_module, exports) => { - // Since http.request treats host as an alias of hostname, - // but the url module interprets host as hostname plus port, - // eliminate the host property to avoid confusion. - if (options.host) { - // Use hostname if set, because it has precedence - if (!options.hostname) { - options.hostname = options.host; - } - delete options.host; - } +"use strict"; - // Complete the URL object when necessary - if (!options.pathname && options.path) { - var searchPos = options.path.indexOf("?"); - if (searchPos < 0) { - options.pathname = options.path; +Object.defineProperty(exports, "__esModule", ({ value: true })); +class WeakableMap { + constructor() { + this.weakMap = new WeakMap(); + this.map = new Map(); } - else { - options.pathname = options.path.substring(0, searchPos); - options.search = options.path.substring(searchPos); + set(key, value) { + if (typeof key === 'object') { + this.weakMap.set(key, value); + } + else { + this.map.set(key, value); + } } - } -}; - + get(key) { + if (typeof key === 'object') { + return this.weakMap.get(key); + } + return this.map.get(key); + } + has(key) { + if (typeof key === 'object') { + return this.weakMap.has(key); + } + return this.map.has(key); + } +} +exports["default"] = WeakableMap; -// Executes the next native request (initial or redirect) -RedirectableRequest.prototype._performRequest = function () { - // Load the native protocol - var protocol = this._options.protocol; - var nativeProtocol = this._options.nativeProtocols[protocol]; - if (!nativeProtocol) { - throw new TypeError("Unsupported protocol " + protocol); - } - // If specified, use the agent corresponding to the protocol - // (HTTP and HTTPS use different types of agents) - if (this._options.agents) { - var scheme = protocol.slice(0, -1); - this._options.agent = this._options.agents[scheme]; - } +/***/ }), - // Create the native request and set up its event handlers - var request = this._currentRequest = - nativeProtocol.request(this._options, this._onNativeResponse); - request._redirectable = this; - for (var event of events) { - request.on(event, eventHandlers[event]); - } +/***/ 34337: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - // RFC7230§5.3.1: When making a request directly to an origin server, […] - // a client MUST send only the absolute path […] as the request-target. - this._currentUrl = /^\//.test(this._options.path) ? - url.format(this._options) : - // When making a request to a proxy, […] - // a client MUST send the target URI in absolute-form […]. - this._options.path; +"use strict"; - // End a redirected request - // (The first request must be ended explicitly with RedirectableRequest#end) - if (this._isRedirect) { - // Write the request entity and end - var i = 0; - var self = this; - var buffers = this._requestBodyBuffers; - (function writeNext(error) { - // Only write if this request has not been redirected yet - // istanbul ignore else - if (request === self._currentRequest) { - // Report any write errors - // istanbul ignore if - if (error) { - self.emit("error", error); +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (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 })); +exports.defaultHandler = void 0; +const is_1 = __nccwpck_require__(7678); +const as_promise_1 = __nccwpck_require__(36056); +const create_rejection_1 = __nccwpck_require__(26457); +const core_1 = __nccwpck_require__(60094); +const deep_freeze_1 = __nccwpck_require__(70285); +const errors = { + RequestError: as_promise_1.RequestError, + CacheError: as_promise_1.CacheError, + ReadError: as_promise_1.ReadError, + HTTPError: as_promise_1.HTTPError, + MaxRedirectsError: as_promise_1.MaxRedirectsError, + TimeoutError: as_promise_1.TimeoutError, + ParseError: as_promise_1.ParseError, + CancelError: as_promise_1.CancelError, + UnsupportedProtocolError: as_promise_1.UnsupportedProtocolError, + UploadError: as_promise_1.UploadError +}; +// The `delay` package weighs 10KB (!) +const delay = async (ms) => new Promise(resolve => { + setTimeout(resolve, ms); +}); +const { normalizeArguments } = core_1.default; +const mergeOptions = (...sources) => { + let mergedOptions; + for (const source of sources) { + mergedOptions = normalizeArguments(undefined, source, mergedOptions); + } + return mergedOptions; +}; +const getPromiseOrStream = (options) => options.isStream ? new core_1.default(undefined, options) : as_promise_1.default(options); +const isGotInstance = (value) => ('defaults' in value && 'options' in value.defaults); +const aliases = [ + 'get', + 'post', + 'put', + 'patch', + 'head', + 'delete' +]; +exports.defaultHandler = (options, next) => next(options); +const callInitHooks = (hooks, options) => { + if (hooks) { + for (const hook of hooks) { + hook(options); } - // Write the next buffer if there are still left - else if (i < buffers.length) { - var buffer = buffers[i++]; - // istanbul ignore else - if (!request.finished) { - request.write(buffer.data, buffer.encoding, writeNext); - } + } +}; +const create = (defaults) => { + // Proxy properties from next handlers + defaults._rawHandlers = defaults.handlers; + defaults.handlers = defaults.handlers.map(fn => ((options, next) => { + // This will be assigned by assigning result + let root; + const result = fn(options, newOptions => { + root = next(newOptions); + return root; + }); + if (result !== root && !options.isStream && root) { + const typedResult = result; + const { then: promiseThen, catch: promiseCatch, finally: promiseFianlly } = typedResult; + Object.setPrototypeOf(typedResult, Object.getPrototypeOf(root)); + Object.defineProperties(typedResult, Object.getOwnPropertyDescriptors(root)); + // These should point to the new promise + // eslint-disable-next-line promise/prefer-await-to-then + typedResult.then = promiseThen; + typedResult.catch = promiseCatch; + typedResult.finally = promiseFianlly; } - // End the request if `end` has been called on us - else if (self._ended) { - request.end(); + return result; + })); + // Got interface + const got = ((url, options = {}, _defaults) => { + var _a, _b; + let iteration = 0; + const iterateHandlers = (newOptions) => { + return defaults.handlers[iteration++](newOptions, iteration === defaults.handlers.length ? getPromiseOrStream : iterateHandlers); + }; + // TODO: Remove this in Got 12. + if (is_1.default.plainObject(url)) { + const mergedOptions = { + ...url, + ...options + }; + core_1.setNonEnumerableProperties([url, options], mergedOptions); + options = mergedOptions; + url = undefined; } - } - }()); - } + try { + // Call `init` hooks + let initHookError; + try { + callInitHooks(defaults.options.hooks.init, options); + callInitHooks((_a = options.hooks) === null || _a === void 0 ? void 0 : _a.init, options); + } + catch (error) { + initHookError = error; + } + // Normalize options & call handlers + const normalizedOptions = normalizeArguments(url, options, _defaults !== null && _defaults !== void 0 ? _defaults : defaults.options); + normalizedOptions[core_1.kIsNormalizedAlready] = true; + if (initHookError) { + throw new as_promise_1.RequestError(initHookError.message, initHookError, normalizedOptions); + } + return iterateHandlers(normalizedOptions); + } + catch (error) { + if (options.isStream) { + throw error; + } + else { + return create_rejection_1.default(error, defaults.options.hooks.beforeError, (_b = options.hooks) === null || _b === void 0 ? void 0 : _b.beforeError); + } + } + }); + got.extend = (...instancesOrOptions) => { + const optionsArray = [defaults.options]; + let handlers = [...defaults._rawHandlers]; + let isMutableDefaults; + for (const value of instancesOrOptions) { + if (isGotInstance(value)) { + optionsArray.push(value.defaults.options); + handlers.push(...value.defaults._rawHandlers); + isMutableDefaults = value.defaults.mutableDefaults; + } + else { + optionsArray.push(value); + if ('handlers' in value) { + handlers.push(...value.handlers); + } + isMutableDefaults = value.mutableDefaults; + } + } + handlers = handlers.filter(handler => handler !== exports.defaultHandler); + if (handlers.length === 0) { + handlers.push(exports.defaultHandler); + } + return create({ + options: mergeOptions(...optionsArray), + handlers, + mutableDefaults: Boolean(isMutableDefaults) + }); + }; + // Pagination + const paginateEach = (async function* (url, options) { + // TODO: Remove this `@ts-expect-error` when upgrading to TypeScript 4. + // Error: Argument of type 'Merge> | undefined' is not assignable to parameter of type 'Options | undefined'. + // @ts-expect-error + let normalizedOptions = normalizeArguments(url, options, defaults.options); + normalizedOptions.resolveBodyOnly = false; + const pagination = normalizedOptions.pagination; + if (!is_1.default.object(pagination)) { + throw new TypeError('`options.pagination` must be implemented'); + } + const all = []; + let { countLimit } = pagination; + let numberOfRequests = 0; + while (numberOfRequests < pagination.requestLimit) { + if (numberOfRequests !== 0) { + // eslint-disable-next-line no-await-in-loop + await delay(pagination.backoff); + } + // @ts-expect-error FIXME! + // TODO: Throw when result is not an instance of Response + // eslint-disable-next-line no-await-in-loop + const result = (await got(undefined, undefined, normalizedOptions)); + // eslint-disable-next-line no-await-in-loop + const parsed = await pagination.transform(result); + const current = []; + for (const item of parsed) { + if (pagination.filter(item, all, current)) { + if (!pagination.shouldContinue(item, all, current)) { + return; + } + yield item; + if (pagination.stackAllItems) { + all.push(item); + } + current.push(item); + if (--countLimit <= 0) { + return; + } + } + } + const optionsToMerge = pagination.paginate(result, all, current); + if (optionsToMerge === false) { + return; + } + if (optionsToMerge === result.request.options) { + normalizedOptions = result.request.options; + } + else if (optionsToMerge !== undefined) { + normalizedOptions = normalizeArguments(undefined, optionsToMerge, normalizedOptions); + } + numberOfRequests++; + } + }); + got.paginate = paginateEach; + got.paginate.all = (async (url, options) => { + const results = []; + for await (const item of paginateEach(url, options)) { + results.push(item); + } + return results; + }); + // For those who like very descriptive names + got.paginate.each = paginateEach; + // Stream API + got.stream = ((url, options) => got(url, { ...options, isStream: true })); + // Shortcuts + for (const method of aliases) { + got[method] = ((url, options) => got(url, { ...options, method })); + got.stream[method] = ((url, options) => { + return got(url, { ...options, method, isStream: true }); + }); + } + Object.assign(got, errors); + Object.defineProperty(got, 'defaults', { + value: defaults.mutableDefaults ? defaults : deep_freeze_1.default(defaults), + writable: defaults.mutableDefaults, + configurable: defaults.mutableDefaults, + enumerable: true + }); + got.mergeOptions = mergeOptions; + return got; }; +exports["default"] = create; +__exportStar(__nccwpck_require__(72613), exports); -// Processes a response from the current native request -RedirectableRequest.prototype._processResponse = function (response) { - // Store the redirected response - var statusCode = response.statusCode; - if (this._options.trackRedirects) { - this._redirects.push({ - url: this._currentUrl, - headers: response.headers, - statusCode: statusCode, - }); - } - // RFC7231§6.4: The 3xx (Redirection) class of status code indicates - // that further action needs to be taken by the user agent in order to - // fulfill the request. If a Location header field is provided, - // the user agent MAY automatically redirect its request to the URI - // referenced by the Location field value, - // even if the specific status code is not understood. +/***/ }), - // If the response is not a redirect; return it as-is - var location = response.headers.location; - if (!location || this._options.followRedirects === false || - statusCode < 300 || statusCode >= 400) { - response.responseUrl = this._currentUrl; - response.redirects = this._redirects; - this.emit("response", response); +/***/ 93061: +/***/ (function(module, exports, __nccwpck_require__) { - // Clean up - this._requestBodyBuffers = []; - return; - } +"use strict"; - // The response is a redirect, so abort the current request - destroyRequest(this._currentRequest); - // Discard the remainder of the response to avoid waiting for data - response.destroy(); +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (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 })); +const url_1 = __nccwpck_require__(57310); +const create_1 = __nccwpck_require__(34337); +const defaults = { + options: { + method: 'GET', + retry: { + limit: 2, + methods: [ + 'GET', + 'PUT', + 'HEAD', + 'DELETE', + 'OPTIONS', + 'TRACE' + ], + statusCodes: [ + 408, + 413, + 429, + 500, + 502, + 503, + 504, + 521, + 522, + 524 + ], + errorCodes: [ + 'ETIMEDOUT', + 'ECONNRESET', + 'EADDRINUSE', + 'ECONNREFUSED', + 'EPIPE', + 'ENOTFOUND', + 'ENETUNREACH', + 'EAI_AGAIN' + ], + maxRetryAfter: undefined, + calculateDelay: ({ computedValue }) => computedValue + }, + timeout: {}, + headers: { + 'user-agent': 'got (https://github.com/sindresorhus/got)' + }, + hooks: { + init: [], + beforeRequest: [], + beforeRedirect: [], + beforeRetry: [], + beforeError: [], + afterResponse: [] + }, + cache: undefined, + dnsCache: undefined, + decompress: true, + throwHttpErrors: true, + followRedirect: true, + isStream: false, + responseType: 'text', + resolveBodyOnly: false, + maxRedirects: 10, + prefixUrl: '', + methodRewriting: true, + ignoreInvalidCookies: false, + context: {}, + // TODO: Set this to `true` when Got 12 gets released + http2: false, + allowGetBody: false, + https: undefined, + pagination: { + transform: (response) => { + if (response.request.options.responseType === 'json') { + return response.body; + } + return JSON.parse(response.body); + }, + paginate: response => { + if (!Reflect.has(response.headers, 'link')) { + return false; + } + const items = response.headers.link.split(','); + let next; + for (const item of items) { + const parsed = item.split(';'); + if (parsed[1].includes('next')) { + next = parsed[0].trimStart().trim(); + next = next.slice(1, -1); + break; + } + } + if (next) { + const options = { + url: new url_1.URL(next) + }; + return options; + } + return false; + }, + filter: () => true, + shouldContinue: () => true, + countLimit: Infinity, + backoff: 0, + requestLimit: 10000, + stackAllItems: true + }, + parseJson: (text) => JSON.parse(text), + stringifyJson: (object) => JSON.stringify(object), + cacheOptions: {} + }, + handlers: [create_1.defaultHandler], + mutableDefaults: false +}; +const got = create_1.default(defaults); +exports["default"] = got; +// For CommonJS default export support +module.exports = got; +module.exports["default"] = got; +module.exports.__esModule = true; // Workaround for TS issue: https://github.com/sindresorhus/got/pull/1267 +__exportStar(__nccwpck_require__(34337), exports); +__exportStar(__nccwpck_require__(36056), exports); - // RFC7231§6.4: A client SHOULD detect and intervene - // in cyclical redirections (i.e., "infinite" redirection loops). - if (++this._redirectCount > this._options.maxRedirects) { - throw new TooManyRedirectsError(); - } - // Store the request headers if applicable - var requestHeaders; - var beforeRedirect = this._options.beforeRedirect; - if (beforeRedirect) { - requestHeaders = Object.assign({ - // The Host header was set by nativeProtocol.request - Host: response.req.getHeader("host"), - }, this._options.headers); - } +/***/ }), - // RFC7231§6.4: Automatic redirection needs to done with - // care for methods not known to be safe, […] - // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change - // the request method from POST to GET for the subsequent request. - var method = this._options.method; - if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || - // RFC7231§6.4.4: The 303 (See Other) status code indicates that - // the server is redirecting the user agent to a different resource […] - // A user agent can perform a retrieval request targeting that URI - // (a GET or HEAD request if using HTTP) […] - (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) { - this._options.method = "GET"; - // Drop a possible entity and headers related to it - this._requestBodyBuffers = []; - removeMatchingHeaders(/^content-/i, this._options.headers); - } +/***/ 72613: +/***/ ((__unused_webpack_module, exports) => { - // Drop the Host header, as the redirect might lead to a different host - var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers); +"use strict"; - // If the redirect is relative, carry over the host of the last request - var currentUrlParts = parseUrl(this._currentUrl); - var currentHost = currentHostHeader || currentUrlParts.host; - var currentUrl = /^\w+:/.test(location) ? this._currentUrl : - url.format(Object.assign(currentUrlParts, { host: currentHost })); +Object.defineProperty(exports, "__esModule", ({ value: true })); - // Create the redirected request - var redirectUrl = resolveUrl(location, currentUrl); - debug("redirecting to", redirectUrl.href); - this._isRedirect = true; - spreadUrlObject(redirectUrl, this._options); - // Drop confidential headers when redirecting to a less secure protocol - // or to a different domain that is not a superdomain - if (redirectUrl.protocol !== currentUrlParts.protocol && - redirectUrl.protocol !== "https:" || - redirectUrl.host !== currentHost && - !isSubdomain(redirectUrl.host, currentHost)) { - removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this._options.headers); - } +/***/ }), - // Evaluate the beforeRedirect callback - if (isFunction(beforeRedirect)) { - var responseDetails = { - headers: response.headers, - statusCode: statusCode, - }; - var requestDetails = { - url: currentUrl, - method: method, - headers: requestHeaders, - }; - beforeRedirect(this._options, responseDetails, requestDetails); - this._sanitizeOptions(this._options); - } +/***/ 70285: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // Perform the redirected request - this._performRequest(); -}; +"use strict"; -// Wraps the key/value object of protocols with redirect functionality -function wrap(protocols) { - // Default settings - var exports = { - maxRedirects: 21, - maxBodyLength: 10 * 1024 * 1024, - }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const is_1 = __nccwpck_require__(7678); +function deepFreeze(object) { + for (const value of Object.values(object)) { + if (is_1.default.plainObject(value) || is_1.default.array(value)) { + deepFreeze(value); + } + } + return Object.freeze(object); +} +exports["default"] = deepFreeze; - // Wrap each protocol - var nativeProtocols = {}; - Object.keys(protocols).forEach(function (scheme) { - var protocol = scheme + ":"; - var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; - var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); - // Executes a request, following redirects - function request(input, options, callback) { - // Parse parameters, ensuring that input is an object - if (isURL(input)) { - input = spreadUrlObject(input); - } - else if (isString(input)) { - input = spreadUrlObject(parseUrl(input)); - } - else { - callback = options; - options = validateUrl(input); - input = { protocol: protocol }; - } - if (isFunction(options)) { - callback = options; - options = null; - } +/***/ }), - // Set defaults - options = Object.assign({ - maxRedirects: exports.maxRedirects, - maxBodyLength: exports.maxBodyLength, - }, input, options); - options.nativeProtocols = nativeProtocols; - if (!isString(options.host) && !isString(options.hostname)) { - options.hostname = "::1"; - } +/***/ 397: +/***/ ((__unused_webpack_module, exports) => { - assert.equal(options.protocol, protocol, "protocol mismatch"); - debug("options", options); - return new RedirectableRequest(options, callback); - } +"use strict"; - // Executes a GET request, following redirects - function get(input, options, callback) { - var wrappedRequest = wrappedProtocol.request(input, options, callback); - wrappedRequest.end(); - return wrappedRequest; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const alreadyWarned = new Set(); +exports["default"] = (message) => { + if (alreadyWarned.has(message)) { + return; } - - // Expose the properties on the wrapped protocol - Object.defineProperties(wrappedProtocol, { - request: { value: request, configurable: true, enumerable: true, writable: true }, - get: { value: get, configurable: true, enumerable: true, writable: true }, + alreadyWarned.add(message); + // @ts-expect-error Missing types. + process.emitWarning(`Got: ${message}`, { + type: 'DeprecationWarning' }); - }); - return exports; -} +}; -function noop() { /* empty */ } -function parseUrl(input) { - var parsed; - // istanbul ignore else - if (useNativeURL) { - parsed = new URL(input); - } - else { - // Ensure the URL is valid and absolute - parsed = validateUrl(url.parse(input)); - if (!isString(parsed.protocol)) { - throw new InvalidUrlError({ input }); - } - } - return parsed; -} +/***/ }), -function resolveUrl(relative, base) { - // istanbul ignore next - return useNativeURL ? new URL(relative, base) : parseUrl(url.resolve(base, relative)); -} +/***/ 4797: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function validateUrl(input) { - if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) { - throw new InvalidUrlError({ input: input.href || input }); - } - if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) { - throw new InvalidUrlError({ input: input.href || input }); - } - return input; -} +"use strict"; -function spreadUrlObject(urlObject, target) { - var spread = target || {}; - for (var key of preservedUrlFields) { - spread[key] = urlObject[key]; - } - // Fix IPv6 hostname - if (spread.hostname.startsWith("[")) { - spread.hostname = spread.hostname.slice(1, -1); - } - // Ensure port is a number - if (spread.port !== "") { - spread.port = Number(spread.port); - } - // Concatenate path - spread.path = spread.search ? spread.pathname + spread.search : spread.pathname; +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.GraphQLError = void 0; +exports.formatError = formatError; +exports.printError = printError; - return spread; -} +var _isObjectLike = __nccwpck_require__(95865); -function removeMatchingHeaders(regex, headers) { - var lastValue; - for (var header in headers) { - if (regex.test(header)) { - lastValue = headers[header]; - delete headers[header]; - } - } - return (lastValue === null || typeof lastValue === "undefined") ? - undefined : String(lastValue).trim(); -} +var _location = __nccwpck_require__(61922); -function createErrorType(code, message, baseClass) { - // Create constructor - function CustomError(properties) { - // istanbul ignore else - if (isFunction(Error.captureStackTrace)) { - Error.captureStackTrace(this, this.constructor); - } - Object.assign(this, properties || {}); - this.code = code; - this.message = this.cause ? message + ": " + this.cause.message : message; - } +var _printLocation = __nccwpck_require__(35250); - // Attach constructor and set default properties - CustomError.prototype = new (baseClass || Error)(); - Object.defineProperties(CustomError.prototype, { - constructor: { - value: CustomError, - enumerable: false, - }, - name: { - value: "Error [" + code + "]", - enumerable: false, - }, - }); - return CustomError; -} +function toNormalizedOptions(args) { + const firstArg = args[0]; -function destroyRequest(request, error) { - for (var event of events) { - request.removeListener(event, eventHandlers[event]); + if (firstArg == null || 'kind' in firstArg || 'length' in firstArg) { + return { + nodes: firstArg, + source: args[1], + positions: args[2], + path: args[3], + originalError: args[4], + extensions: args[5], + }; } - request.on("error", noop); - request.destroy(error); -} -function isSubdomain(subdomain, domain) { - assert(isString(subdomain) && isString(domain)); - var dot = subdomain.length - domain.length - 1; - return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain); + return firstArg; } +/** + * A GraphQLError describes an Error found during the parse, validate, or + * execute phases of performing a GraphQL operation. In addition to a message + * and stack trace, it also includes information about the locations in a + * GraphQL document and/or execution result that correspond to the Error. + */ -function isString(value) { - return typeof value === "string" || value instanceof String; -} +class GraphQLError extends Error { + /** + * An array of `{ line, column }` locations within the source GraphQL document + * which correspond to this error. + * + * Errors during validation often contain multiple locations, for example to + * point out two things with the same name. Errors during execution include a + * single location, the field which produced the error. + * + * Enumerable, and appears in the result of JSON.stringify(). + */ -function isFunction(value) { - return typeof value === "function"; -} + /** + * An array describing the JSON-path into the execution response which + * corresponds to this error. Only included for errors during execution. + * + * Enumerable, and appears in the result of JSON.stringify(). + */ -function isBuffer(value) { - return typeof value === "object" && ("length" in value); -} + /** + * An array of GraphQL AST Nodes corresponding to this error. + */ -function isURL(value) { - return URL && value instanceof URL; -} + /** + * The source GraphQL document for the first location of this error. + * + * Note that if this Error represents more than one node, the source may not + * represent nodes after the first node. + */ -// Exports -module.exports = wrap({ http: http, https: https }); -module.exports.wrap = wrap; + /** + * An array of character offsets within the source GraphQL document + * which correspond to this error. + */ + /** + * The original error thrown from a field resolver during execution. + */ -/***/ }), + /** + * Extension fields to add to the formatted error. + */ -/***/ 47568: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** + * @deprecated Please use the `GraphQLErrorOptions` constructor overload instead. + */ + constructor(message, ...rawArgs) { + var _this$nodes, _nodeLocations$, _ref; -module.exports = ForeverAgent -ForeverAgent.SSL = ForeverAgentSSL + const { nodes, source, positions, path, originalError, extensions } = + toNormalizedOptions(rawArgs); + super(message); + this.name = 'GraphQLError'; + this.path = path !== null && path !== void 0 ? path : undefined; + this.originalError = + originalError !== null && originalError !== void 0 + ? originalError + : undefined; // Compute list of blame nodes. -var util = __nccwpck_require__(73837) - , Agent = (__nccwpck_require__(13685).Agent) - , net = __nccwpck_require__(41808) - , tls = __nccwpck_require__(24404) - , AgentSSL = (__nccwpck_require__(95687).Agent) - -function getConnectionName(host, port) { - var name = '' - if (typeof host === 'string') { - name = host + ':' + port - } else { - // For node.js v012.0 and iojs-v1.5.1, host is an object. And any existing localAddress is part of the connection name. - name = host.host + ':' + host.port + ':' + (host.localAddress ? (host.localAddress + ':') : ':') - } - return name -} + this.nodes = undefinedIfEmpty( + Array.isArray(nodes) ? nodes : nodes ? [nodes] : undefined, + ); + const nodeLocations = undefinedIfEmpty( + (_this$nodes = this.nodes) === null || _this$nodes === void 0 + ? void 0 + : _this$nodes.map((node) => node.loc).filter((loc) => loc != null), + ); // Compute locations in the source for the given nodes/positions. -function ForeverAgent(options) { - var self = this - self.options = options || {} - self.requests = {} - self.sockets = {} - self.freeSockets = {} - self.maxSockets = self.options.maxSockets || Agent.defaultMaxSockets - self.minSockets = self.options.minSockets || ForeverAgent.defaultMinSockets - self.on('free', function(socket, host, port) { - var name = getConnectionName(host, port) + this.source = + source !== null && source !== void 0 + ? source + : nodeLocations === null || nodeLocations === void 0 + ? void 0 + : (_nodeLocations$ = nodeLocations[0]) === null || + _nodeLocations$ === void 0 + ? void 0 + : _nodeLocations$.source; + this.positions = + positions !== null && positions !== void 0 + ? positions + : nodeLocations === null || nodeLocations === void 0 + ? void 0 + : nodeLocations.map((loc) => loc.start); + this.locations = + positions && source + ? positions.map((pos) => (0, _location.getLocation)(source, pos)) + : nodeLocations === null || nodeLocations === void 0 + ? void 0 + : nodeLocations.map((loc) => + (0, _location.getLocation)(loc.source, loc.start), + ); + const originalExtensions = (0, _isObjectLike.isObjectLike)( + originalError === null || originalError === void 0 + ? void 0 + : originalError.extensions, + ) + ? originalError === null || originalError === void 0 + ? void 0 + : originalError.extensions + : undefined; + this.extensions = + (_ref = + extensions !== null && extensions !== void 0 + ? extensions + : originalExtensions) !== null && _ref !== void 0 + ? _ref + : Object.create(null); // Only properties prescribed by the spec should be enumerable. + // Keep the rest as non-enumerable. - if (self.requests[name] && self.requests[name].length) { - self.requests[name].shift().onSocket(socket) - } else if (self.sockets[name].length < self.minSockets) { - if (!self.freeSockets[name]) self.freeSockets[name] = [] - self.freeSockets[name].push(socket) - - // if an error happens while we don't use the socket anyway, meh, throw the socket away - var onIdleError = function() { - socket.destroy() - } - socket._onIdleError = onIdleError - socket.on('error', onIdleError) + Object.defineProperties(this, { + message: { + writable: true, + enumerable: true, + }, + name: { + enumerable: false, + }, + nodes: { + enumerable: false, + }, + source: { + enumerable: false, + }, + positions: { + enumerable: false, + }, + originalError: { + enumerable: false, + }, + }); // Include (non-enumerable) stack trace. + + /* c8 ignore start */ + // FIXME: https://github.com/graphql/graphql-js/issues/2317 + + if ( + originalError !== null && + originalError !== void 0 && + originalError.stack + ) { + Object.defineProperty(this, 'stack', { + value: originalError.stack, + writable: true, + configurable: true, + }); + } else if (Error.captureStackTrace) { + Error.captureStackTrace(this, GraphQLError); } else { - // If there are no pending requests just destroy the - // socket and it will get removed from the pool. This - // gets us out of timeout issues and allows us to - // default to Connection:keep-alive. - socket.destroy() + Object.defineProperty(this, 'stack', { + value: Error().stack, + writable: true, + configurable: true, + }); } - }) + /* c8 ignore stop */ + } -} -util.inherits(ForeverAgent, Agent) + get [Symbol.toStringTag]() { + return 'GraphQLError'; + } -ForeverAgent.defaultMinSockets = 5 + toString() { + let output = this.message; + if (this.nodes) { + for (const node of this.nodes) { + if (node.loc) { + output += '\n\n' + (0, _printLocation.printLocation)(node.loc); + } + } + } else if (this.source && this.locations) { + for (const location of this.locations) { + output += + '\n\n' + + (0, _printLocation.printSourceLocation)(this.source, location); + } + } -ForeverAgent.prototype.createConnection = net.createConnection -ForeverAgent.prototype.addRequestNoreuse = Agent.prototype.addRequest -ForeverAgent.prototype.addRequest = function(req, host, port) { - var name = getConnectionName(host, port) - - if (typeof host !== 'string') { - var options = host - port = options.port - host = options.host + return output; } - if (this.freeSockets[name] && this.freeSockets[name].length > 0 && !req.useChunkedEncodingByDefault) { - var idleSocket = this.freeSockets[name].pop() - idleSocket.removeListener('error', idleSocket._onIdleError) - delete idleSocket._onIdleError - req._reusedSocket = true - req.onSocket(idleSocket) - } else { - this.addRequestNoreuse(req, host, port) - } -} + toJSON() { + const formattedError = { + message: this.message, + }; -ForeverAgent.prototype.removeSocket = function(s, name, host, port) { - if (this.sockets[name]) { - var index = this.sockets[name].indexOf(s) - if (index !== -1) { - this.sockets[name].splice(index, 1) + if (this.locations != null) { + formattedError.locations = this.locations; } - } else if (this.sockets[name] && this.sockets[name].length === 0) { - // don't leak - delete this.sockets[name] - delete this.requests[name] - } - - if (this.freeSockets[name]) { - var index = this.freeSockets[name].indexOf(s) - if (index !== -1) { - this.freeSockets[name].splice(index, 1) - if (this.freeSockets[name].length === 0) { - delete this.freeSockets[name] - } + + if (this.path != null) { + formattedError.path = this.path; } - } - if (this.requests[name] && this.requests[name].length) { - // If we have pending requests and a socket gets closed a new one - // needs to be created to take over in the pool for the one that closed. - this.createSocket(name, host, port).emit('free') - } -} + if (this.extensions != null && Object.keys(this.extensions).length > 0) { + formattedError.extensions = this.extensions; + } -function ForeverAgentSSL (options) { - ForeverAgent.call(this, options) + return formattedError; + } } -util.inherits(ForeverAgentSSL, ForeverAgent) -ForeverAgentSSL.prototype.createConnection = createConnectionSSL -ForeverAgentSSL.prototype.addRequestNoreuse = AgentSSL.prototype.addRequest - -function createConnectionSSL (port, host, options) { - if (typeof port === 'object') { - options = port; - } else if (typeof host === 'object') { - options = host; - } else if (typeof options === 'object') { - options = options; - } else { - options = {}; - } +exports.GraphQLError = GraphQLError; - if (typeof port === 'number') { - options.port = port; - } +function undefinedIfEmpty(array) { + return array === undefined || array.length === 0 ? undefined : array; +} +/** + * See: https://spec.graphql.org/draft/#sec-Errors + */ - if (typeof host === 'string') { - options.host = host; - } +/** + * Prints a GraphQLError to a string, representing useful location information + * about the error's position in the source. + * + * @deprecated Please use `error.toString` instead. Will be removed in v17 + */ +function printError(error) { + return error.toString(); +} +/** + * Given a GraphQLError, format it according to the rules described by the + * Response Format, Errors section of the GraphQL Specification. + * + * @deprecated Please use `error.toJSON` instead. Will be removed in v17 + */ - return tls.connect(options); +function formatError(error) { + return error.toJSON(); } /***/ }), -/***/ 27714: +/***/ 50578: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -const MiniPass = __nccwpck_require__(41077) -const EE = (__nccwpck_require__(82361).EventEmitter) -const fs = __nccwpck_require__(57147) - -let writev = fs.writev -/* istanbul ignore next */ -if (!writev) { - // This entire block can be removed if support for earlier than Node.js - // 12.9.0 is not needed. - const binding = process.binding('fs') - const FSReqWrap = binding.FSReqWrap || binding.FSReqCallback - - writev = (fd, iovec, pos, cb) => { - const done = (er, bw) => cb(er, bw, iovec) - const req = new FSReqWrap() - req.oncomplete = done - binding.writeBuffers(fd, iovec, pos, req) - } -} - -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) +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +Object.defineProperty(exports, "GraphQLError", ({ + enumerable: true, + get: function () { + return _GraphQLError.GraphQLError; + }, +})); +Object.defineProperty(exports, "formatError", ({ + enumerable: true, + get: function () { + return _GraphQLError.formatError; + }, +})); +Object.defineProperty(exports, "locatedError", ({ + enumerable: true, + get: function () { + return _locatedError.locatedError; + }, +})); +Object.defineProperty(exports, "printError", ({ + enumerable: true, + get: function () { + return _GraphQLError.printError; + }, +})); +Object.defineProperty(exports, "syntaxError", ({ + enumerable: true, + get: function () { + return _syntaxError.syntaxError; + }, +})); - this.readable = true - this.writable = false +var _GraphQLError = __nccwpck_require__(4797); - if (typeof path !== 'string') - throw new TypeError('path must be a string') +var _syntaxError = __nccwpck_require__(52295); - 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 +var _locatedError = __nccwpck_require__(16842); - if (typeof this[_fd] === 'number') - this[_read]() - else - this[_open]() - } - get fd () { return this[_fd] } - get path () { return this[_path] } +/***/ }), - write () { - throw new TypeError('this is a readable stream') - } +/***/ 16842: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - end () { - throw new TypeError('this is a readable stream') - } +"use strict"; - [_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]() - } - } +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.locatedError = locatedError; - [_makeBuf] () { - return Buffer.allocUnsafe(Math.min(this[_readSize], this[_remain])) - } +var _toError = __nccwpck_require__(15472); - [_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, buf) => - this[_onread](er, br, buf)) - } - } +var _GraphQLError = __nccwpck_require__(4797); - [_onread] (er, br, buf) { - this[_reading] = false - if (er) - this[_onerror](er) - else if (this[_handleChunk](br, buf)) - this[_read]() - } +/** + * Given an arbitrary value, presumably thrown while attempting to execute a + * GraphQL operation, produce a new GraphQLError aware of the location in the + * document responsible for the original Error. + */ +function locatedError(rawOriginalError, nodes, path) { + var _nodes; - [_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')) - } - } + const originalError = (0, _toError.toError)(rawOriginalError); // Note: this uses a brand-check to support GraphQL errors originating from other contexts. - [_onerror] (er) { - this[_reading] = true - this[_close]() - this.emit('error', er) + if (isLocatedGraphQLError(originalError)) { + return originalError; } - [_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) + return new _GraphQLError.GraphQLError(originalError.message, { + nodes: + (_nodes = originalError.nodes) !== null && _nodes !== void 0 + ? _nodes + : nodes, + source: originalError.source, + positions: originalError.positions, + path, + originalError, + }); +} - if (br === 0 || this[_remain] <= 0) { - ret = false - this[_close]() - super.end() - } +function isLocatedGraphQLError(error) { + return Array.isArray(error.path); +} - return ret - } - emit (ev, data) { - switch (ev) { - case 'prefinish': - case 'finish': - break +/***/ }), - case 'drain': - if (typeof this[_fd] === 'number') - this[_read]() - break +/***/ 52295: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - case 'error': - if (this[_errored]) - return - this[_errored] = true - return super.emit(ev, data) +"use strict"; - default: - return super.emit(ev, 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]() - } - } +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.syntaxError = syntaxError; - [_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]() - } - } +var _GraphQLError = __nccwpck_require__(4797); - [_close] () { - if (this[_autoClose] && typeof this[_fd] === 'number') { - const fd = this[_fd] - this[_fd] = null - fs.closeSync(fd) - this.emit('close') - } - } +/** + * Produces a GraphQLError representing a syntax error, containing useful + * descriptive information about the syntax error's position in the source. + */ +function syntaxError(source, position, description) { + return new _GraphQLError.GraphQLError(`Syntax Error: ${description}`, { + source, + positions: [position], + }); } -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 - - // 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 - if (this[_fd] === null) - this[_open]() - } +/***/ }), - emit (ev, data) { - if (ev === 'error') { - if (this[_errored]) - return - this[_errored] = true - } - return super.emit(ev, data) - } +/***/ 49942: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; - get fd () { return this[_fd] } - get path () { return this[_path] } - [_onerror] (er) { - this[_close]() - this[_writing] = true - this.emit('error', er) - } +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.collectFields = collectFields; +exports.collectSubfields = collectSubfields; - [_open] () { - fs.open(this[_path], this[_flags], this[_mode], - (er, fd) => this[_onopen](er, fd)) - } +var _kinds = __nccwpck_require__(11927); - [_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) - this[_flush]() - } - } +var _definition = __nccwpck_require__(32150); - end (buf, enc) { - if (buf) - this.write(buf, enc) +var _directives = __nccwpck_require__(83614); - this[_ended] = true +var _typeFromAST = __nccwpck_require__(27664); - // synthetic after-write logic, where drain/finish live - if (!this[_writing] && !this[_queue].length && - typeof this[_fd] === 'number') - this[_onwrite](null, 0) - return this - } +var _values = __nccwpck_require__(94834); - write (buf, enc) { - if (typeof buf === 'string') - buf = Buffer.from(buf, enc) +/** + * Given a selectionSet, collects all of the fields and returns them. + * + * CollectFields requires the "runtime type" of an object. For a field that + * returns an Interface or Union type, the "runtime type" will be the actual + * object type returned by that field. + * + * @internal + */ +function collectFields( + schema, + fragments, + variableValues, + runtimeType, + selectionSet, +) { + const fields = new Map(); + collectFieldsImpl( + schema, + fragments, + variableValues, + runtimeType, + selectionSet, + fields, + new Set(), + ); + return fields; +} +/** + * Given an array of field nodes, collects all of the subfields of the passed + * in fields, and returns them at the end. + * + * CollectSubFields requires the "return type" of an object. For a field that + * returns an Interface or Union type, the "return type" will be the actual + * object type returned by that field. + * + * @internal + */ - if (this[_ended]) { - this.emit('error', new Error('write() after end()')) - return false - } +function collectSubfields( + schema, + fragments, + variableValues, + returnType, + fieldNodes, +) { + const subFieldNodes = new Map(); + const visitedFragmentNames = new Set(); - if (this[_fd] === null || this[_writing] || this[_queue].length) { - this[_queue].push(buf) - this[_needDrain] = true - return false + for (const node of fieldNodes) { + if (node.selectionSet) { + collectFieldsImpl( + schema, + fragments, + variableValues, + returnType, + node.selectionSet, + subFieldNodes, + visitedFragmentNames, + ); } - - this[_writing] = true - this[_write](buf) - return true } - [_write] (buf) { - fs.write(this[_fd], buf, 0, buf.length, this[_pos], (er, bw) => - this[_onwrite](er, bw)) - } + return subFieldNodes; +} - [_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 collectFieldsImpl( + schema, + fragments, + variableValues, + runtimeType, + selectionSet, + fields, + visitedFragmentNames, +) { + for (const selection of selectionSet.selections) { + switch (selection.kind) { + case _kinds.Kind.FIELD: { + if (!shouldIncludeNode(variableValues, selection)) { + continue; + } - if (this[_ended] && !this[_finished]) { - this[_finished] = true - this[_close]() - this.emit('finish') - } else if (this[_needDrain]) { - this[_needDrain] = false - this.emit('drain') + const name = getFieldEntryKey(selection); + const fieldList = fields.get(name); + + if (fieldList !== undefined) { + fieldList.push(selection); + } else { + fields.set(name, [selection]); } - } - } - } - [_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)) - } - } + break; + } - [_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')) - } - } -} + case _kinds.Kind.INLINE_FRAGMENT: { + if ( + !shouldIncludeNode(variableValues, selection) || + !doesFragmentConditionMatch(schema, selection, runtimeType) + ) { + continue; + } -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 + collectFieldsImpl( + schema, + fragments, + variableValues, + runtimeType, + selection.selectionSet, + fields, + visitedFragmentNames, + ); + break; } - } else - fd = fs.openSync(this[_path], this[_flags], this[_mode]) - this[_onopen](null, fd) - } + case _kinds.Kind.FRAGMENT_SPREAD: { + const fragName = selection.name.value; - [_close] () { - if (this[_autoClose] && typeof this[_fd] === 'number') { - const fd = this[_fd] - this[_fd] = null - fs.closeSync(fd) - this.emit('close') - } - } + if ( + visitedFragmentNames.has(fragName) || + !shouldIncludeNode(variableValues, selection) + ) { + continue; + } - [_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 (_) {} + visitedFragmentNames.add(fragName); + const fragment = fragments[fragName]; + + if ( + !fragment || + !doesFragmentConditionMatch(schema, fragment, runtimeType) + ) { + continue; + } + + collectFieldsImpl( + schema, + fragments, + variableValues, + runtimeType, + fragment.selectionSet, + fields, + visitedFragmentNames, + ); + break; + } } } } +/** + * Determines if a field should be included based on the `@include` and `@skip` + * directives, where `@skip` has higher precedence than `@include`. + */ -exports.ReadStream = ReadStream -exports.ReadStreamSync = ReadStreamSync - -exports.WriteStream = WriteStream -exports.WriteStreamSync = WriteStreamSync - - -/***/ }), - -/***/ 46863: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function shouldIncludeNode(variableValues, node) { + const skip = (0, _values.getDirectiveValues)( + _directives.GraphQLSkipDirective, + node, + variableValues, + ); -module.exports = realpath -realpath.realpath = realpath -realpath.sync = realpathSync -realpath.realpathSync = realpathSync -realpath.monkeypatch = monkeypatch -realpath.unmonkeypatch = unmonkeypatch + if ((skip === null || skip === void 0 ? void 0 : skip.if) === true) { + return false; + } -var fs = __nccwpck_require__(57147) -var origRealpath = fs.realpath -var origRealpathSync = fs.realpathSync + const include = (0, _values.getDirectiveValues)( + _directives.GraphQLIncludeDirective, + node, + variableValues, + ); -var version = process.version -var ok = /^v[0-5]\./.test(version) -var old = __nccwpck_require__(71734) + if ( + (include === null || include === void 0 ? void 0 : include.if) === false + ) { + return false; + } -function newError (er) { - return er && er.syscall === 'realpath' && ( - er.code === 'ELOOP' || - er.code === 'ENOMEM' || - er.code === 'ENAMETOOLONG' - ) + return true; } +/** + * Determines if a fragment is applicable to the given type. + */ -function realpath (p, cache, cb) { - if (ok) { - return origRealpath(p, cache, cb) - } +function doesFragmentConditionMatch(schema, fragment, type) { + const typeConditionNode = fragment.typeCondition; - if (typeof cache === 'function') { - cb = cache - cache = null + if (!typeConditionNode) { + return true; } - origRealpath(p, cache, function (er, result) { - if (newError(er)) { - old.realpath(p, cache, cb) - } else { - cb(er, result) - } - }) -} -function realpathSync (p, cache) { - if (ok) { - return origRealpathSync(p, cache) + const conditionalType = (0, _typeFromAST.typeFromAST)( + schema, + typeConditionNode, + ); + + if (conditionalType === type) { + return true; } - try { - return origRealpathSync(p, cache) - } catch (er) { - if (newError(er)) { - return old.realpathSync(p, cache) - } else { - throw er - } + if ((0, _definition.isAbstractType)(conditionalType)) { + return schema.isSubType(conditionalType, type); } -} -function monkeypatch () { - fs.realpath = realpath - fs.realpathSync = realpathSync + return false; } +/** + * Implements the logic to compute the key of a given field's entry + */ -function unmonkeypatch () { - fs.realpath = origRealpath - fs.realpathSync = origRealpathSync +function getFieldEntryKey(node) { + return node.alias ? node.alias.value : node.name.value; } /***/ }), -/***/ 71734: +/***/ 83677: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var pathModule = __nccwpck_require__(71017); -var isWindows = process.platform === 'win32'; -var fs = __nccwpck_require__(57147); - -// JavaScript implementation of realpath, ported from node pre-v6 +"use strict"; -var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); -function rethrow() { - // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and - // is fairly slow to generate. - var callback; - if (DEBUG) { - var backtrace = new Error; - callback = debugCallback; - } else - callback = missingCallback; +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.assertValidExecutionArguments = assertValidExecutionArguments; +exports.buildExecutionContext = buildExecutionContext; +exports.buildResolveInfo = buildResolveInfo; +exports.defaultTypeResolver = exports.defaultFieldResolver = void 0; +exports.execute = execute; +exports.executeSync = executeSync; +exports.getFieldDef = getFieldDef; - return callback; +var _devAssert = __nccwpck_require__(46514); - function debugCallback(err) { - if (err) { - backtrace.message = err.message; - err = backtrace; - missingCallback(err); - } - } +var _inspect = __nccwpck_require__(10102); - function missingCallback(err) { - if (err) { - if (process.throwDeprecation) - throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs - else if (!process.noDeprecation) { - var msg = 'fs: missing callback ' + (err.stack || err.message); - if (process.traceDeprecation) - console.trace(msg); - else - console.error(msg); - } - } - } -} +var _invariant = __nccwpck_require__(28847); -function maybeCallback(cb) { - return typeof cb === 'function' ? cb : rethrow(); -} +var _isIterableObject = __nccwpck_require__(81258); -var normalize = pathModule.normalize; +var _isObjectLike = __nccwpck_require__(95865); -// Regexp that finds the next partion of a (partial) path -// result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] -if (isWindows) { - var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; -} else { - var nextPartRe = /(.*?)(?:[\/]+|$)/g; -} +var _isPromise = __nccwpck_require__(93910); -// Regex to find the device root, including trailing slash. E.g. 'c:\\'. -if (isWindows) { - var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; -} else { - var splitRootRe = /^[\/]*/; -} +var _memoize = __nccwpck_require__(64217); -exports.realpathSync = function realpathSync(p, cache) { - // make p is absolute - p = pathModule.resolve(p); +var _Path = __nccwpck_require__(11262); - if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { - return cache[p]; - } +var _promiseForObject = __nccwpck_require__(46804); - var original = p, - seenLinks = {}, - knownHard = {}; +var _promiseReduce = __nccwpck_require__(63925); - // current character position in p - var pos; - // the partial path so far, including a trailing slash if any - var current; - // the partial path without a trailing slash (except when pointing at a root) - var base; - // the partial path scanned in the previous round, with slash - var previous; +var _GraphQLError = __nccwpck_require__(4797); - start(); +var _locatedError = __nccwpck_require__(16842); - function start() { - // Skip over roots - var m = splitRootRe.exec(p); - pos = m[0].length; - current = m[0]; - base = m[0]; - previous = ''; +var _ast = __nccwpck_require__(45494); - // On windows, check that the root exists. On unix there is no need. - if (isWindows && !knownHard[base]) { - fs.lstatSync(base); - knownHard[base] = true; - } - } +var _kinds = __nccwpck_require__(11927); - // walk down the path, swapping out linked pathparts for their real - // values - // NB: p.length changes. - while (pos < p.length) { - // find the next part - nextPartRe.lastIndex = pos; - var result = nextPartRe.exec(p); - previous = current; - current += result[0]; - base = previous + result[1]; - pos = nextPartRe.lastIndex; +var _definition = __nccwpck_require__(32150); - // continue if not a symlink - if (knownHard[base] || (cache && cache[base] === base)) { - continue; - } +var _introspection = __nccwpck_require__(28344); - var resolvedLink; - if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { - // some known symbolic link. no need to stat again. - resolvedLink = cache[base]; - } else { - var stat = fs.lstatSync(base); - if (!stat.isSymbolicLink()) { - knownHard[base] = true; - if (cache) cache[base] = base; - continue; - } +var _validate = __nccwpck_require__(22430); - // read the link if it wasn't read before - // dev/ino always return 0 on windows, so skip the check. - var linkTarget = null; - if (!isWindows) { - var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); - if (seenLinks.hasOwnProperty(id)) { - linkTarget = seenLinks[id]; - } - } - if (linkTarget === null) { - fs.statSync(base); - linkTarget = fs.readlinkSync(base); - } - resolvedLink = pathModule.resolve(previous, linkTarget); - // track this, if given a cache. - if (cache) cache[base] = resolvedLink; - if (!isWindows) seenLinks[id] = linkTarget; - } +var _collectFields = __nccwpck_require__(49942); - // resolve the link, then start over - p = pathModule.resolve(resolvedLink, p.slice(pos)); - start(); - } +var _values = __nccwpck_require__(94834); - if (cache) cache[original] = p; +/** + * A memoized collection of relevant subfields with regard to the return + * type. Memoizing ensures the subfields are not repeatedly calculated, which + * saves overhead when resolving lists of values. + */ +const collectSubfields = (0, _memoize.memoize3)( + (exeContext, returnType, fieldNodes) => + (0, _collectFields.collectSubfields)( + exeContext.schema, + exeContext.fragments, + exeContext.variableValues, + returnType, + fieldNodes, + ), +); +/** + * Terminology + * + * "Definitions" are the generic name for top-level statements in the document. + * Examples of this include: + * 1) Operations (such as a query) + * 2) Fragments + * + * "Operations" are a generic name for requests in the document. + * Examples of this include: + * 1) query, + * 2) mutation + * + * "Selections" are the definitions that can appear legally and at + * single level of the query. These include: + * 1) field references e.g `a` + * 2) fragment "spreads" e.g. `...c` + * 3) inline fragment "spreads" e.g. `...on Type { a }` + */ - return p; -}; +/** + * Data that must be available at all points during query execution. + * + * Namely, schema of the type system that is currently executing, + * and the fragments defined in the query document + */ +/** + * Implements the "Executing requests" section of the GraphQL specification. + * + * Returns either a synchronous ExecutionResult (if all encountered resolvers + * are synchronous), or a Promise of an ExecutionResult that will eventually be + * resolved and never rejected. + * + * If the arguments to this function do not result in a legal execution context, + * a GraphQLError will be thrown immediately explaining the invalid input. + */ +function execute(args) { + // Temporary for v15 to v16 migration. Remove in v17 + arguments.length < 2 || + (0, _devAssert.devAssert)( + false, + 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.', + ); + const { schema, document, variableValues, rootValue } = args; // If arguments are missing or incorrect, throw an error. -exports.realpath = function realpath(p, cache, cb) { - if (typeof cb !== 'function') { - cb = maybeCallback(cache); - cache = null; - } + assertValidExecutionArguments(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments, + // a "Response" with only errors is returned. - // make p is absolute - p = pathModule.resolve(p); + const exeContext = buildExecutionContext(args); // Return early errors if execution context failed. - if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { - return process.nextTick(cb.bind(null, null, cache[p])); - } + if (!('schema' in exeContext)) { + return { + errors: exeContext, + }; + } // Return a Promise that will eventually resolve to the data described by + // The "Response" section of the GraphQL specification. + // + // If errors are encountered while executing a GraphQL field, only that + // field and its descendants will be omitted, and sibling fields will still + // be executed. An execution which encounters errors will still result in a + // resolved Promise. + // + // Errors from sub-fields of a NonNull type may propagate to the top level, + // at which point we still log the error and null the parent field, which + // in this case is the entire response. - var original = p, - seenLinks = {}, - knownHard = {}; + try { + const { operation } = exeContext; + const result = executeOperation(exeContext, operation, rootValue); - // current character position in p - var pos; - // the partial path so far, including a trailing slash if any - var current; - // the partial path without a trailing slash (except when pointing at a root) - var base; - // the partial path scanned in the previous round, with slash - var previous; + if ((0, _isPromise.isPromise)(result)) { + return result.then( + (data) => buildResponse(data, exeContext.errors), + (error) => { + exeContext.errors.push(error); + return buildResponse(null, exeContext.errors); + }, + ); + } - start(); + return buildResponse(result, exeContext.errors); + } catch (error) { + exeContext.errors.push(error); + return buildResponse(null, exeContext.errors); + } +} +/** + * Also implements the "Executing requests" section of the GraphQL specification. + * However, it guarantees to complete synchronously (or throw an error) assuming + * that all field resolvers are also synchronous. + */ - function start() { - // Skip over roots - var m = splitRootRe.exec(p); - pos = m[0].length; - current = m[0]; - base = m[0]; - previous = ''; +function executeSync(args) { + const result = execute(args); // Assert that the execution was synchronous. - // On windows, check that the root exists. On unix there is no need. - if (isWindows && !knownHard[base]) { - fs.lstat(base, function(err) { - if (err) return cb(err); - knownHard[base] = true; - LOOP(); - }); - } else { - process.nextTick(LOOP); - } + if ((0, _isPromise.isPromise)(result)) { + throw new Error('GraphQL execution failed to complete synchronously.'); } - // walk down the path, swapping out linked pathparts for their real - // values - function LOOP() { - // stop if scanned past end of path - if (pos >= p.length) { - if (cache) cache[original] = p; - return cb(null, p); - } + return result; +} +/** + * Given a completed execution context and data, build the `{ errors, data }` + * response defined by the "Response" section of the GraphQL specification. + */ - // find the next part - nextPartRe.lastIndex = pos; - var result = nextPartRe.exec(p); - previous = current; - current += result[0]; - base = previous + result[1]; - pos = nextPartRe.lastIndex; +function buildResponse(data, errors) { + return errors.length === 0 + ? { + data, + } + : { + errors, + data, + }; +} +/** + * Essential assertions before executing to provide developer feedback for + * improper use of the GraphQL library. + * + * @internal + */ - // continue if not a symlink - if (knownHard[base] || (cache && cache[base] === base)) { - return process.nextTick(LOOP); - } +function assertValidExecutionArguments(schema, document, rawVariableValues) { + document || (0, _devAssert.devAssert)(false, 'Must provide document.'); // If the schema used for execution is invalid, throw an error. - if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { - // known symbolic link. no need to stat again. - return gotResolvedLink(cache[base]); - } + (0, _validate.assertValidSchema)(schema); // Variables, if provided, must be an object. - return fs.lstat(base, gotStat); - } + rawVariableValues == null || + (0, _isObjectLike.isObjectLike)(rawVariableValues) || + (0, _devAssert.devAssert)( + false, + 'Variables must be provided as an Object where each property is a variable value. Perhaps look to see if an unparsed JSON string was provided.', + ); +} +/** + * Constructs a ExecutionContext object from the arguments passed to + * execute, which we will pass throughout the other execution methods. + * + * Throws a GraphQLError if a valid execution context cannot be created. + * + * @internal + */ - function gotStat(err, stat) { - if (err) return cb(err); +function buildExecutionContext(args) { + var _definition$name, _operation$variableDe, _options$maxCoercionE; - // if not a symlink, skip to the next path part - if (!stat.isSymbolicLink()) { - knownHard[base] = true; - if (cache) cache[base] = base; - return process.nextTick(LOOP); - } + const { + schema, + document, + rootValue, + contextValue, + variableValues: rawVariableValues, + operationName, + fieldResolver, + typeResolver, + subscribeFieldResolver, + options, + } = args; + let operation; + const fragments = Object.create(null); - // stat & read the link if not read before - // call gotTarget as soon as the link target is known - // dev/ino always return 0 on windows, so skip the check. - if (!isWindows) { - var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); - if (seenLinks.hasOwnProperty(id)) { - return gotTarget(null, seenLinks[id], base); - } - } - fs.stat(base, function(err) { - if (err) return cb(err); + for (const definition of document.definitions) { + switch (definition.kind) { + case _kinds.Kind.OPERATION_DEFINITION: + if (operationName == null) { + if (operation !== undefined) { + return [ + new _GraphQLError.GraphQLError( + 'Must provide operation name if query contains multiple operations.', + ), + ]; + } - fs.readlink(base, function(err, target) { - if (!isWindows) seenLinks[id] = target; - gotTarget(err, target); - }); - }); - } + operation = definition; + } else if ( + ((_definition$name = definition.name) === null || + _definition$name === void 0 + ? void 0 + : _definition$name.value) === operationName + ) { + operation = definition; + } - function gotTarget(err, target, base) { - if (err) return cb(err); + break; - var resolvedLink = pathModule.resolve(previous, target); - if (cache) cache[base] = resolvedLink; - gotResolvedLink(resolvedLink); - } + case _kinds.Kind.FRAGMENT_DEFINITION: + fragments[definition.name.value] = definition; + break; - function gotResolvedLink(resolvedLink) { - // resolve the link, then start over - p = pathModule.resolve(resolvedLink, p.slice(pos)); - start(); + default: // ignore non-executable definitions + } } -}; + if (!operation) { + if (operationName != null) { + return [ + new _GraphQLError.GraphQLError( + `Unknown operation named "${operationName}".`, + ), + ]; + } -/***/ }), - -/***/ 5045: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return [new _GraphQLError.GraphQLError('Must provide an operation.')]; + } // FIXME: https://github.com/graphql/graphql-js/issues/2203 -"use strict"; + /* c8 ignore next */ + const variableDefinitions = + (_operation$variableDe = operation.variableDefinitions) !== null && + _operation$variableDe !== void 0 + ? _operation$variableDe + : []; + const coercedVariableValues = (0, _values.getVariableValues)( + schema, + variableDefinitions, + rawVariableValues !== null && rawVariableValues !== void 0 + ? rawVariableValues + : {}, + { + maxErrors: + (_options$maxCoercionE = + options === null || options === void 0 + ? void 0 + : options.maxCoercionErrors) !== null && + _options$maxCoercionE !== void 0 + ? _options$maxCoercionE + : 50, + }, + ); -var $Object = __nccwpck_require__(78308); + if (coercedVariableValues.errors) { + return coercedVariableValues.errors; + } -/** @type {import('./Object.getPrototypeOf')} */ -module.exports = $Object.getPrototypeOf || null; + return { + schema, + fragments, + rootValue, + contextValue, + operation, + variableValues: coercedVariableValues.coerced, + fieldResolver: + fieldResolver !== null && fieldResolver !== void 0 + ? fieldResolver + : defaultFieldResolver, + typeResolver: + typeResolver !== null && typeResolver !== void 0 + ? typeResolver + : defaultTypeResolver, + subscribeFieldResolver: + subscribeFieldResolver !== null && subscribeFieldResolver !== void 0 + ? subscribeFieldResolver + : defaultFieldResolver, + errors: [], + }; +} +/** + * Implements the "Executing operations" section of the spec. + */ +function executeOperation(exeContext, operation, rootValue) { + const rootType = exeContext.schema.getRootType(operation.operation); -/***/ }), + if (rootType == null) { + throw new _GraphQLError.GraphQLError( + `Schema is not configured to execute ${operation.operation} operation.`, + { + nodes: operation, + }, + ); + } -/***/ 78859: -/***/ ((module) => { + const rootFields = (0, _collectFields.collectFields)( + exeContext.schema, + exeContext.fragments, + exeContext.variableValues, + rootType, + operation.selectionSet, + ); + const path = undefined; -"use strict"; + switch (operation.operation) { + case _ast.OperationTypeNode.QUERY: + return executeFields(exeContext, rootType, rootValue, path, rootFields); + case _ast.OperationTypeNode.MUTATION: + return executeFieldsSerially( + exeContext, + rootType, + rootValue, + path, + rootFields, + ); -/** @type {import('./Reflect.getPrototypeOf')} */ -module.exports = (typeof Reflect !== 'undefined' && Reflect.getPrototypeOf) || null; + case _ast.OperationTypeNode.SUBSCRIPTION: + // TODO: deprecate `subscribe` and move all logic here + // Temporary solution until we finish merging execute and subscribe together + return executeFields(exeContext, rootType, rootValue, path, rootFields); + } +} +/** + * Implements the "Executing selection sets" section of the spec + * for fields that must be executed serially. + */ +function executeFieldsSerially( + exeContext, + parentType, + sourceValue, + path, + fields, +) { + return (0, _promiseReduce.promiseReduce)( + fields.entries(), + (results, [responseName, fieldNodes]) => { + const fieldPath = (0, _Path.addPath)(path, responseName, parentType.name); + const result = executeField( + exeContext, + parentType, + sourceValue, + fieldNodes, + fieldPath, + ); -/***/ }), + if (result === undefined) { + return results; + } -/***/ 13592: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if ((0, _isPromise.isPromise)(result)) { + return result.then((resolvedResult) => { + results[responseName] = resolvedResult; + return results; + }); + } -"use strict"; + results[responseName] = result; + return results; + }, + Object.create(null), + ); +} +/** + * Implements the "Executing selection sets" section of the spec + * for fields that may be executed in parallel. + */ +function executeFields(exeContext, parentType, sourceValue, path, fields) { + const results = Object.create(null); + let containsPromise = false; -var reflectGetProto = __nccwpck_require__(78859); -var originalGetProto = __nccwpck_require__(5045); + try { + for (const [responseName, fieldNodes] of fields.entries()) { + const fieldPath = (0, _Path.addPath)(path, responseName, parentType.name); + const result = executeField( + exeContext, + parentType, + sourceValue, + fieldNodes, + fieldPath, + ); -var getDunderProto = __nccwpck_require__(62693); + if (result !== undefined) { + results[responseName] = result; -/** @type {import('.')} */ -module.exports = reflectGetProto - ? function getProto(O) { - // @ts-expect-error TS can't narrow inside a closure, for some reason - return reflectGetProto(O); - } - : originalGetProto - ? function getProto(O) { - if (!O || (typeof O !== 'object' && typeof O !== 'function')) { - throw new TypeError('getProto: not an object'); - } - // @ts-expect-error TS can't narrow inside a closure, for some reason - return originalGetProto(O); - } - : getDunderProto - ? function getProto(O) { - // @ts-expect-error TS can't narrow inside a closure, for some reason - return getDunderProto(O); - } - : null; + if ((0, _isPromise.isPromise)(result)) { + containsPromise = true; + } + } + } + } catch (error) { + if (containsPromise) { + // Ensure that any promises returned by other fields are handled, as they may also reject. + return (0, _promiseForObject.promiseForObject)(results).finally(() => { + throw error; + }); + } + throw error; + } // If there are no promises, we can just return the object -/***/ }), + if (!containsPromise) { + return results; + } // Otherwise, results is a map from field name to the result of resolving that + // field, which is possibly a promise. Return a promise that will return this + // same map, but with any promises replaced with the values they resolved to. -/***/ 91585: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return (0, _promiseForObject.promiseForObject)(results); +} +/** + * Implements the "Executing fields" section of the spec + * In particular, this function figures out the value that the field returns by + * calling its resolve function, then calls completeValue to complete promises, + * serialize scalars, or execute the sub-selection-set for objects. + */ -"use strict"; +function executeField(exeContext, parentType, source, fieldNodes, path) { + var _fieldDef$resolve; -const {PassThrough: PassThroughStream} = __nccwpck_require__(12781); + const fieldDef = getFieldDef(exeContext.schema, parentType, fieldNodes[0]); -module.exports = options => { - options = {...options}; + if (!fieldDef) { + return; + } - const {array} = options; - let {encoding} = options; - const isBuffer = encoding === 'buffer'; - let objectMode = false; + const returnType = fieldDef.type; + const resolveFn = + (_fieldDef$resolve = fieldDef.resolve) !== null && + _fieldDef$resolve !== void 0 + ? _fieldDef$resolve + : exeContext.fieldResolver; + const info = buildResolveInfo( + exeContext, + fieldDef, + fieldNodes, + parentType, + path, + ); // Get the resolve function, regardless of if its result is normal or abrupt (error). - if (array) { - objectMode = !(encoding || isBuffer); - } else { - encoding = encoding || 'utf8'; - } + try { + // Build a JS object of arguments from the field.arguments AST, using the + // variables scope to fulfill any variable references. + // TODO: find a way to memoize, in case this field is within a List type. + const args = (0, _values.getArgumentValues)( + fieldDef, + fieldNodes[0], + exeContext.variableValues, + ); // The resolve function's optional third argument is a context value that + // is provided to every resolve function within an execution. It is commonly + // used to represent an authenticated user, or request-specific caches. - if (isBuffer) { - encoding = null; - } + const contextValue = exeContext.contextValue; + const result = resolveFn(source, args, contextValue, info); + let completed; - const stream = new PassThroughStream({objectMode}); + if ((0, _isPromise.isPromise)(result)) { + completed = result.then((resolved) => + completeValue(exeContext, returnType, fieldNodes, info, path, resolved), + ); + } else { + completed = completeValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, + ); + } - if (encoding) { - stream.setEncoding(encoding); - } + if ((0, _isPromise.isPromise)(completed)) { + // Note: we don't rely on a `catch` method, but we do expect "thenable" + // to take a second callback for the error case. + return completed.then(undefined, (rawError) => { + const error = (0, _locatedError.locatedError)( + rawError, + fieldNodes, + (0, _Path.pathToArray)(path), + ); + return handleFieldError(error, returnType, exeContext); + }); + } - let length = 0; - const chunks = []; + return completed; + } catch (rawError) { + const error = (0, _locatedError.locatedError)( + rawError, + fieldNodes, + (0, _Path.pathToArray)(path), + ); + return handleFieldError(error, returnType, exeContext); + } +} +/** + * @internal + */ - stream.on('data', chunk => { - chunks.push(chunk); +function buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path) { + // The resolve function's optional fourth argument is a collection of + // information about the current execution state. + return { + fieldName: fieldDef.name, + fieldNodes, + returnType: fieldDef.type, + parentType, + path, + schema: exeContext.schema, + fragments: exeContext.fragments, + rootValue: exeContext.rootValue, + operation: exeContext.operation, + variableValues: exeContext.variableValues, + }; +} - if (objectMode) { - length = chunks.length; - } else { - length += chunk.length; - } - }); +function handleFieldError(error, returnType, exeContext) { + // If the field type is non-nullable, then it is resolved without any + // protection from errors, however it still properly locates the error. + if ((0, _definition.isNonNullType)(returnType)) { + throw error; + } // Otherwise, error protection is applied, logging the error and resolving + // a null value for this field if one is encountered. - stream.getBufferedValue = () => { - if (array) { - return chunks; - } + exeContext.errors.push(error); + return null; +} +/** + * Implements the instructions for completeValue as defined in the + * "Value Completion" section of the spec. + * + * If the field type is Non-Null, then this recursively completes the value + * for the inner type. It throws a field error if that completion returns null, + * as per the "Nullability" section of the spec. + * + * If the field type is a List, then this recursively completes the value + * for the inner type on each item in the list. + * + * If the field type is a Scalar or Enum, ensures the completed value is a legal + * value of the type by calling the `serialize` method of GraphQL type + * definition. + * + * If the field is an abstract type, determine the runtime type of the value + * and then complete based on that type + * + * Otherwise, the field type expects a sub-selection set, and will complete the + * value by executing all sub-selections. + */ - return isBuffer ? Buffer.concat(chunks, length) : chunks.join(''); - }; +function completeValue(exeContext, returnType, fieldNodes, info, path, result) { + // If result is an Error, throw a located error. + if (result instanceof Error) { + throw result; + } // If field type is NonNull, complete for inner type, and throw field error + // if result is null. - stream.getBufferedLength = () => length; + if ((0, _definition.isNonNullType)(returnType)) { + const completed = completeValue( + exeContext, + returnType.ofType, + fieldNodes, + info, + path, + result, + ); - return stream; -}; + if (completed === null) { + throw new Error( + `Cannot return null for non-nullable field ${info.parentType.name}.${info.fieldName}.`, + ); + } + return completed; + } // If result value is null or undefined then return null. -/***/ }), + if (result == null) { + return null; + } // If field type is List, complete each item in the list with the inner type -/***/ 21766: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if ((0, _definition.isListType)(returnType)) { + return completeListValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, + ); + } // If field type is a leaf type, Scalar or Enum, serialize to a valid value, + // returning null if serialization is not possible. -"use strict"; + if ((0, _definition.isLeafType)(returnType)) { + return completeLeafValue(returnType, result); + } // If field type is an abstract type, Interface or Union, determine the + // runtime Object type and complete for that type. -const {constants: BufferConstants} = __nccwpck_require__(14300); -const stream = __nccwpck_require__(12781); -const {promisify} = __nccwpck_require__(73837); -const bufferStream = __nccwpck_require__(91585); + if ((0, _definition.isAbstractType)(returnType)) { + return completeAbstractValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, + ); + } // If field type is Object, execute and complete all sub-selections. -const streamPipelinePromisified = promisify(stream.pipeline); + if ((0, _definition.isObjectType)(returnType)) { + return completeObjectValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, + ); + } + /* c8 ignore next 6 */ + // Not reachable, all possible output types have been considered. -class MaxBufferError extends Error { - constructor() { - super('maxBuffer exceeded'); - this.name = 'MaxBufferError'; - } + false || + (0, _invariant.invariant)( + false, + 'Cannot complete value of unexpected output type: ' + + (0, _inspect.inspect)(returnType), + ); } +/** + * Complete a list value by completing each item in the list with the + * inner type + */ -async function getStream(inputStream, options) { - if (!inputStream) { - throw new Error('Expected a stream'); - } - - options = { - maxBuffer: Infinity, - ...options - }; +function completeListValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, +) { + if (!(0, _isIterableObject.isIterableObject)(result)) { + throw new _GraphQLError.GraphQLError( + `Expected Iterable, but did not find one for field "${info.parentType.name}.${info.fieldName}".`, + ); + } // This is specified as a simple map, however we're optimizing the path + // where the list contains no Promises by avoiding creating another Promise. - const {maxBuffer} = options; - const stream = bufferStream(options); + const itemType = returnType.ofType; + let containsPromise = false; + const completedResults = Array.from(result, (item, index) => { + // No need to modify the info object containing the path, + // since from here on it is not ever accessed by resolver functions. + const itemPath = (0, _Path.addPath)(path, index, undefined); - await new Promise((resolve, reject) => { - const rejectPromise = error => { - // Don't retrieve an oversized buffer. - if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) { - error.bufferedData = stream.getBufferedValue(); - } + try { + let completedItem; - reject(error); - }; + if ((0, _isPromise.isPromise)(item)) { + completedItem = item.then((resolved) => + completeValue( + exeContext, + itemType, + fieldNodes, + info, + itemPath, + resolved, + ), + ); + } else { + completedItem = completeValue( + exeContext, + itemType, + fieldNodes, + info, + itemPath, + item, + ); + } - (async () => { - try { - await streamPipelinePromisified(inputStream, stream); - resolve(); - } catch (error) { - rejectPromise(error); - } - })(); + if ((0, _isPromise.isPromise)(completedItem)) { + containsPromise = true; // Note: we don't rely on a `catch` method, but we do expect "thenable" + // to take a second callback for the error case. - stream.on('data', () => { - if (stream.getBufferedLength() > maxBuffer) { - rejectPromise(new MaxBufferError()); - } - }); - }); + return completedItem.then(undefined, (rawError) => { + const error = (0, _locatedError.locatedError)( + rawError, + fieldNodes, + (0, _Path.pathToArray)(itemPath), + ); + return handleFieldError(error, itemType, exeContext); + }); + } - return stream.getBufferedValue(); + return completedItem; + } catch (rawError) { + const error = (0, _locatedError.locatedError)( + rawError, + fieldNodes, + (0, _Path.pathToArray)(itemPath), + ); + return handleFieldError(error, itemType, exeContext); + } + }); + return containsPromise ? Promise.all(completedResults) : completedResults; } +/** + * Complete a Scalar or Enum by serializing to a valid value, returning + * null if serialization is not possible. + */ -module.exports = getStream; -module.exports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'}); -module.exports.array = (stream, options) => getStream(stream, {...options, array: true}); -module.exports.MaxBufferError = MaxBufferError; +function completeLeafValue(returnType, result) { + const serializedResult = returnType.serialize(result); + + if (serializedResult == null) { + throw new Error( + `Expected \`${(0, _inspect.inspect)(returnType)}.serialize(${(0, + _inspect.inspect)(result)})\` to ` + + `return non-nullable value, returned: ${(0, _inspect.inspect)( + serializedResult, + )}`, + ); + } + return serializedResult; +} +/** + * Complete a value of an abstract type by determining the runtime object type + * of that value, then complete the value for that type. + */ -/***/ }), +function completeAbstractValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, +) { + var _returnType$resolveTy; -/***/ 47625: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + const resolveTypeFn = + (_returnType$resolveTy = returnType.resolveType) !== null && + _returnType$resolveTy !== void 0 + ? _returnType$resolveTy + : exeContext.typeResolver; + const contextValue = exeContext.contextValue; + const runtimeType = resolveTypeFn(result, contextValue, info, returnType); -exports.setopts = setopts -exports.ownProp = ownProp -exports.makeAbs = makeAbs -exports.finish = finish -exports.mark = mark -exports.isIgnored = isIgnored -exports.childrenIgnored = childrenIgnored + if ((0, _isPromise.isPromise)(runtimeType)) { + return runtimeType.then((resolvedRuntimeType) => + completeObjectValue( + exeContext, + ensureValidRuntimeType( + resolvedRuntimeType, + exeContext, + returnType, + fieldNodes, + info, + result, + ), + fieldNodes, + info, + path, + result, + ), + ); + } -function ownProp (obj, field) { - return Object.prototype.hasOwnProperty.call(obj, field) + return completeObjectValue( + exeContext, + ensureValidRuntimeType( + runtimeType, + exeContext, + returnType, + fieldNodes, + info, + result, + ), + fieldNodes, + info, + path, + result, + ); } -var fs = __nccwpck_require__(57147) -var path = __nccwpck_require__(71017) -var minimatch = __nccwpck_require__(83973) -var isAbsolute = __nccwpck_require__(38714) -var Minimatch = minimatch.Minimatch +function ensureValidRuntimeType( + runtimeTypeName, + exeContext, + returnType, + fieldNodes, + info, + result, +) { + if (runtimeTypeName == null) { + throw new _GraphQLError.GraphQLError( + `Abstract type "${returnType.name}" must resolve to an Object type at runtime for field "${info.parentType.name}.${info.fieldName}". Either the "${returnType.name}" type should provide a "resolveType" function or each possible type should provide an "isTypeOf" function.`, + fieldNodes, + ); + } // releases before 16.0.0 supported returning `GraphQLObjectType` from `resolveType` + // TODO: remove in 17.0.0 release -function alphasort (a, b) { - return a.localeCompare(b, 'en') -} + if ((0, _definition.isObjectType)(runtimeTypeName)) { + throw new _GraphQLError.GraphQLError( + 'Support for returning GraphQLObjectType from resolveType was removed in graphql-js@16.0.0 please return type name instead.', + ); + } -function setupIgnores (self, options) { - self.ignore = options.ignore || [] + if (typeof runtimeTypeName !== 'string') { + throw new _GraphQLError.GraphQLError( + `Abstract type "${returnType.name}" must resolve to an Object type at runtime for field "${info.parentType.name}.${info.fieldName}" with ` + + `value ${(0, _inspect.inspect)(result)}, received "${(0, + _inspect.inspect)(runtimeTypeName)}".`, + ); + } - if (!Array.isArray(self.ignore)) - self.ignore = [self.ignore] + const runtimeType = exeContext.schema.getType(runtimeTypeName); - if (self.ignore.length) { - self.ignore = self.ignore.map(ignoreMap) + if (runtimeType == null) { + throw new _GraphQLError.GraphQLError( + `Abstract type "${returnType.name}" was resolved to a type "${runtimeTypeName}" that does not exist inside the schema.`, + { + nodes: fieldNodes, + }, + ); } -} -// ignore patterns are always in dot:true mode. -function ignoreMap (pattern) { - var gmatcher = null - if (pattern.slice(-3) === '/**') { - var gpattern = pattern.replace(/(\/\*\*)+$/, '') - gmatcher = new Minimatch(gpattern, { dot: true }) + if (!(0, _definition.isObjectType)(runtimeType)) { + throw new _GraphQLError.GraphQLError( + `Abstract type "${returnType.name}" was resolved to a non-object type "${runtimeTypeName}".`, + { + nodes: fieldNodes, + }, + ); } - return { - matcher: new Minimatch(pattern, { dot: true }), - gmatcher: gmatcher + if (!exeContext.schema.isSubType(returnType, runtimeType)) { + throw new _GraphQLError.GraphQLError( + `Runtime Object type "${runtimeType.name}" is not a possible type for "${returnType.name}".`, + { + nodes: fieldNodes, + }, + ); } -} -function setopts (self, pattern, options) { - if (!options) - options = {} + return runtimeType; +} +/** + * Complete an Object value by executing all sub-selections. + */ - // base-matching: just use globstar for that. - if (options.matchBase && -1 === pattern.indexOf("/")) { - if (options.noglobstar) { - throw new Error("base matching requires globstar") - } - pattern = "**/" + pattern - } +function completeObjectValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, +) { + // Collect sub-fields to execute to complete this value. + const subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes); // If there is an isTypeOf predicate function, call it with the + // current result. If isTypeOf returns false, then raise an error rather + // than continuing execution. - self.silent = !!options.silent - self.pattern = pattern - self.strict = options.strict !== false - self.realpath = !!options.realpath - self.realpathCache = options.realpathCache || Object.create(null) - self.follow = !!options.follow - self.dot = !!options.dot - self.mark = !!options.mark - self.nodir = !!options.nodir - if (self.nodir) - self.mark = true - self.sync = !!options.sync - self.nounique = !!options.nounique - self.nonull = !!options.nonull - self.nosort = !!options.nosort - self.nocase = !!options.nocase - self.stat = !!options.stat - self.noprocess = !!options.noprocess - self.absolute = !!options.absolute - self.fs = options.fs || fs + if (returnType.isTypeOf) { + const isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info); - self.maxLength = options.maxLength || Infinity - self.cache = options.cache || Object.create(null) - self.statCache = options.statCache || Object.create(null) - self.symlinks = options.symlinks || Object.create(null) + if ((0, _isPromise.isPromise)(isTypeOf)) { + return isTypeOf.then((resolvedIsTypeOf) => { + if (!resolvedIsTypeOf) { + throw invalidReturnTypeError(returnType, result, fieldNodes); + } - setupIgnores(self, options) + return executeFields( + exeContext, + returnType, + result, + path, + subFieldNodes, + ); + }); + } - self.changedCwd = false - var cwd = process.cwd() - if (!ownProp(options, "cwd")) - self.cwd = cwd - else { - self.cwd = path.resolve(options.cwd) - self.changedCwd = self.cwd !== cwd + if (!isTypeOf) { + throw invalidReturnTypeError(returnType, result, fieldNodes); + } } - self.root = options.root || path.resolve(self.cwd, "/") - self.root = path.resolve(self.root) - if (process.platform === "win32") - self.root = self.root.replace(/\\/g, "/") + return executeFields(exeContext, returnType, result, path, subFieldNodes); +} - // TODO: is an absolute `cwd` supposed to be resolved against `root`? - // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') - self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd) - if (process.platform === "win32") - self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") - self.nomount = !!options.nomount +function invalidReturnTypeError(returnType, result, fieldNodes) { + return new _GraphQLError.GraphQLError( + `Expected value of type "${returnType.name}" but got: ${(0, + _inspect.inspect)(result)}.`, + { + nodes: fieldNodes, + }, + ); +} +/** + * If a resolveType function is not given, then a default resolve behavior is + * used which attempts two strategies: + * + * First, See if the provided value has a `__typename` field defined, if so, use + * that value as name of the resolved type. + * + * Otherwise, test each possible type for the abstract type by calling + * isTypeOf for the object being coerced, returning the first type that matches. + */ - // disable comments and negation in Minimatch. - // Note that they are not supported in Glob itself anyway. - options.nonegate = true - options.nocomment = true - // always treat \ in patterns as escapes, not path separators - options.allowWindowsEscape = false +const defaultTypeResolver = function (value, contextValue, info, abstractType) { + // First, look for `__typename`. + if ( + (0, _isObjectLike.isObjectLike)(value) && + typeof value.__typename === 'string' + ) { + return value.__typename; + } // Otherwise, test each possible type. - self.minimatch = new Minimatch(pattern, options) - self.options = self.minimatch.options -} + const possibleTypes = info.schema.getPossibleTypes(abstractType); + const promisedIsTypeOfResults = []; -function finish (self) { - var nou = self.nounique - var all = nou ? [] : Object.create(null) + for (let i = 0; i < possibleTypes.length; i++) { + const type = possibleTypes[i]; - for (var i = 0, l = self.matches.length; i < l; i ++) { - var matches = self.matches[i] - if (!matches || Object.keys(matches).length === 0) { - if (self.nonull) { - // do like the shell, and spit out the literal glob - var literal = self.minimatch.globSet[i] - if (nou) - all.push(literal) - else - all[literal] = true + if (type.isTypeOf) { + const isTypeOfResult = type.isTypeOf(value, contextValue, info); + + if ((0, _isPromise.isPromise)(isTypeOfResult)) { + promisedIsTypeOfResults[i] = isTypeOfResult; + } else if (isTypeOfResult) { + return type.name; } - } else { - // had matches - var m = Object.keys(matches) - if (nou) - all.push.apply(all, m) - else - m.forEach(function (m) { - all[m] = true - }) } } - if (!nou) - all = Object.keys(all) + if (promisedIsTypeOfResults.length) { + return Promise.all(promisedIsTypeOfResults).then((isTypeOfResults) => { + for (let i = 0; i < isTypeOfResults.length; i++) { + if (isTypeOfResults[i]) { + return possibleTypes[i].name; + } + } + }); + } +}; +/** + * If a resolve function is not given, then a default resolve behavior is used + * which takes the property of the source object of the same name as the field + * and returns it as the result, or if it's a function, returns the result + * of calling that function while passing along args and context value. + */ - if (!self.nosort) - all = all.sort(alphasort) +exports.defaultTypeResolver = defaultTypeResolver; - // at *some* point we statted all of these - if (self.mark) { - for (var i = 0; i < all.length; i++) { - all[i] = self._mark(all[i]) - } - if (self.nodir) { - all = all.filter(function (e) { - var notDir = !(/\/$/.test(e)) - var c = self.cache[e] || self.cache[makeAbs(self, e)] - if (notDir && c) - notDir = c !== 'DIR' && !Array.isArray(c) - return notDir - }) - } - } +const defaultFieldResolver = function (source, args, contextValue, info) { + // ensure source is a value for which property access is acceptable. + if ((0, _isObjectLike.isObjectLike)(source) || typeof source === 'function') { + const property = source[info.fieldName]; - if (self.ignore.length) - all = all.filter(function(m) { - return !isIgnored(self, m) - }) + if (typeof property === 'function') { + return source[info.fieldName](args, contextValue, info); + } - self.found = all -} + return property; + } +}; +/** + * This method looks up the field on the given type definition. + * It has special casing for the three introspection fields, + * __schema, __type and __typename. __typename is special because + * it can always be queried as a field, even in situations where no + * other fields are allowed, like on a Union. __schema and __type + * could get automatically added to the query type, but that would + * require mutating type definitions, which would cause issues. + * + * @internal + */ -function mark (self, p) { - var abs = makeAbs(self, p) - var c = self.cache[abs] - var m = p - if (c) { - var isDir = c === 'DIR' || Array.isArray(c) - var slash = p.slice(-1) === '/' +exports.defaultFieldResolver = defaultFieldResolver; - if (isDir && !slash) - m += '/' - else if (!isDir && slash) - m = m.slice(0, -1) +function getFieldDef(schema, parentType, fieldNode) { + const fieldName = fieldNode.name.value; - if (m !== p) { - var mabs = makeAbs(self, m) - self.statCache[mabs] = self.statCache[abs] - self.cache[mabs] = self.cache[abs] - } + if ( + fieldName === _introspection.SchemaMetaFieldDef.name && + schema.getQueryType() === parentType + ) { + return _introspection.SchemaMetaFieldDef; + } else if ( + fieldName === _introspection.TypeMetaFieldDef.name && + schema.getQueryType() === parentType + ) { + return _introspection.TypeMetaFieldDef; + } else if (fieldName === _introspection.TypeNameMetaFieldDef.name) { + return _introspection.TypeNameMetaFieldDef; } - return m + return parentType.getFields()[fieldName]; } -// lotta situps... -function makeAbs (self, f) { - var abs = f - if (f.charAt(0) === '/') { - abs = path.join(self.root, f) - } else if (isAbsolute(f) || f === '') { - abs = f - } else if (self.changedCwd) { - abs = path.resolve(self.cwd, f) - } else { - abs = path.resolve(f) - } - if (process.platform === 'win32') - abs = abs.replace(/\\/g, '/') +/***/ }), - return abs -} +/***/ 13176: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; -// Return true, if pattern ends with globstar '**', for the accompanying parent directory. -// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents -function isIgnored (self, path) { - if (!self.ignore.length) - return false - return self.ignore.some(function(item) { - return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) - }) -} +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +Object.defineProperty(exports, "createSourceEventStream", ({ + enumerable: true, + get: function () { + return _subscribe.createSourceEventStream; + }, +})); +Object.defineProperty(exports, "defaultFieldResolver", ({ + enumerable: true, + get: function () { + return _execute.defaultFieldResolver; + }, +})); +Object.defineProperty(exports, "defaultTypeResolver", ({ + enumerable: true, + get: function () { + return _execute.defaultTypeResolver; + }, +})); +Object.defineProperty(exports, "execute", ({ + enumerable: true, + get: function () { + return _execute.execute; + }, +})); +Object.defineProperty(exports, "executeSync", ({ + enumerable: true, + get: function () { + return _execute.executeSync; + }, +})); +Object.defineProperty(exports, "getArgumentValues", ({ + enumerable: true, + get: function () { + return _values.getArgumentValues; + }, +})); +Object.defineProperty(exports, "getDirectiveValues", ({ + enumerable: true, + get: function () { + return _values.getDirectiveValues; + }, +})); +Object.defineProperty(exports, "getVariableValues", ({ + enumerable: true, + get: function () { + return _values.getVariableValues; + }, +})); +Object.defineProperty(exports, "responsePathAsArray", ({ + enumerable: true, + get: function () { + return _Path.pathToArray; + }, +})); +Object.defineProperty(exports, "subscribe", ({ + enumerable: true, + get: function () { + return _subscribe.subscribe; + }, +})); -function childrenIgnored (self, path) { - if (!self.ignore.length) - return false +var _Path = __nccwpck_require__(11262); - return self.ignore.some(function(item) { - return !!(item.gmatcher && item.gmatcher.match(path)) - }) -} +var _execute = __nccwpck_require__(83677); + +var _subscribe = __nccwpck_require__(77847); + +var _values = __nccwpck_require__(94834); /***/ }), -/***/ 91957: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 86063: +/***/ ((__unused_webpack_module, exports) => { -// Approach: -// -// 1. Get the minimatch set -// 2. For each pattern in the set, PROCESS(pattern, false) -// 3. Store matches per-set, then uniq them -// -// PROCESS(pattern, inGlobStar) -// Get the first [n] items from pattern that are all strings -// Join these together. This is PREFIX. -// If there is no more remaining, then stat(PREFIX) and -// add to matches if it succeeds. END. -// -// If inGlobStar and PREFIX is symlink and points to dir -// set ENTRIES = [] -// else readdir(PREFIX) as ENTRIES -// If fail, END -// -// with ENTRIES -// If pattern[n] is GLOBSTAR -// // handle the case where the globstar match is empty -// // by pruning it out, and testing the resulting pattern -// PROCESS(pattern[0..n] + pattern[n+1 .. $], false) -// // handle other cases. -// for ENTRY in ENTRIES (not dotfiles) -// // attach globstar + tail onto the entry -// // Mark that this entry is a globstar match -// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) -// -// else // not globstar -// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) -// Test ENTRY against pattern[n] -// If fails, continue -// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) -// -// Caveat: -// Cache all stats and readdirs results to minimize syscall. Since all -// we ever care about is existence and directory-ness, we can just keep -// `true` for files, and [children,...] for directories, or `false` for -// things that don't exist. +"use strict"; -module.exports = glob -var rp = __nccwpck_require__(46863) -var minimatch = __nccwpck_require__(83973) -var Minimatch = minimatch.Minimatch -var inherits = __nccwpck_require__(44124) -var EE = (__nccwpck_require__(82361).EventEmitter) -var path = __nccwpck_require__(71017) -var assert = __nccwpck_require__(39491) -var isAbsolute = __nccwpck_require__(38714) -var globSync = __nccwpck_require__(29010) -var common = __nccwpck_require__(47625) -var setopts = common.setopts -var ownProp = common.ownProp -var inflight = __nccwpck_require__(52492) -var util = __nccwpck_require__(73837) -var childrenIgnored = common.childrenIgnored -var isIgnored = common.isIgnored +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.mapAsyncIterator = mapAsyncIterator; -var once = __nccwpck_require__(1223) +/** + * Given an AsyncIterable and a callback function, return an AsyncIterator + * which produces values mapped via calling the callback function. + */ +function mapAsyncIterator(iterable, callback) { + const iterator = iterable[Symbol.asyncIterator](); -function glob (pattern, options, cb) { - if (typeof options === 'function') cb = options, options = {} - if (!options) options = {} + async function mapResult(result) { + if (result.done) { + return result; + } - if (options.sync) { - if (cb) - throw new TypeError('callback provided to sync glob') - return globSync(pattern, options) + try { + return { + value: await callback(result.value), + done: false, + }; + } catch (error) { + /* c8 ignore start */ + // FIXME: add test case + if (typeof iterator.return === 'function') { + try { + await iterator.return(); + } catch (_e) { + /* ignore error */ + } + } + + throw error; + /* c8 ignore stop */ + } } - return new Glob(pattern, options, cb) -} + return { + async next() { + return mapResult(await iterator.next()); + }, -glob.sync = globSync -var GlobSync = glob.GlobSync = globSync.GlobSync + async return() { + // If iterator.return() does not exist, then type R must be undefined. + return typeof iterator.return === 'function' + ? mapResult(await iterator.return()) + : { + value: undefined, + done: true, + }; + }, -// old api surface -glob.glob = glob + async throw(error) { + if (typeof iterator.throw === 'function') { + return mapResult(await iterator.throw(error)); + } -function extend (origin, add) { - if (add === null || typeof add !== 'object') { - return origin - } + throw error; + }, - var keys = Object.keys(add) - var i = keys.length - while (i--) { - origin[keys[i]] = add[keys[i]] - } - return origin + [Symbol.asyncIterator]() { + return this; + }, + }; } -glob.hasMagic = function (pattern, options_) { - var options = extend({}, options_) - options.noprocess = true - var g = new Glob(pattern, options) - var set = g.minimatch.set +/***/ }), - if (!pattern) - return false +/***/ 77847: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (set.length > 1) - return true +"use strict"; - for (var j = 0; j < set[0].length; j++) { - if (typeof set[0][j] !== 'string') - return true - } - return false -} +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.createSourceEventStream = createSourceEventStream; +exports.subscribe = subscribe; -glob.Glob = Glob -inherits(Glob, EE) -function Glob (pattern, options, cb) { - if (typeof options === 'function') { - cb = options - options = null - } +var _devAssert = __nccwpck_require__(46514); - if (options && options.sync) { - if (cb) - throw new TypeError('callback provided to sync glob') - return new GlobSync(pattern, options) - } +var _inspect = __nccwpck_require__(10102); - if (!(this instanceof Glob)) - return new Glob(pattern, options, cb) +var _isAsyncIterable = __nccwpck_require__(20626); - setopts(this, pattern, options) - this._didRealPath = false +var _Path = __nccwpck_require__(11262); - // process each pattern in the minimatch set - var n = this.minimatch.set.length +var _GraphQLError = __nccwpck_require__(4797); - // The matches are stored as {: true,...} so that - // duplicates are automagically pruned. - // Later, we do an Object.keys() on these. - // Keep them as a list so we can fill in when nonull is set. - this.matches = new Array(n) +var _locatedError = __nccwpck_require__(16842); - if (typeof cb === 'function') { - cb = once(cb) - this.on('error', cb) - this.on('end', function (matches) { - cb(null, matches) - }) - } +var _collectFields = __nccwpck_require__(49942); - var self = this - this._processing = 0 +var _execute = __nccwpck_require__(83677); - this._emitQueue = [] - this._processQueue = [] - this.paused = false +var _mapAsyncIterator = __nccwpck_require__(86063); - if (this.noprocess) - return this +var _values = __nccwpck_require__(94834); - if (n === 0) - return done() +/** + * Implements the "Subscribe" algorithm described in the GraphQL specification. + * + * Returns a Promise which resolves to either an AsyncIterator (if successful) + * or an ExecutionResult (error). The promise will be rejected if the schema or + * other arguments to this function are invalid, or if the resolved event stream + * is not an async iterable. + * + * If the client-provided arguments to this function do not result in a + * compliant subscription, a GraphQL Response (ExecutionResult) with + * descriptive errors and no data will be returned. + * + * If the source stream could not be created due to faulty subscription + * resolver logic or underlying systems, the promise will resolve to a single + * ExecutionResult containing `errors` and no `data`. + * + * If the operation succeeded, the promise resolves to an AsyncIterator, which + * yields a stream of ExecutionResults representing the response stream. + * + * Accepts either an object with named arguments, or individual arguments. + */ +async function subscribe(args) { + // Temporary for v15 to v16 migration. Remove in v17 + arguments.length < 2 || + (0, _devAssert.devAssert)( + false, + 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.', + ); + const resultOrStream = await createSourceEventStream(args); - var sync = true - for (var i = 0; i < n; i ++) { - this._process(this.minimatch.set[i], i, false, done) - } - sync = false + if (!(0, _isAsyncIterable.isAsyncIterable)(resultOrStream)) { + return resultOrStream; + } // For each payload yielded from a subscription, map it over the normal + // GraphQL `execute` function, with `payload` as the rootValue. + // This implements the "MapSourceToResponseEvent" algorithm described in + // the GraphQL specification. The `execute` function provides the + // "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the + // "ExecuteQuery" algorithm, for which `execute` is also used. - function done () { - --self._processing - if (self._processing <= 0) { - if (sync) { - process.nextTick(function () { - self._finish() - }) - } else { - self._finish() - } - } + const mapSourceToResponse = (payload) => + (0, _execute.execute)({ ...args, rootValue: payload }); // Map every source value to a ExecutionResult value as described above. + + return (0, _mapAsyncIterator.mapAsyncIterator)( + resultOrStream, + mapSourceToResponse, + ); +} + +function toNormalizedArgs(args) { + const firstArg = args[0]; + + if (firstArg && 'document' in firstArg) { + return firstArg; } + + return { + schema: firstArg, + // FIXME: when underlying TS bug fixed, see https://github.com/microsoft/TypeScript/issues/31613 + document: args[1], + rootValue: args[2], + contextValue: args[3], + variableValues: args[4], + operationName: args[5], + subscribeFieldResolver: args[6], + }; } +/** + * Implements the "CreateSourceEventStream" algorithm described in the + * GraphQL specification, resolving the subscription source event stream. + * + * Returns a Promise which resolves to either an AsyncIterable (if successful) + * or an ExecutionResult (error). The promise will be rejected if the schema or + * other arguments to this function are invalid, or if the resolved event stream + * is not an async iterable. + * + * If the client-provided arguments to this function do not result in a + * compliant subscription, a GraphQL Response (ExecutionResult) with + * descriptive errors and no data will be returned. + * + * If the the source stream could not be created due to faulty subscription + * resolver logic or underlying systems, the promise will resolve to a single + * ExecutionResult containing `errors` and no `data`. + * + * If the operation succeeded, the promise resolves to the AsyncIterable for the + * event stream returned by the resolver. + * + * A Source Event Stream represents a sequence of events, each of which triggers + * a GraphQL execution for that event. + * + * This may be useful when hosting the stateful subscription service in a + * different process or machine than the stateless GraphQL execution engine, + * or otherwise separating these two steps. For more on this, see the + * "Supporting Subscriptions at Scale" information in the GraphQL specification. + */ -Glob.prototype._finish = function () { - assert(this instanceof Glob) - if (this.aborted) - return +async function createSourceEventStream(...rawArgs) { + const args = toNormalizedArgs(rawArgs); + const { schema, document, variableValues } = args; // If arguments are missing or incorrectly typed, this is an internal + // developer mistake which should throw an early error. - if (this.realpath && !this._didRealpath) - return this._realpath() + (0, _execute.assertValidExecutionArguments)(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments, + // a "Response" with only errors is returned. - common.finish(this) - this.emit('end', this.found) -} + const exeContext = (0, _execute.buildExecutionContext)(args); // Return early errors if execution context failed. -Glob.prototype._realpath = function () { - if (this._didRealpath) - return + if (!('schema' in exeContext)) { + return { + errors: exeContext, + }; + } - this._didRealpath = true + try { + const eventStream = await executeSubscription(exeContext); // Assert field returned an event stream, otherwise yield an error. - var n = this.matches.length - if (n === 0) - return this._finish() + if (!(0, _isAsyncIterable.isAsyncIterable)(eventStream)) { + throw new Error( + 'Subscription field must return Async Iterable. ' + + `Received: ${(0, _inspect.inspect)(eventStream)}.`, + ); + } - var self = this - for (var i = 0; i < this.matches.length; i++) - this._realpathSet(i, next) + return eventStream; + } catch (error) { + // If it GraphQLError, report it as an ExecutionResult, containing only errors and no data. + // Otherwise treat the error as a system-class error and re-throw it. + if (error instanceof _GraphQLError.GraphQLError) { + return { + errors: [error], + }; + } - function next () { - if (--n === 0) - self._finish() + throw error; } } -Glob.prototype._realpathSet = function (index, cb) { - var matchset = this.matches[index] - if (!matchset) - return cb() +async function executeSubscription(exeContext) { + const { schema, fragments, operation, variableValues, rootValue } = + exeContext; + const rootType = schema.getSubscriptionType(); - var found = Object.keys(matchset) - var self = this - var n = found.length + if (rootType == null) { + throw new _GraphQLError.GraphQLError( + 'Schema is not configured to execute subscription operation.', + { + nodes: operation, + }, + ); + } - if (n === 0) - return cb() + const rootFields = (0, _collectFields.collectFields)( + schema, + fragments, + variableValues, + rootType, + operation.selectionSet, + ); + const [responseName, fieldNodes] = [...rootFields.entries()][0]; + const fieldDef = (0, _execute.getFieldDef)(schema, rootType, fieldNodes[0]); - var set = this.matches[index] = Object.create(null) - found.forEach(function (p, i) { - // If there's a problem with the stat, then it means that - // one or more of the links in the realpath couldn't be - // resolved. just return the abs value in that case. - p = self._makeAbs(p) - rp.realpath(p, self.realpathCache, function (er, real) { - if (!er) - set[real] = true - else if (er.syscall === 'stat') - set[p] = true - else - self.emit('error', er) // srsly wtf right here + if (!fieldDef) { + const fieldName = fieldNodes[0].name.value; + throw new _GraphQLError.GraphQLError( + `The subscription field "${fieldName}" is not defined.`, + { + nodes: fieldNodes, + }, + ); + } - if (--n === 0) { - self.matches[index] = set - cb() - } - }) - }) -} + const path = (0, _Path.addPath)(undefined, responseName, rootType.name); + const info = (0, _execute.buildResolveInfo)( + exeContext, + fieldDef, + fieldNodes, + rootType, + path, + ); -Glob.prototype._mark = function (p) { - return common.mark(this, p) -} + try { + var _fieldDef$subscribe; -Glob.prototype._makeAbs = function (f) { - return common.makeAbs(this, f) -} + // Implements the "ResolveFieldEventStream" algorithm from GraphQL specification. + // It differs from "ResolveFieldValue" due to providing a different `resolveFn`. + // Build a JS object of arguments from the field.arguments AST, using the + // variables scope to fulfill any variable references. + const args = (0, _values.getArgumentValues)( + fieldDef, + fieldNodes[0], + variableValues, + ); // The resolve function's optional third argument is a context value that + // is provided to every resolve function within an execution. It is commonly + // used to represent an authenticated user, or request-specific caches. -Glob.prototype.abort = function () { - this.aborted = true - this.emit('abort') -} + const contextValue = exeContext.contextValue; // Call the `subscribe()` resolver or the default resolver to produce an + // AsyncIterable yielding raw payloads. -Glob.prototype.pause = function () { - if (!this.paused) { - this.paused = true - this.emit('pause') - } -} + const resolveFn = + (_fieldDef$subscribe = fieldDef.subscribe) !== null && + _fieldDef$subscribe !== void 0 + ? _fieldDef$subscribe + : exeContext.subscribeFieldResolver; + const eventStream = await resolveFn(rootValue, args, contextValue, info); -Glob.prototype.resume = function () { - if (this.paused) { - this.emit('resume') - this.paused = false - if (this._emitQueue.length) { - var eq = this._emitQueue.slice(0) - this._emitQueue.length = 0 - for (var i = 0; i < eq.length; i ++) { - var e = eq[i] - this._emitMatch(e[0], e[1]) - } - } - if (this._processQueue.length) { - var pq = this._processQueue.slice(0) - this._processQueue.length = 0 - for (var i = 0; i < pq.length; i ++) { - var p = pq[i] - this._processing-- - this._process(p[0], p[1], p[2], p[3]) - } + if (eventStream instanceof Error) { + throw eventStream; } + + return eventStream; + } catch (error) { + throw (0, _locatedError.locatedError)( + error, + fieldNodes, + (0, _Path.pathToArray)(path), + ); } } -Glob.prototype._process = function (pattern, index, inGlobStar, cb) { - assert(this instanceof Glob) - assert(typeof cb === 'function') - if (this.aborted) - return +/***/ }), - this._processing++ - if (this.paused) { - this._processQueue.push([pattern, index, inGlobStar, cb]) - return - } +/***/ 94834: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - //console.error('PROCESS %d', this._processing, pattern) +"use strict"; - // Get the first [n] parts of pattern that are all strings. - var n = 0 - while (typeof pattern[n] === 'string') { - n ++ - } - // now n is the index of the first one that is *not* a string. - // see if there's anything else - var prefix - switch (n) { - // if not, then this is rather simple - case pattern.length: - this._processSimple(pattern.join('/'), index, cb) - return +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.getArgumentValues = getArgumentValues; +exports.getDirectiveValues = getDirectiveValues; +exports.getVariableValues = getVariableValues; - case 0: - // pattern *starts* with some non-trivial item. - // going to readdir(cwd), but not include the prefix in matches. - prefix = null - break +var _inspect = __nccwpck_require__(10102); - default: - // pattern has some string bits in the front. - // whatever it starts with, whether that's 'absolute' like /foo/bar, - // or 'relative' like '../baz' - prefix = pattern.slice(0, n).join('/') - break - } +var _keyMap = __nccwpck_require__(10711); - var remain = pattern.slice(n) +var _printPathArray = __nccwpck_require__(94281); - // get the list of entries. - var read - if (prefix === null) - read = '.' - else if (isAbsolute(prefix) || - isAbsolute(pattern.map(function (p) { - return typeof p === 'string' ? p : '[*]' - }).join('/'))) { - if (!prefix || !isAbsolute(prefix)) - prefix = '/' + prefix - read = prefix - } else - read = prefix +var _GraphQLError = __nccwpck_require__(4797); - var abs = this._makeAbs(read) +var _kinds = __nccwpck_require__(11927); - //if ignored, skip _processing - if (childrenIgnored(this, read)) - return cb() +var _printer = __nccwpck_require__(68203); - var isGlobStar = remain[0] === minimatch.GLOBSTAR - if (isGlobStar) - this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) - else - this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) -} +var _definition = __nccwpck_require__(32150); -Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { - var self = this - this._readdir(abs, inGlobStar, function (er, entries) { - return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) - }) -} +var _coerceInputValue = __nccwpck_require__(39603); -Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { +var _typeFromAST = __nccwpck_require__(27664); - // if the abs isn't a dir, then nothing can match! - if (!entries) - return cb() +var _valueFromAST = __nccwpck_require__(83181); - // It will only match dot entries if it starts with a dot, or if - // dot is set. Stuff like @(.foo|.bar) isn't allowed. - var pn = remain[0] - var negate = !!this.minimatch.negate - var rawGlob = pn._glob - var dotOk = this.dot || rawGlob.charAt(0) === '.' +/** + * Prepares an object map of variableValues of the correct type based on the + * provided variable definitions and arbitrary input. If the input cannot be + * parsed to match the variable definitions, a GraphQLError will be thrown. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ +function getVariableValues(schema, varDefNodes, inputs, options) { + const errors = []; + const maxErrors = + options === null || options === void 0 ? void 0 : options.maxErrors; - var matchedEntries = [] - for (var i = 0; i < entries.length; i++) { - var e = entries[i] - if (e.charAt(0) !== '.' || dotOk) { - var m - if (negate && !prefix) { - m = !e.match(pn) - } else { - m = e.match(pn) - } - if (m) - matchedEntries.push(e) + try { + const coerced = coerceVariableValues( + schema, + varDefNodes, + inputs, + (error) => { + if (maxErrors != null && errors.length >= maxErrors) { + throw new _GraphQLError.GraphQLError( + 'Too many errors processing variables, error limit reached. Execution aborted.', + ); + } + + errors.push(error); + }, + ); + + if (errors.length === 0) { + return { + coerced, + }; } + } catch (error) { + errors.push(error); } - //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) + return { + errors, + }; +} - var len = matchedEntries.length - // If there are no matched entries, then nothing matches. - if (len === 0) - return cb() +function coerceVariableValues(schema, varDefNodes, inputs, onError) { + const coercedValues = {}; - // if this is the last remaining pattern bit, then no need for - // an additional stat *unless* the user has specified mark or - // stat explicitly. We know they exist, since readdir returned - // them. + for (const varDefNode of varDefNodes) { + const varName = varDefNode.variable.name.value; + const varType = (0, _typeFromAST.typeFromAST)(schema, varDefNode.type); - if (remain.length === 1 && !this.mark && !this.stat) { - if (!this.matches[index]) - this.matches[index] = Object.create(null) + if (!(0, _definition.isInputType)(varType)) { + // Must use input types for variables. This should be caught during + // validation, however is checked again here for safety. + const varTypeStr = (0, _printer.print)(varDefNode.type); + onError( + new _GraphQLError.GraphQLError( + `Variable "$${varName}" expected value of type "${varTypeStr}" which cannot be used as an input type.`, + { + nodes: varDefNode.type, + }, + ), + ); + continue; + } - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - if (prefix) { - if (prefix !== '/') - e = prefix + '/' + e - else - e = prefix + e + if (!hasOwnProperty(inputs, varName)) { + if (varDefNode.defaultValue) { + coercedValues[varName] = (0, _valueFromAST.valueFromAST)( + varDefNode.defaultValue, + varType, + ); + } else if ((0, _definition.isNonNullType)(varType)) { + const varTypeStr = (0, _inspect.inspect)(varType); + onError( + new _GraphQLError.GraphQLError( + `Variable "$${varName}" of required type "${varTypeStr}" was not provided.`, + { + nodes: varDefNode, + }, + ), + ); } - if (e.charAt(0) === '/' && !this.nomount) { - e = path.join(this.root, e) - } - this._emitMatch(index, e) + continue; } - // This was the last one, and no stats were needed - return cb() - } - // now test all matched entries as stand-ins for that part - // of the pattern. - remain.shift() - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - var newPattern - if (prefix) { - if (prefix !== '/') - e = prefix + '/' + e - else - e = prefix + e + const value = inputs[varName]; + + if (value === null && (0, _definition.isNonNullType)(varType)) { + const varTypeStr = (0, _inspect.inspect)(varType); + onError( + new _GraphQLError.GraphQLError( + `Variable "$${varName}" of non-null type "${varTypeStr}" must not be null.`, + { + nodes: varDefNode, + }, + ), + ); + continue; } - this._process([e].concat(remain), index, inGlobStar, cb) - } - cb() -} -Glob.prototype._emitMatch = function (index, e) { - if (this.aborted) - return + coercedValues[varName] = (0, _coerceInputValue.coerceInputValue)( + value, + varType, + (path, invalidValue, error) => { + let prefix = + `Variable "$${varName}" got invalid value ` + + (0, _inspect.inspect)(invalidValue); - if (isIgnored(this, e)) - return + if (path.length > 0) { + prefix += ` at "${varName}${(0, _printPathArray.printPathArray)( + path, + )}"`; + } - if (this.paused) { - this._emitQueue.push([index, e]) - return + onError( + new _GraphQLError.GraphQLError(prefix + '; ' + error.message, { + nodes: varDefNode, + originalError: error, + }), + ); + }, + ); } - var abs = isAbsolute(e) ? e : this._makeAbs(e) - - if (this.mark) - e = this._mark(e) - - if (this.absolute) - e = abs - - if (this.matches[index][e]) - return + return coercedValues; +} +/** + * Prepares an object map of argument values given a list of argument + * definitions and list of argument AST nodes. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ - if (this.nodir) { - var c = this.cache[abs] - if (c === 'DIR' || Array.isArray(c)) - return - } +function getArgumentValues(def, node, variableValues) { + var _node$arguments; - this.matches[index][e] = true + const coercedValues = {}; // FIXME: https://github.com/graphql/graphql-js/issues/2203 - var st = this.statCache[abs] - if (st) - this.emit('stat', e, st) + /* c8 ignore next */ - this.emit('match', e) -} + const argumentNodes = + (_node$arguments = node.arguments) !== null && _node$arguments !== void 0 + ? _node$arguments + : []; + const argNodeMap = (0, _keyMap.keyMap)( + argumentNodes, + (arg) => arg.name.value, + ); -Glob.prototype._readdirInGlobStar = function (abs, cb) { - if (this.aborted) - return + for (const argDef of def.args) { + const name = argDef.name; + const argType = argDef.type; + const argumentNode = argNodeMap[name]; - // follow all symlinked directories forever - // just proceed as if this is a non-globstar situation - if (this.follow) - return this._readdir(abs, false, cb) + if (!argumentNode) { + if (argDef.defaultValue !== undefined) { + coercedValues[name] = argDef.defaultValue; + } else if ((0, _definition.isNonNullType)(argType)) { + throw new _GraphQLError.GraphQLError( + `Argument "${name}" of required type "${(0, _inspect.inspect)( + argType, + )}" ` + 'was not provided.', + { + nodes: node, + }, + ); + } - var lstatkey = 'lstat\0' + abs - var self = this - var lstatcb = inflight(lstatkey, lstatcb_) + continue; + } - if (lstatcb) - self.fs.lstat(abs, lstatcb) + const valueNode = argumentNode.value; + let isNull = valueNode.kind === _kinds.Kind.NULL; - function lstatcb_ (er, lstat) { - if (er && er.code === 'ENOENT') - return cb() + if (valueNode.kind === _kinds.Kind.VARIABLE) { + const variableName = valueNode.name.value; - var isSym = lstat && lstat.isSymbolicLink() - self.symlinks[abs] = isSym + if ( + variableValues == null || + !hasOwnProperty(variableValues, variableName) + ) { + if (argDef.defaultValue !== undefined) { + coercedValues[name] = argDef.defaultValue; + } else if ((0, _definition.isNonNullType)(argType)) { + throw new _GraphQLError.GraphQLError( + `Argument "${name}" of required type "${(0, _inspect.inspect)( + argType, + )}" ` + + `was provided the variable "$${variableName}" which was not provided a runtime value.`, + { + nodes: valueNode, + }, + ); + } - // If it's not a symlink or a dir, then it's definitely a regular file. - // don't bother doing a readdir in that case. - if (!isSym && lstat && !lstat.isDirectory()) { - self.cache[abs] = 'FILE' - cb() - } else - self._readdir(abs, false, cb) - } -} + continue; + } -Glob.prototype._readdir = function (abs, inGlobStar, cb) { - if (this.aborted) - return + isNull = variableValues[variableName] == null; + } - cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) - if (!cb) - return + if (isNull && (0, _definition.isNonNullType)(argType)) { + throw new _GraphQLError.GraphQLError( + `Argument "${name}" of non-null type "${(0, _inspect.inspect)( + argType, + )}" ` + 'must not be null.', + { + nodes: valueNode, + }, + ); + } - //console.error('RD %j %j', +inGlobStar, abs) - if (inGlobStar && !ownProp(this.symlinks, abs)) - return this._readdirInGlobStar(abs, cb) + const coercedValue = (0, _valueFromAST.valueFromAST)( + valueNode, + argType, + variableValues, + ); - if (ownProp(this.cache, abs)) { - var c = this.cache[abs] - if (!c || c === 'FILE') - return cb() + if (coercedValue === undefined) { + // Note: ValuesOfCorrectTypeRule validation should catch this before + // execution. This is a runtime check to ensure execution does not + // continue with an invalid argument value. + throw new _GraphQLError.GraphQLError( + `Argument "${name}" has invalid value ${(0, _printer.print)( + valueNode, + )}.`, + { + nodes: valueNode, + }, + ); + } - if (Array.isArray(c)) - return cb(null, c) + coercedValues[name] = coercedValue; } - var self = this - self.fs.readdir(abs, readdirCb(this, abs, cb)) + return coercedValues; } +/** + * Prepares an object map of argument values given a directive definition + * and a AST node which may contain directives. Optionally also accepts a map + * of variable values. + * + * If the directive does not exist on the node, returns undefined. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ -function readdirCb (self, abs, cb) { - return function (er, entries) { - if (er) - self._readdirError(abs, er, cb) - else - self._readdirEntries(abs, entries, cb) - } -} +function getDirectiveValues(directiveDef, node, variableValues) { + var _node$directives; -Glob.prototype._readdirEntries = function (abs, entries, cb) { - if (this.aborted) - return + const directiveNode = + (_node$directives = node.directives) === null || _node$directives === void 0 + ? void 0 + : _node$directives.find( + (directive) => directive.name.value === directiveDef.name, + ); - // if we haven't asked to stat everything, then just - // assume that everything in there exists, so we can avoid - // having to stat it a second time. - if (!this.mark && !this.stat) { - for (var i = 0; i < entries.length; i ++) { - var e = entries[i] - if (abs === '/') - e = abs + e - else - e = abs + '/' + e - this.cache[e] = true - } + if (directiveNode) { + return getArgumentValues(directiveDef, directiveNode, variableValues); } - - this.cache[abs] = entries - return cb(null, entries) } -Glob.prototype._readdirError = function (f, er, cb) { - if (this.aborted) - return +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} - // handle errors, and cache the information - switch (er.code) { - case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 - case 'ENOTDIR': // totally normal. means it *does* exist. - var abs = this._makeAbs(f) - this.cache[abs] = 'FILE' - if (abs === this.cwdAbs) { - var error = new Error(er.code + ' invalid cwd ' + this.cwd) - error.path = this.cwd - error.code = er.code - this.emit('error', error) - this.abort() - } - break - case 'ENOENT': // not terribly unusual - case 'ELOOP': - case 'ENAMETOOLONG': - case 'UNKNOWN': - this.cache[this._makeAbs(f)] = false - break +/***/ }), - default: // some unusual error. Treat as failure. - this.cache[this._makeAbs(f)] = false - if (this.strict) { - this.emit('error', er) - // If the error is handled, then we abort - // if not, we threw out of here - this.abort() - } - if (!this.silent) - console.error('glob error', er) - break - } +/***/ 64215: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return cb() -} +"use strict"; -Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { - var self = this - this._readdir(abs, inGlobStar, function (er, entries) { - self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) - }) -} +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.graphql = graphql; +exports.graphqlSync = graphqlSync; -Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { - //console.error('pgs2', prefix, remain[0], entries) +var _devAssert = __nccwpck_require__(46514); - // no entries means not a dir, so it can never have matches - // foo.txt/** doesn't match foo.txt - if (!entries) - return cb() +var _isPromise = __nccwpck_require__(93910); - // test without the globstar, and with every child both below - // and replacing the globstar. - var remainWithoutGlobStar = remain.slice(1) - var gspref = prefix ? [ prefix ] : [] - var noGlobStar = gspref.concat(remainWithoutGlobStar) +var _parser = __nccwpck_require__(50655); - // the noGlobStar pattern exits the inGlobStar state - this._process(noGlobStar, index, false, cb) +var _validate = __nccwpck_require__(22430); - var isSym = this.symlinks[abs] - var len = entries.length +var _validate2 = __nccwpck_require__(14193); - // If it's a symlink, and we're in a globstar, then stop - if (isSym && inGlobStar) - return cb() +var _execute = __nccwpck_require__(83677); - for (var i = 0; i < len; i++) { - var e = entries[i] - if (e.charAt(0) === '.' && !this.dot) - continue +function graphql(args) { + // Always return a Promise for a consistent API. + return new Promise((resolve) => resolve(graphqlImpl(args))); +} +/** + * The graphqlSync function also fulfills GraphQL operations by parsing, + * validating, and executing a GraphQL document along side a GraphQL schema. + * However, it guarantees to complete synchronously (or throw an error) assuming + * that all field resolvers are also synchronous. + */ - // these two cases enter the inGlobStar state - var instead = gspref.concat(entries[i], remainWithoutGlobStar) - this._process(instead, index, true, cb) +function graphqlSync(args) { + const result = graphqlImpl(args); // Assert that the execution was synchronous. - var below = gspref.concat(entries[i], remain) - this._process(below, index, true, cb) + if ((0, _isPromise.isPromise)(result)) { + throw new Error('GraphQL execution failed to complete synchronously.'); } - cb() -} - -Glob.prototype._processSimple = function (prefix, index, cb) { - // XXX review this. Shouldn't it be doing the mounting etc - // before doing stat? kinda weird? - var self = this - this._stat(prefix, function (er, exists) { - self._processSimple2(prefix, index, er, exists, cb) - }) + return result; } -Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { - //console.error('ps2', prefix, exists) +function graphqlImpl(args) { + // Temporary for v15 to v16 migration. Remove in v17 + arguments.length < 2 || + (0, _devAssert.devAssert)( + false, + 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.', + ); + const { + schema, + source, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + typeResolver, + } = args; // Validate Schema - if (!this.matches[index]) - this.matches[index] = Object.create(null) + const schemaValidationErrors = (0, _validate.validateSchema)(schema); - // If it doesn't exist, then just mark the lack of results - if (!exists) - return cb() + if (schemaValidationErrors.length > 0) { + return { + errors: schemaValidationErrors, + }; + } // Parse - if (prefix && isAbsolute(prefix) && !this.nomount) { - var trail = /[\/\\]$/.test(prefix) - if (prefix.charAt(0) === '/') { - prefix = path.join(this.root, prefix) - } else { - prefix = path.resolve(this.root, prefix) - if (trail) - prefix += '/' - } - } + let document; - if (process.platform === 'win32') - prefix = prefix.replace(/\\/g, '/') + try { + document = (0, _parser.parse)(source); + } catch (syntaxError) { + return { + errors: [syntaxError], + }; + } // Validate - // Mark this as a match - this._emitMatch(index, prefix) - cb() -} + const validationErrors = (0, _validate2.validate)(schema, document); -// Returns either 'DIR', 'FILE', or false -Glob.prototype._stat = function (f, cb) { - var abs = this._makeAbs(f) - var needDir = f.slice(-1) === '/' + if (validationErrors.length > 0) { + return { + errors: validationErrors, + }; + } // Execute - if (f.length > this.maxLength) - return cb() + return (0, _execute.execute)({ + schema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + typeResolver, + }); +} - if (!this.stat && ownProp(this.cache, abs)) { - var c = this.cache[abs] - if (Array.isArray(c)) - c = 'DIR' +/***/ }), - // It exists, but maybe not how we need it - if (!needDir || c === 'DIR') - return cb(null, c) +/***/ 16155: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (needDir && c === 'FILE') - return cb() +"use strict"; - // otherwise we have to stat, because maybe c=true - // if we know it exists, but not what it is. - } - var exists - var stat = this.statCache[abs] - if (stat !== undefined) { - if (stat === false) - return cb(null, stat) - else { - var type = stat.isDirectory() ? 'DIR' : 'FILE' - if (needDir && type === 'FILE') - return cb() - else - return cb(null, type, stat) - } - } +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +Object.defineProperty(exports, "BREAK", ({ + enumerable: true, + get: function () { + return _index2.BREAK; + }, +})); +Object.defineProperty(exports, "BreakingChangeType", ({ + enumerable: true, + get: function () { + return _index6.BreakingChangeType; + }, +})); +Object.defineProperty(exports, "DEFAULT_DEPRECATION_REASON", ({ + enumerable: true, + get: function () { + return _index.DEFAULT_DEPRECATION_REASON; + }, +})); +Object.defineProperty(exports, "DangerousChangeType", ({ + enumerable: true, + get: function () { + return _index6.DangerousChangeType; + }, +})); +Object.defineProperty(exports, "DirectiveLocation", ({ + enumerable: true, + get: function () { + return _index2.DirectiveLocation; + }, +})); +Object.defineProperty(exports, "ExecutableDefinitionsRule", ({ + enumerable: true, + get: function () { + return _index4.ExecutableDefinitionsRule; + }, +})); +Object.defineProperty(exports, "FieldsOnCorrectTypeRule", ({ + enumerable: true, + get: function () { + return _index4.FieldsOnCorrectTypeRule; + }, +})); +Object.defineProperty(exports, "FragmentsOnCompositeTypesRule", ({ + enumerable: true, + get: function () { + return _index4.FragmentsOnCompositeTypesRule; + }, +})); +Object.defineProperty(exports, "GRAPHQL_MAX_INT", ({ + enumerable: true, + get: function () { + return _index.GRAPHQL_MAX_INT; + }, +})); +Object.defineProperty(exports, "GRAPHQL_MIN_INT", ({ + enumerable: true, + get: function () { + return _index.GRAPHQL_MIN_INT; + }, +})); +Object.defineProperty(exports, "GraphQLBoolean", ({ + enumerable: true, + get: function () { + return _index.GraphQLBoolean; + }, +})); +Object.defineProperty(exports, "GraphQLDeprecatedDirective", ({ + enumerable: true, + get: function () { + return _index.GraphQLDeprecatedDirective; + }, +})); +Object.defineProperty(exports, "GraphQLDirective", ({ + enumerable: true, + get: function () { + return _index.GraphQLDirective; + }, +})); +Object.defineProperty(exports, "GraphQLEnumType", ({ + enumerable: true, + get: function () { + return _index.GraphQLEnumType; + }, +})); +Object.defineProperty(exports, "GraphQLError", ({ + enumerable: true, + get: function () { + return _index5.GraphQLError; + }, +})); +Object.defineProperty(exports, "GraphQLFloat", ({ + enumerable: true, + get: function () { + return _index.GraphQLFloat; + }, +})); +Object.defineProperty(exports, "GraphQLID", ({ + enumerable: true, + get: function () { + return _index.GraphQLID; + }, +})); +Object.defineProperty(exports, "GraphQLIncludeDirective", ({ + enumerable: true, + get: function () { + return _index.GraphQLIncludeDirective; + }, +})); +Object.defineProperty(exports, "GraphQLInputObjectType", ({ + enumerable: true, + get: function () { + return _index.GraphQLInputObjectType; + }, +})); +Object.defineProperty(exports, "GraphQLInt", ({ + enumerable: true, + get: function () { + return _index.GraphQLInt; + }, +})); +Object.defineProperty(exports, "GraphQLInterfaceType", ({ + enumerable: true, + get: function () { + return _index.GraphQLInterfaceType; + }, +})); +Object.defineProperty(exports, "GraphQLList", ({ + enumerable: true, + get: function () { + return _index.GraphQLList; + }, +})); +Object.defineProperty(exports, "GraphQLNonNull", ({ + enumerable: true, + get: function () { + return _index.GraphQLNonNull; + }, +})); +Object.defineProperty(exports, "GraphQLObjectType", ({ + enumerable: true, + get: function () { + return _index.GraphQLObjectType; + }, +})); +Object.defineProperty(exports, "GraphQLOneOfDirective", ({ + enumerable: true, + get: function () { + return _index.GraphQLOneOfDirective; + }, +})); +Object.defineProperty(exports, "GraphQLScalarType", ({ + enumerable: true, + get: function () { + return _index.GraphQLScalarType; + }, +})); +Object.defineProperty(exports, "GraphQLSchema", ({ + enumerable: true, + get: function () { + return _index.GraphQLSchema; + }, +})); +Object.defineProperty(exports, "GraphQLSkipDirective", ({ + enumerable: true, + get: function () { + return _index.GraphQLSkipDirective; + }, +})); +Object.defineProperty(exports, "GraphQLSpecifiedByDirective", ({ + enumerable: true, + get: function () { + return _index.GraphQLSpecifiedByDirective; + }, +})); +Object.defineProperty(exports, "GraphQLString", ({ + enumerable: true, + get: function () { + return _index.GraphQLString; + }, +})); +Object.defineProperty(exports, "GraphQLUnionType", ({ + enumerable: true, + get: function () { + return _index.GraphQLUnionType; + }, +})); +Object.defineProperty(exports, "Kind", ({ + enumerable: true, + get: function () { + return _index2.Kind; + }, +})); +Object.defineProperty(exports, "KnownArgumentNamesRule", ({ + enumerable: true, + get: function () { + return _index4.KnownArgumentNamesRule; + }, +})); +Object.defineProperty(exports, "KnownDirectivesRule", ({ + enumerable: true, + get: function () { + return _index4.KnownDirectivesRule; + }, +})); +Object.defineProperty(exports, "KnownFragmentNamesRule", ({ + enumerable: true, + get: function () { + return _index4.KnownFragmentNamesRule; + }, +})); +Object.defineProperty(exports, "KnownTypeNamesRule", ({ + enumerable: true, + get: function () { + return _index4.KnownTypeNamesRule; + }, +})); +Object.defineProperty(exports, "Lexer", ({ + enumerable: true, + get: function () { + return _index2.Lexer; + }, +})); +Object.defineProperty(exports, "Location", ({ + enumerable: true, + get: function () { + return _index2.Location; + }, +})); +Object.defineProperty(exports, "LoneAnonymousOperationRule", ({ + enumerable: true, + get: function () { + return _index4.LoneAnonymousOperationRule; + }, +})); +Object.defineProperty(exports, "LoneSchemaDefinitionRule", ({ + enumerable: true, + get: function () { + return _index4.LoneSchemaDefinitionRule; + }, +})); +Object.defineProperty(exports, "MaxIntrospectionDepthRule", ({ + enumerable: true, + get: function () { + return _index4.MaxIntrospectionDepthRule; + }, +})); +Object.defineProperty(exports, "NoDeprecatedCustomRule", ({ + enumerable: true, + get: function () { + return _index4.NoDeprecatedCustomRule; + }, +})); +Object.defineProperty(exports, "NoFragmentCyclesRule", ({ + enumerable: true, + get: function () { + return _index4.NoFragmentCyclesRule; + }, +})); +Object.defineProperty(exports, "NoSchemaIntrospectionCustomRule", ({ + enumerable: true, + get: function () { + return _index4.NoSchemaIntrospectionCustomRule; + }, +})); +Object.defineProperty(exports, "NoUndefinedVariablesRule", ({ + enumerable: true, + get: function () { + return _index4.NoUndefinedVariablesRule; + }, +})); +Object.defineProperty(exports, "NoUnusedFragmentsRule", ({ + enumerable: true, + get: function () { + return _index4.NoUnusedFragmentsRule; + }, +})); +Object.defineProperty(exports, "NoUnusedVariablesRule", ({ + enumerable: true, + get: function () { + return _index4.NoUnusedVariablesRule; + }, +})); +Object.defineProperty(exports, "OperationTypeNode", ({ + enumerable: true, + get: function () { + return _index2.OperationTypeNode; + }, +})); +Object.defineProperty(exports, "OverlappingFieldsCanBeMergedRule", ({ + enumerable: true, + get: function () { + return _index4.OverlappingFieldsCanBeMergedRule; + }, +})); +Object.defineProperty(exports, "PossibleFragmentSpreadsRule", ({ + enumerable: true, + get: function () { + return _index4.PossibleFragmentSpreadsRule; + }, +})); +Object.defineProperty(exports, "PossibleTypeExtensionsRule", ({ + enumerable: true, + get: function () { + return _index4.PossibleTypeExtensionsRule; + }, +})); +Object.defineProperty(exports, "ProvidedRequiredArgumentsRule", ({ + enumerable: true, + get: function () { + return _index4.ProvidedRequiredArgumentsRule; + }, +})); +Object.defineProperty(exports, "ScalarLeafsRule", ({ + enumerable: true, + get: function () { + return _index4.ScalarLeafsRule; + }, +})); +Object.defineProperty(exports, "SchemaMetaFieldDef", ({ + enumerable: true, + get: function () { + return _index.SchemaMetaFieldDef; + }, +})); +Object.defineProperty(exports, "SingleFieldSubscriptionsRule", ({ + enumerable: true, + get: function () { + return _index4.SingleFieldSubscriptionsRule; + }, +})); +Object.defineProperty(exports, "Source", ({ + enumerable: true, + get: function () { + return _index2.Source; + }, +})); +Object.defineProperty(exports, "Token", ({ + enumerable: true, + get: function () { + return _index2.Token; + }, +})); +Object.defineProperty(exports, "TokenKind", ({ + enumerable: true, + get: function () { + return _index2.TokenKind; + }, +})); +Object.defineProperty(exports, "TypeInfo", ({ + enumerable: true, + get: function () { + return _index6.TypeInfo; + }, +})); +Object.defineProperty(exports, "TypeKind", ({ + enumerable: true, + get: function () { + return _index.TypeKind; + }, +})); +Object.defineProperty(exports, "TypeMetaFieldDef", ({ + enumerable: true, + get: function () { + return _index.TypeMetaFieldDef; + }, +})); +Object.defineProperty(exports, "TypeNameMetaFieldDef", ({ + enumerable: true, + get: function () { + return _index.TypeNameMetaFieldDef; + }, +})); +Object.defineProperty(exports, "UniqueArgumentDefinitionNamesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueArgumentDefinitionNamesRule; + }, +})); +Object.defineProperty(exports, "UniqueArgumentNamesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueArgumentNamesRule; + }, +})); +Object.defineProperty(exports, "UniqueDirectiveNamesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueDirectiveNamesRule; + }, +})); +Object.defineProperty(exports, "UniqueDirectivesPerLocationRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueDirectivesPerLocationRule; + }, +})); +Object.defineProperty(exports, "UniqueEnumValueNamesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueEnumValueNamesRule; + }, +})); +Object.defineProperty(exports, "UniqueFieldDefinitionNamesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueFieldDefinitionNamesRule; + }, +})); +Object.defineProperty(exports, "UniqueFragmentNamesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueFragmentNamesRule; + }, +})); +Object.defineProperty(exports, "UniqueInputFieldNamesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueInputFieldNamesRule; + }, +})); +Object.defineProperty(exports, "UniqueOperationNamesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueOperationNamesRule; + }, +})); +Object.defineProperty(exports, "UniqueOperationTypesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueOperationTypesRule; + }, +})); +Object.defineProperty(exports, "UniqueTypeNamesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueTypeNamesRule; + }, +})); +Object.defineProperty(exports, "UniqueVariableNamesRule", ({ + enumerable: true, + get: function () { + return _index4.UniqueVariableNamesRule; + }, +})); +Object.defineProperty(exports, "ValidationContext", ({ + enumerable: true, + get: function () { + return _index4.ValidationContext; + }, +})); +Object.defineProperty(exports, "ValuesOfCorrectTypeRule", ({ + enumerable: true, + get: function () { + return _index4.ValuesOfCorrectTypeRule; + }, +})); +Object.defineProperty(exports, "VariablesAreInputTypesRule", ({ + enumerable: true, + get: function () { + return _index4.VariablesAreInputTypesRule; + }, +})); +Object.defineProperty(exports, "VariablesInAllowedPositionRule", ({ + enumerable: true, + get: function () { + return _index4.VariablesInAllowedPositionRule; + }, +})); +Object.defineProperty(exports, "__Directive", ({ + enumerable: true, + get: function () { + return _index.__Directive; + }, +})); +Object.defineProperty(exports, "__DirectiveLocation", ({ + enumerable: true, + get: function () { + return _index.__DirectiveLocation; + }, +})); +Object.defineProperty(exports, "__EnumValue", ({ + enumerable: true, + get: function () { + return _index.__EnumValue; + }, +})); +Object.defineProperty(exports, "__Field", ({ + enumerable: true, + get: function () { + return _index.__Field; + }, +})); +Object.defineProperty(exports, "__InputValue", ({ + enumerable: true, + get: function () { + return _index.__InputValue; + }, +})); +Object.defineProperty(exports, "__Schema", ({ + enumerable: true, + get: function () { + return _index.__Schema; + }, +})); +Object.defineProperty(exports, "__Type", ({ + enumerable: true, + get: function () { + return _index.__Type; + }, +})); +Object.defineProperty(exports, "__TypeKind", ({ + enumerable: true, + get: function () { + return _index.__TypeKind; + }, +})); +Object.defineProperty(exports, "assertAbstractType", ({ + enumerable: true, + get: function () { + return _index.assertAbstractType; + }, +})); +Object.defineProperty(exports, "assertCompositeType", ({ + enumerable: true, + get: function () { + return _index.assertCompositeType; + }, +})); +Object.defineProperty(exports, "assertDirective", ({ + enumerable: true, + get: function () { + return _index.assertDirective; + }, +})); +Object.defineProperty(exports, "assertEnumType", ({ + enumerable: true, + get: function () { + return _index.assertEnumType; + }, +})); +Object.defineProperty(exports, "assertEnumValueName", ({ + enumerable: true, + get: function () { + return _index.assertEnumValueName; + }, +})); +Object.defineProperty(exports, "assertInputObjectType", ({ + enumerable: true, + get: function () { + return _index.assertInputObjectType; + }, +})); +Object.defineProperty(exports, "assertInputType", ({ + enumerable: true, + get: function () { + return _index.assertInputType; + }, +})); +Object.defineProperty(exports, "assertInterfaceType", ({ + enumerable: true, + get: function () { + return _index.assertInterfaceType; + }, +})); +Object.defineProperty(exports, "assertLeafType", ({ + enumerable: true, + get: function () { + return _index.assertLeafType; + }, +})); +Object.defineProperty(exports, "assertListType", ({ + enumerable: true, + get: function () { + return _index.assertListType; + }, +})); +Object.defineProperty(exports, "assertName", ({ + enumerable: true, + get: function () { + return _index.assertName; + }, +})); +Object.defineProperty(exports, "assertNamedType", ({ + enumerable: true, + get: function () { + return _index.assertNamedType; + }, +})); +Object.defineProperty(exports, "assertNonNullType", ({ + enumerable: true, + get: function () { + return _index.assertNonNullType; + }, +})); +Object.defineProperty(exports, "assertNullableType", ({ + enumerable: true, + get: function () { + return _index.assertNullableType; + }, +})); +Object.defineProperty(exports, "assertObjectType", ({ + enumerable: true, + get: function () { + return _index.assertObjectType; + }, +})); +Object.defineProperty(exports, "assertOutputType", ({ + enumerable: true, + get: function () { + return _index.assertOutputType; + }, +})); +Object.defineProperty(exports, "assertScalarType", ({ + enumerable: true, + get: function () { + return _index.assertScalarType; + }, +})); +Object.defineProperty(exports, "assertSchema", ({ + enumerable: true, + get: function () { + return _index.assertSchema; + }, +})); +Object.defineProperty(exports, "assertType", ({ + enumerable: true, + get: function () { + return _index.assertType; + }, +})); +Object.defineProperty(exports, "assertUnionType", ({ + enumerable: true, + get: function () { + return _index.assertUnionType; + }, +})); +Object.defineProperty(exports, "assertValidName", ({ + enumerable: true, + get: function () { + return _index6.assertValidName; + }, +})); +Object.defineProperty(exports, "assertValidSchema", ({ + enumerable: true, + get: function () { + return _index.assertValidSchema; + }, +})); +Object.defineProperty(exports, "assertWrappingType", ({ + enumerable: true, + get: function () { + return _index.assertWrappingType; + }, +})); +Object.defineProperty(exports, "astFromValue", ({ + enumerable: true, + get: function () { + return _index6.astFromValue; + }, +})); +Object.defineProperty(exports, "buildASTSchema", ({ + enumerable: true, + get: function () { + return _index6.buildASTSchema; + }, +})); +Object.defineProperty(exports, "buildClientSchema", ({ + enumerable: true, + get: function () { + return _index6.buildClientSchema; + }, +})); +Object.defineProperty(exports, "buildSchema", ({ + enumerable: true, + get: function () { + return _index6.buildSchema; + }, +})); +Object.defineProperty(exports, "coerceInputValue", ({ + enumerable: true, + get: function () { + return _index6.coerceInputValue; + }, +})); +Object.defineProperty(exports, "concatAST", ({ + enumerable: true, + get: function () { + return _index6.concatAST; + }, +})); +Object.defineProperty(exports, "createSourceEventStream", ({ + enumerable: true, + get: function () { + return _index3.createSourceEventStream; + }, +})); +Object.defineProperty(exports, "defaultFieldResolver", ({ + enumerable: true, + get: function () { + return _index3.defaultFieldResolver; + }, +})); +Object.defineProperty(exports, "defaultTypeResolver", ({ + enumerable: true, + get: function () { + return _index3.defaultTypeResolver; + }, +})); +Object.defineProperty(exports, "doTypesOverlap", ({ + enumerable: true, + get: function () { + return _index6.doTypesOverlap; + }, +})); +Object.defineProperty(exports, "execute", ({ + enumerable: true, + get: function () { + return _index3.execute; + }, +})); +Object.defineProperty(exports, "executeSync", ({ + enumerable: true, + get: function () { + return _index3.executeSync; + }, +})); +Object.defineProperty(exports, "extendSchema", ({ + enumerable: true, + get: function () { + return _index6.extendSchema; + }, +})); +Object.defineProperty(exports, "findBreakingChanges", ({ + enumerable: true, + get: function () { + return _index6.findBreakingChanges; + }, +})); +Object.defineProperty(exports, "findDangerousChanges", ({ + enumerable: true, + get: function () { + return _index6.findDangerousChanges; + }, +})); +Object.defineProperty(exports, "formatError", ({ + enumerable: true, + get: function () { + return _index5.formatError; + }, +})); +Object.defineProperty(exports, "getArgumentValues", ({ + enumerable: true, + get: function () { + return _index3.getArgumentValues; + }, +})); +Object.defineProperty(exports, "getDirectiveValues", ({ + enumerable: true, + get: function () { + return _index3.getDirectiveValues; + }, +})); +Object.defineProperty(exports, "getEnterLeaveForKind", ({ + enumerable: true, + get: function () { + return _index2.getEnterLeaveForKind; + }, +})); +Object.defineProperty(exports, "getIntrospectionQuery", ({ + enumerable: true, + get: function () { + return _index6.getIntrospectionQuery; + }, +})); +Object.defineProperty(exports, "getLocation", ({ + enumerable: true, + get: function () { + return _index2.getLocation; + }, +})); +Object.defineProperty(exports, "getNamedType", ({ + enumerable: true, + get: function () { + return _index.getNamedType; + }, +})); +Object.defineProperty(exports, "getNullableType", ({ + enumerable: true, + get: function () { + return _index.getNullableType; + }, +})); +Object.defineProperty(exports, "getOperationAST", ({ + enumerable: true, + get: function () { + return _index6.getOperationAST; + }, +})); +Object.defineProperty(exports, "getOperationRootType", ({ + enumerable: true, + get: function () { + return _index6.getOperationRootType; + }, +})); +Object.defineProperty(exports, "getVariableValues", ({ + enumerable: true, + get: function () { + return _index3.getVariableValues; + }, +})); +Object.defineProperty(exports, "getVisitFn", ({ + enumerable: true, + get: function () { + return _index2.getVisitFn; + }, +})); +Object.defineProperty(exports, "graphql", ({ + enumerable: true, + get: function () { + return _graphql.graphql; + }, +})); +Object.defineProperty(exports, "graphqlSync", ({ + enumerable: true, + get: function () { + return _graphql.graphqlSync; + }, +})); +Object.defineProperty(exports, "introspectionFromSchema", ({ + enumerable: true, + get: function () { + return _index6.introspectionFromSchema; + }, +})); +Object.defineProperty(exports, "introspectionTypes", ({ + enumerable: true, + get: function () { + return _index.introspectionTypes; + }, +})); +Object.defineProperty(exports, "isAbstractType", ({ + enumerable: true, + get: function () { + return _index.isAbstractType; + }, +})); +Object.defineProperty(exports, "isCompositeType", ({ + enumerable: true, + get: function () { + return _index.isCompositeType; + }, +})); +Object.defineProperty(exports, "isConstValueNode", ({ + enumerable: true, + get: function () { + return _index2.isConstValueNode; + }, +})); +Object.defineProperty(exports, "isDefinitionNode", ({ + enumerable: true, + get: function () { + return _index2.isDefinitionNode; + }, +})); +Object.defineProperty(exports, "isDirective", ({ + enumerable: true, + get: function () { + return _index.isDirective; + }, +})); +Object.defineProperty(exports, "isEnumType", ({ + enumerable: true, + get: function () { + return _index.isEnumType; + }, +})); +Object.defineProperty(exports, "isEqualType", ({ + enumerable: true, + get: function () { + return _index6.isEqualType; + }, +})); +Object.defineProperty(exports, "isExecutableDefinitionNode", ({ + enumerable: true, + get: function () { + return _index2.isExecutableDefinitionNode; + }, +})); +Object.defineProperty(exports, "isInputObjectType", ({ + enumerable: true, + get: function () { + return _index.isInputObjectType; + }, +})); +Object.defineProperty(exports, "isInputType", ({ + enumerable: true, + get: function () { + return _index.isInputType; + }, +})); +Object.defineProperty(exports, "isInterfaceType", ({ + enumerable: true, + get: function () { + return _index.isInterfaceType; + }, +})); +Object.defineProperty(exports, "isIntrospectionType", ({ + enumerable: true, + get: function () { + return _index.isIntrospectionType; + }, +})); +Object.defineProperty(exports, "isLeafType", ({ + enumerable: true, + get: function () { + return _index.isLeafType; + }, +})); +Object.defineProperty(exports, "isListType", ({ + enumerable: true, + get: function () { + return _index.isListType; + }, +})); +Object.defineProperty(exports, "isNamedType", ({ + enumerable: true, + get: function () { + return _index.isNamedType; + }, +})); +Object.defineProperty(exports, "isNonNullType", ({ + enumerable: true, + get: function () { + return _index.isNonNullType; + }, +})); +Object.defineProperty(exports, "isNullableType", ({ + enumerable: true, + get: function () { + return _index.isNullableType; + }, +})); +Object.defineProperty(exports, "isObjectType", ({ + enumerable: true, + get: function () { + return _index.isObjectType; + }, +})); +Object.defineProperty(exports, "isOutputType", ({ + enumerable: true, + get: function () { + return _index.isOutputType; + }, +})); +Object.defineProperty(exports, "isRequiredArgument", ({ + enumerable: true, + get: function () { + return _index.isRequiredArgument; + }, +})); +Object.defineProperty(exports, "isRequiredInputField", ({ + enumerable: true, + get: function () { + return _index.isRequiredInputField; + }, +})); +Object.defineProperty(exports, "isScalarType", ({ + enumerable: true, + get: function () { + return _index.isScalarType; + }, +})); +Object.defineProperty(exports, "isSchema", ({ + enumerable: true, + get: function () { + return _index.isSchema; + }, +})); +Object.defineProperty(exports, "isSelectionNode", ({ + enumerable: true, + get: function () { + return _index2.isSelectionNode; + }, +})); +Object.defineProperty(exports, "isSpecifiedDirective", ({ + enumerable: true, + get: function () { + return _index.isSpecifiedDirective; + }, +})); +Object.defineProperty(exports, "isSpecifiedScalarType", ({ + enumerable: true, + get: function () { + return _index.isSpecifiedScalarType; + }, +})); +Object.defineProperty(exports, "isType", ({ + enumerable: true, + get: function () { + return _index.isType; + }, +})); +Object.defineProperty(exports, "isTypeDefinitionNode", ({ + enumerable: true, + get: function () { + return _index2.isTypeDefinitionNode; + }, +})); +Object.defineProperty(exports, "isTypeExtensionNode", ({ + enumerable: true, + get: function () { + return _index2.isTypeExtensionNode; + }, +})); +Object.defineProperty(exports, "isTypeNode", ({ + enumerable: true, + get: function () { + return _index2.isTypeNode; + }, +})); +Object.defineProperty(exports, "isTypeSubTypeOf", ({ + enumerable: true, + get: function () { + return _index6.isTypeSubTypeOf; + }, +})); +Object.defineProperty(exports, "isTypeSystemDefinitionNode", ({ + enumerable: true, + get: function () { + return _index2.isTypeSystemDefinitionNode; + }, +})); +Object.defineProperty(exports, "isTypeSystemExtensionNode", ({ + enumerable: true, + get: function () { + return _index2.isTypeSystemExtensionNode; + }, +})); +Object.defineProperty(exports, "isUnionType", ({ + enumerable: true, + get: function () { + return _index.isUnionType; + }, +})); +Object.defineProperty(exports, "isValidNameError", ({ + enumerable: true, + get: function () { + return _index6.isValidNameError; + }, +})); +Object.defineProperty(exports, "isValueNode", ({ + enumerable: true, + get: function () { + return _index2.isValueNode; + }, +})); +Object.defineProperty(exports, "isWrappingType", ({ + enumerable: true, + get: function () { + return _index.isWrappingType; + }, +})); +Object.defineProperty(exports, "lexicographicSortSchema", ({ + enumerable: true, + get: function () { + return _index6.lexicographicSortSchema; + }, +})); +Object.defineProperty(exports, "locatedError", ({ + enumerable: true, + get: function () { + return _index5.locatedError; + }, +})); +Object.defineProperty(exports, "parse", ({ + enumerable: true, + get: function () { + return _index2.parse; + }, +})); +Object.defineProperty(exports, "parseConstValue", ({ + enumerable: true, + get: function () { + return _index2.parseConstValue; + }, +})); +Object.defineProperty(exports, "parseType", ({ + enumerable: true, + get: function () { + return _index2.parseType; + }, +})); +Object.defineProperty(exports, "parseValue", ({ + enumerable: true, + get: function () { + return _index2.parseValue; + }, +})); +Object.defineProperty(exports, "print", ({ + enumerable: true, + get: function () { + return _index2.print; + }, +})); +Object.defineProperty(exports, "printError", ({ + enumerable: true, + get: function () { + return _index5.printError; + }, +})); +Object.defineProperty(exports, "printIntrospectionSchema", ({ + enumerable: true, + get: function () { + return _index6.printIntrospectionSchema; + }, +})); +Object.defineProperty(exports, "printLocation", ({ + enumerable: true, + get: function () { + return _index2.printLocation; + }, +})); +Object.defineProperty(exports, "printSchema", ({ + enumerable: true, + get: function () { + return _index6.printSchema; + }, +})); +Object.defineProperty(exports, "printSourceLocation", ({ + enumerable: true, + get: function () { + return _index2.printSourceLocation; + }, +})); +Object.defineProperty(exports, "printType", ({ + enumerable: true, + get: function () { + return _index6.printType; + }, +})); +Object.defineProperty(exports, "recommendedRules", ({ + enumerable: true, + get: function () { + return _index4.recommendedRules; + }, +})); +Object.defineProperty(exports, "resolveObjMapThunk", ({ + enumerable: true, + get: function () { + return _index.resolveObjMapThunk; + }, +})); +Object.defineProperty(exports, "resolveReadonlyArrayThunk", ({ + enumerable: true, + get: function () { + return _index.resolveReadonlyArrayThunk; + }, +})); +Object.defineProperty(exports, "responsePathAsArray", ({ + enumerable: true, + get: function () { + return _index3.responsePathAsArray; + }, +})); +Object.defineProperty(exports, "separateOperations", ({ + enumerable: true, + get: function () { + return _index6.separateOperations; + }, +})); +Object.defineProperty(exports, "specifiedDirectives", ({ + enumerable: true, + get: function () { + return _index.specifiedDirectives; + }, +})); +Object.defineProperty(exports, "specifiedRules", ({ + enumerable: true, + get: function () { + return _index4.specifiedRules; + }, +})); +Object.defineProperty(exports, "specifiedScalarTypes", ({ + enumerable: true, + get: function () { + return _index.specifiedScalarTypes; + }, +})); +Object.defineProperty(exports, "stripIgnoredCharacters", ({ + enumerable: true, + get: function () { + return _index6.stripIgnoredCharacters; + }, +})); +Object.defineProperty(exports, "subscribe", ({ + enumerable: true, + get: function () { + return _index3.subscribe; + }, +})); +Object.defineProperty(exports, "syntaxError", ({ + enumerable: true, + get: function () { + return _index5.syntaxError; + }, +})); +Object.defineProperty(exports, "typeFromAST", ({ + enumerable: true, + get: function () { + return _index6.typeFromAST; + }, +})); +Object.defineProperty(exports, "validate", ({ + enumerable: true, + get: function () { + return _index4.validate; + }, +})); +Object.defineProperty(exports, "validateSchema", ({ + enumerable: true, + get: function () { + return _index.validateSchema; + }, +})); +Object.defineProperty(exports, "valueFromAST", ({ + enumerable: true, + get: function () { + return _index6.valueFromAST; + }, +})); +Object.defineProperty(exports, "valueFromASTUntyped", ({ + enumerable: true, + get: function () { + return _index6.valueFromASTUntyped; + }, +})); +Object.defineProperty(exports, "version", ({ + enumerable: true, + get: function () { + return _version.version; + }, +})); +Object.defineProperty(exports, "versionInfo", ({ + enumerable: true, + get: function () { + return _version.versionInfo; + }, +})); +Object.defineProperty(exports, "visit", ({ + enumerable: true, + get: function () { + return _index2.visit; + }, +})); +Object.defineProperty(exports, "visitInParallel", ({ + enumerable: true, + get: function () { + return _index2.visitInParallel; + }, +})); +Object.defineProperty(exports, "visitWithTypeInfo", ({ + enumerable: true, + get: function () { + return _index6.visitWithTypeInfo; + }, +})); - var self = this - var statcb = inflight('stat\0' + abs, lstatcb_) - if (statcb) - self.fs.lstat(abs, statcb) +var _version = __nccwpck_require__(81923); - function lstatcb_ (er, lstat) { - if (lstat && lstat.isSymbolicLink()) { - // If it's a symlink, then treat it as the target, unless - // the target does not exist, then treat it as a file. - return self.fs.stat(abs, function (er, stat) { - if (er) - self._stat2(f, abs, null, lstat, cb) - else - self._stat2(f, abs, er, stat, cb) - }) - } else { - self._stat2(f, abs, er, lstat, cb) - } - } -} +var _graphql = __nccwpck_require__(64215); -Glob.prototype._stat2 = function (f, abs, er, stat, cb) { - if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { - this.statCache[abs] = false - return cb() - } +var _index = __nccwpck_require__(63280); - var needDir = f.slice(-1) === '/' - this.statCache[abs] = stat +var _index2 = __nccwpck_require__(89537); - if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) - return cb(null, false, stat) +var _index3 = __nccwpck_require__(13176); - var c = true - if (stat) - c = stat.isDirectory() ? 'DIR' : 'FILE' - this.cache[abs] = this.cache[abs] || c +var _index4 = __nccwpck_require__(82201); - if (needDir && c === 'FILE') - return cb() +var _index5 = __nccwpck_require__(50578); - return cb(null, c, stat) -} +var _index6 = __nccwpck_require__(676); /***/ }), -/***/ 29010: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = globSync -globSync.GlobSync = GlobSync - -var rp = __nccwpck_require__(46863) -var minimatch = __nccwpck_require__(83973) -var Minimatch = minimatch.Minimatch -var Glob = (__nccwpck_require__(91957).Glob) -var util = __nccwpck_require__(73837) -var path = __nccwpck_require__(71017) -var assert = __nccwpck_require__(39491) -var isAbsolute = __nccwpck_require__(38714) -var common = __nccwpck_require__(47625) -var setopts = common.setopts -var ownProp = common.ownProp -var childrenIgnored = common.childrenIgnored -var isIgnored = common.isIgnored - -function globSync (pattern, options) { - if (typeof options === 'function' || arguments.length === 3) - throw new TypeError('callback provided to sync glob\n'+ - 'See: https://github.com/isaacs/node-glob/issues/167') - - return new GlobSync(pattern, options).found -} - -function GlobSync (pattern, options) { - if (!pattern) - throw new Error('must provide pattern') - - if (typeof options === 'function' || arguments.length === 3) - throw new TypeError('callback provided to sync glob\n'+ - 'See: https://github.com/isaacs/node-glob/issues/167') - - if (!(this instanceof GlobSync)) - return new GlobSync(pattern, options) - - setopts(this, pattern, options) - - if (this.noprocess) - return this - - var n = this.minimatch.set.length - this.matches = new Array(n) - for (var i = 0; i < n; i ++) { - this._process(this.minimatch.set[i], i, false) - } - this._finish() -} - -GlobSync.prototype._finish = function () { - assert.ok(this instanceof GlobSync) - if (this.realpath) { - var self = this - this.matches.forEach(function (matchset, index) { - var set = self.matches[index] = Object.create(null) - for (var p in matchset) { - try { - p = self._makeAbs(p) - var real = rp.realpathSync(p, self.realpathCache) - set[real] = true - } catch (er) { - if (er.syscall === 'stat') - set[self._makeAbs(p)] = true - else - throw er - } - } - }) - } - common.finish(this) -} - - -GlobSync.prototype._process = function (pattern, index, inGlobStar) { - assert.ok(this instanceof GlobSync) - - // Get the first [n] parts of pattern that are all strings. - var n = 0 - while (typeof pattern[n] === 'string') { - n ++ - } - // now n is the index of the first one that is *not* a string. - - // See if there's anything else - var prefix - switch (n) { - // if not, then this is rather simple - case pattern.length: - this._processSimple(pattern.join('/'), index) - return - - case 0: - // pattern *starts* with some non-trivial item. - // going to readdir(cwd), but not include the prefix in matches. - prefix = null - break - - default: - // pattern has some string bits in the front. - // whatever it starts with, whether that's 'absolute' like /foo/bar, - // or 'relative' like '../baz' - prefix = pattern.slice(0, n).join('/') - break - } - - var remain = pattern.slice(n) - - // get the list of entries. - var read - if (prefix === null) - read = '.' - else if (isAbsolute(prefix) || - isAbsolute(pattern.map(function (p) { - return typeof p === 'string' ? p : '[*]' - }).join('/'))) { - if (!prefix || !isAbsolute(prefix)) - prefix = '/' + prefix - read = prefix - } else - read = prefix - - var abs = this._makeAbs(read) - - //if ignored, skip processing - if (childrenIgnored(this, read)) - return - - var isGlobStar = remain[0] === minimatch.GLOBSTAR - if (isGlobStar) - this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) - else - this._processReaddir(prefix, read, abs, remain, index, inGlobStar) -} - - -GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { - var entries = this._readdir(abs, inGlobStar) - - // if the abs isn't a dir, then nothing can match! - if (!entries) - return - - // It will only match dot entries if it starts with a dot, or if - // dot is set. Stuff like @(.foo|.bar) isn't allowed. - var pn = remain[0] - var negate = !!this.minimatch.negate - var rawGlob = pn._glob - var dotOk = this.dot || rawGlob.charAt(0) === '.' - - var matchedEntries = [] - for (var i = 0; i < entries.length; i++) { - var e = entries[i] - if (e.charAt(0) !== '.' || dotOk) { - var m - if (negate && !prefix) { - m = !e.match(pn) - } else { - m = e.match(pn) - } - if (m) - matchedEntries.push(e) - } - } - - var len = matchedEntries.length - // If there are no matched entries, then nothing matches. - if (len === 0) - return - - // if this is the last remaining pattern bit, then no need for - // an additional stat *unless* the user has specified mark or - // stat explicitly. We know they exist, since readdir returned - // them. - - if (remain.length === 1 && !this.mark && !this.stat) { - if (!this.matches[index]) - this.matches[index] = Object.create(null) - - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - if (prefix) { - if (prefix.slice(-1) !== '/') - e = prefix + '/' + e - else - e = prefix + e - } - - if (e.charAt(0) === '/' && !this.nomount) { - e = path.join(this.root, e) - } - this._emitMatch(index, e) - } - // This was the last one, and no stats were needed - return - } - - // now test all matched entries as stand-ins for that part - // of the pattern. - remain.shift() - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - var newPattern - if (prefix) - newPattern = [prefix, e] - else - newPattern = [e] - this._process(newPattern.concat(remain), index, inGlobStar) - } -} - - -GlobSync.prototype._emitMatch = function (index, e) { - if (isIgnored(this, e)) - return - - var abs = this._makeAbs(e) - - if (this.mark) - e = this._mark(e) - - if (this.absolute) { - e = abs - } - - if (this.matches[index][e]) - return - - if (this.nodir) { - var c = this.cache[abs] - if (c === 'DIR' || Array.isArray(c)) - return - } - - this.matches[index][e] = true - - if (this.stat) - this._stat(e) -} - - -GlobSync.prototype._readdirInGlobStar = function (abs) { - // follow all symlinked directories forever - // just proceed as if this is a non-globstar situation - if (this.follow) - return this._readdir(abs, false) - - var entries - var lstat - var stat - try { - lstat = this.fs.lstatSync(abs) - } catch (er) { - if (er.code === 'ENOENT') { - // lstat failed, doesn't exist - return null - } - } - - var isSym = lstat && lstat.isSymbolicLink() - this.symlinks[abs] = isSym - - // If it's not a symlink or a dir, then it's definitely a regular file. - // don't bother doing a readdir in that case. - if (!isSym && lstat && !lstat.isDirectory()) - this.cache[abs] = 'FILE' - else - entries = this._readdir(abs, false) - - return entries -} - -GlobSync.prototype._readdir = function (abs, inGlobStar) { - var entries - - if (inGlobStar && !ownProp(this.symlinks, abs)) - return this._readdirInGlobStar(abs) - - if (ownProp(this.cache, abs)) { - var c = this.cache[abs] - if (!c || c === 'FILE') - return null - - if (Array.isArray(c)) - return c - } - - try { - return this._readdirEntries(abs, this.fs.readdirSync(abs)) - } catch (er) { - this._readdirError(abs, er) - return null - } -} - -GlobSync.prototype._readdirEntries = function (abs, entries) { - // if we haven't asked to stat everything, then just - // assume that everything in there exists, so we can avoid - // having to stat it a second time. - if (!this.mark && !this.stat) { - for (var i = 0; i < entries.length; i ++) { - var e = entries[i] - if (abs === '/') - e = abs + e - else - e = abs + '/' + e - this.cache[e] = true - } - } - - this.cache[abs] = entries - - // mark and cache dir-ness - return entries -} - -GlobSync.prototype._readdirError = function (f, er) { - // handle errors, and cache the information - switch (er.code) { - case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 - case 'ENOTDIR': // totally normal. means it *does* exist. - var abs = this._makeAbs(f) - this.cache[abs] = 'FILE' - if (abs === this.cwdAbs) { - var error = new Error(er.code + ' invalid cwd ' + this.cwd) - error.path = this.cwd - error.code = er.code - throw error - } - break - - case 'ENOENT': // not terribly unusual - case 'ELOOP': - case 'ENAMETOOLONG': - case 'UNKNOWN': - this.cache[this._makeAbs(f)] = false - break - - default: // some unusual error. Treat as failure. - this.cache[this._makeAbs(f)] = false - if (this.strict) - throw er - if (!this.silent) - console.error('glob error', er) - break - } -} - -GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { - - var entries = this._readdir(abs, inGlobStar) - - // no entries means not a dir, so it can never have matches - // foo.txt/** doesn't match foo.txt - if (!entries) - return - - // test without the globstar, and with every child both below - // and replacing the globstar. - var remainWithoutGlobStar = remain.slice(1) - var gspref = prefix ? [ prefix ] : [] - var noGlobStar = gspref.concat(remainWithoutGlobStar) - - // the noGlobStar pattern exits the inGlobStar state - this._process(noGlobStar, index, false) - - var len = entries.length - var isSym = this.symlinks[abs] - - // If it's a symlink, and we're in a globstar, then stop - if (isSym && inGlobStar) - return - - for (var i = 0; i < len; i++) { - var e = entries[i] - if (e.charAt(0) === '.' && !this.dot) - continue - - // these two cases enter the inGlobStar state - var instead = gspref.concat(entries[i], remainWithoutGlobStar) - this._process(instead, index, true) - - var below = gspref.concat(entries[i], remain) - this._process(below, index, true) - } -} - -GlobSync.prototype._processSimple = function (prefix, index) { - // XXX review this. Shouldn't it be doing the mounting etc - // before doing stat? kinda weird? - var exists = this._stat(prefix) - - if (!this.matches[index]) - this.matches[index] = Object.create(null) +/***/ 11262: +/***/ ((__unused_webpack_module, exports) => { - // If it doesn't exist, then just mark the lack of results - if (!exists) - return +"use strict"; - if (prefix && isAbsolute(prefix) && !this.nomount) { - var trail = /[\/\\]$/.test(prefix) - if (prefix.charAt(0) === '/') { - prefix = path.join(this.root, prefix) - } else { - prefix = path.resolve(this.root, prefix) - if (trail) - prefix += '/' - } - } - if (process.platform === 'win32') - prefix = prefix.replace(/\\/g, '/') +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.addPath = addPath; +exports.pathToArray = pathToArray; - // Mark this as a match - this._emitMatch(index, prefix) +/** + * Given a Path and a key, return a new Path containing the new key. + */ +function addPath(prev, key, typename) { + return { + prev, + key, + typename, + }; } +/** + * Given a Path, return an Array of the path keys. + */ -// Returns either 'DIR', 'FILE', or false -GlobSync.prototype._stat = function (f) { - var abs = this._makeAbs(f) - var needDir = f.slice(-1) === '/' - - if (f.length > this.maxLength) - return false - - if (!this.stat && ownProp(this.cache, abs)) { - var c = this.cache[abs] - - if (Array.isArray(c)) - c = 'DIR' - - // It exists, but maybe not how we need it - if (!needDir || c === 'DIR') - return c - - if (needDir && c === 'FILE') - return false - - // otherwise we have to stat, because maybe c=true - // if we know it exists, but not what it is. - } - - var exists - var stat = this.statCache[abs] - if (!stat) { - var lstat - try { - lstat = this.fs.lstatSync(abs) - } catch (er) { - if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { - this.statCache[abs] = false - return false - } - } +function pathToArray(path) { + const flattened = []; + let curr = path; - if (lstat && lstat.isSymbolicLink()) { - try { - stat = this.fs.statSync(abs) - } catch (er) { - stat = lstat - } - } else { - stat = lstat - } + while (curr) { + flattened.push(curr.key); + curr = curr.prev; } - this.statCache[abs] = stat - - var c = true - if (stat) - c = stat.isDirectory() ? 'DIR' : 'FILE' - - this.cache[abs] = this.cache[abs] || c - - if (needDir && c === 'FILE') - return false - - return c -} - -GlobSync.prototype._mark = function (p) { - return common.mark(this, p) -} - -GlobSync.prototype._makeAbs = function (f) { - return common.makeAbs(this, f) + return flattened.reverse(); } /***/ }), -/***/ 26457: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 46514: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const types_1 = __nccwpck_require__(64597); -function createRejection(error, ...beforeErrorGroups) { - const promise = (async () => { - if (error instanceof types_1.RequestError) { - try { - for (const hooks of beforeErrorGroups) { - if (hooks) { - for (const hook of hooks) { - // eslint-disable-next-line no-await-in-loop - error = await hook(error); - } - } - } - } - catch (error_) { - error = error_; - } - } - throw error; - })(); - const returnPromise = () => promise; - promise.json = returnPromise; - promise.text = returnPromise; - promise.buffer = returnPromise; - promise.on = returnPromise; - return promise; -} -exports["default"] = createRejection; - - -/***/ }), - -/***/ 36056: -/***/ (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; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; +Object.defineProperty(exports, "__esModule", ({ + value: true, })); -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 })); -const events_1 = __nccwpck_require__(82361); -const is_1 = __nccwpck_require__(68977); -const PCancelable = __nccwpck_require__(19072); -const types_1 = __nccwpck_require__(64597); -const parse_body_1 = __nccwpck_require__(88220); -const core_1 = __nccwpck_require__(60094); -const proxy_events_1 = __nccwpck_require__(53021); -const get_buffer_1 = __nccwpck_require__(34500); -const is_response_ok_1 = __nccwpck_require__(49298); -const proxiedRequestEvents = [ - 'request', - 'response', - 'redirect', - 'uploadProgress', - 'downloadProgress' -]; -function asPromise(normalizedOptions) { - let globalRequest; - let globalResponse; - const emitter = new events_1.EventEmitter(); - const promise = new PCancelable((resolve, reject, onCancel) => { - const makeRequest = (retryCount) => { - const request = new core_1.default(undefined, normalizedOptions); - request.retryCount = retryCount; - request._noPipe = true; - onCancel(() => request.destroy()); - onCancel.shouldReject = false; - onCancel(() => reject(new types_1.CancelError(request))); - globalRequest = request; - request.once('response', async (response) => { - var _a; - response.retryCount = retryCount; - if (response.request.aborted) { - // Canceled while downloading - will throw a `CancelError` or `TimeoutError` error - return; - } - // Download body - let rawBody; - try { - rawBody = await get_buffer_1.default(request); - response.rawBody = rawBody; - } - catch (_b) { - // The same error is caught below. - // See request.once('error') - return; - } - if (request._isAboutToError) { - return; - } - // Parse body - const contentEncoding = ((_a = response.headers['content-encoding']) !== null && _a !== void 0 ? _a : '').toLowerCase(); - const isCompressed = ['gzip', 'deflate', 'br'].includes(contentEncoding); - const { options } = request; - if (isCompressed && !options.decompress) { - response.body = rawBody; - } - else { - try { - response.body = parse_body_1.default(response, options.responseType, options.parseJson, options.encoding); - } - catch (error) { - // Fallback to `utf8` - response.body = rawBody.toString(); - if (is_response_ok_1.isResponseOk(response)) { - request._beforeError(error); - return; - } - } - } - try { - for (const [index, hook] of options.hooks.afterResponse.entries()) { - // @ts-expect-error TS doesn't notice that CancelableRequest is a Promise - // eslint-disable-next-line no-await-in-loop - response = await hook(response, async (updatedOptions) => { - const typedOptions = core_1.default.normalizeArguments(undefined, { - ...updatedOptions, - retry: { - calculateDelay: () => 0 - }, - throwHttpErrors: false, - resolveBodyOnly: false - }, options); - // Remove any further hooks for that request, because we'll call them anyway. - // The loop continues. We don't want duplicates (asPromise recursion). - typedOptions.hooks.afterResponse = typedOptions.hooks.afterResponse.slice(0, index); - for (const hook of typedOptions.hooks.beforeRetry) { - // eslint-disable-next-line no-await-in-loop - await hook(typedOptions); - } - const promise = asPromise(typedOptions); - onCancel(() => { - promise.catch(() => { }); - promise.cancel(); - }); - return promise; - }); - } - } - catch (error) { - request._beforeError(new types_1.RequestError(error.message, error, request)); - return; - } - globalResponse = response; - if (!is_response_ok_1.isResponseOk(response)) { - request._beforeError(new types_1.HTTPError(response)); - return; - } - request.destroy(); - resolve(request.options.resolveBodyOnly ? response.body : response); - }); - const onError = (error) => { - if (promise.isCanceled) { - return; - } - const { options } = request; - if (error instanceof types_1.HTTPError && !options.throwHttpErrors) { - const { response } = error; - resolve(request.options.resolveBodyOnly ? response.body : response); - return; - } - reject(error); - }; - request.once('error', onError); - const previousBody = request.options.body; - request.once('retry', (newRetryCount, error) => { - var _a, _b; - if (previousBody === ((_a = error.request) === null || _a === void 0 ? void 0 : _a.options.body) && is_1.default.nodeStream((_b = error.request) === null || _b === void 0 ? void 0 : _b.options.body)) { - onError(error); - return; - } - makeRequest(newRetryCount); - }); - proxy_events_1.default(request, emitter, proxiedRequestEvents); - }; - makeRequest(0); - }); - promise.on = (event, fn) => { - emitter.on(event, fn); - return promise; - }; - const shortcut = (responseType) => { - const newPromise = (async () => { - // Wait until downloading has ended - await promise; - const { options } = globalResponse.request; - return parse_body_1.default(globalResponse, responseType, options.parseJson, options.encoding); - })(); - Object.defineProperties(newPromise, Object.getOwnPropertyDescriptors(promise)); - return newPromise; - }; - promise.json = () => { - const { headers } = globalRequest.options; - if (!globalRequest.writableFinished && headers.accept === undefined) { - headers.accept = 'application/json'; - } - return shortcut('json'); - }; - promise.buffer = () => shortcut('buffer'); - promise.text = () => shortcut('text'); - return promise; -} -exports["default"] = asPromise; -__exportStar(__nccwpck_require__(64597), exports); - - -/***/ }), - -/***/ 41048: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const is_1 = __nccwpck_require__(68977); -const normalizeArguments = (options, defaults) => { - if (is_1.default.null_(options.encoding)) { - throw new TypeError('To get a Buffer, set `options.responseType` to `buffer` instead'); - } - is_1.assert.any([is_1.default.string, is_1.default.undefined], options.encoding); - is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.resolveBodyOnly); - is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.methodRewriting); - is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.isStream); - is_1.assert.any([is_1.default.string, is_1.default.undefined], options.responseType); - // `options.responseType` - if (options.responseType === undefined) { - options.responseType = 'text'; - } - // `options.retry` - const { retry } = options; - if (defaults) { - options.retry = { ...defaults.retry }; - } - else { - options.retry = { - calculateDelay: retryObject => retryObject.computedValue, - limit: 0, - methods: [], - statusCodes: [], - errorCodes: [], - maxRetryAfter: undefined - }; - } - if (is_1.default.object(retry)) { - options.retry = { - ...options.retry, - ...retry - }; - options.retry.methods = [...new Set(options.retry.methods.map(method => method.toUpperCase()))]; - options.retry.statusCodes = [...new Set(options.retry.statusCodes)]; - options.retry.errorCodes = [...new Set(options.retry.errorCodes)]; - } - else if (is_1.default.number(retry)) { - options.retry.limit = retry; - } - if (is_1.default.undefined(options.retry.maxRetryAfter)) { - options.retry.maxRetryAfter = Math.min( - // TypeScript is not smart enough to handle `.filter(x => is.number(x))`. - // eslint-disable-next-line unicorn/no-fn-reference-in-iterator - ...[options.timeout.request, options.timeout.connect].filter(is_1.default.number)); - } - // `options.pagination` - if (is_1.default.object(options.pagination)) { - if (defaults) { - options.pagination = { - ...defaults.pagination, - ...options.pagination - }; - } - const { pagination } = options; - if (!is_1.default.function_(pagination.transform)) { - throw new Error('`options.pagination.transform` must be implemented'); - } - if (!is_1.default.function_(pagination.shouldContinue)) { - throw new Error('`options.pagination.shouldContinue` must be implemented'); - } - if (!is_1.default.function_(pagination.filter)) { - throw new TypeError('`options.pagination.filter` must be implemented'); - } - if (!is_1.default.function_(pagination.paginate)) { - throw new Error('`options.pagination.paginate` must be implemented'); - } - } - // JSON mode - if (options.responseType === 'json' && options.headers.accept === undefined) { - options.headers.accept = 'application/json'; - } - return options; -}; -exports["default"] = normalizeArguments; - - -/***/ }), - -/***/ 88220: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const types_1 = __nccwpck_require__(64597); -const parseBody = (response, responseType, parseJson, encoding) => { - const { rawBody } = response; - try { - if (responseType === 'text') { - return rawBody.toString(encoding); - } - if (responseType === 'json') { - return rawBody.length === 0 ? '' : parseJson(rawBody.toString()); - } - if (responseType === 'buffer') { - return rawBody; - } - throw new types_1.ParseError({ - message: `Unknown body type '${responseType}'`, - name: 'Error' - }, response); - } - catch (error) { - throw new types_1.ParseError(error, response); - } -}; -exports["default"] = parseBody; - - -/***/ }), - -/***/ 64597: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; +exports.devAssert = devAssert; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (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 })); -exports.CancelError = exports.ParseError = void 0; -const core_1 = __nccwpck_require__(60094); -/** -An error to be thrown when server response code is 2xx, and parsing body fails. -Includes a `response` property. -*/ -class ParseError extends core_1.RequestError { - constructor(error, response) { - const { options } = response.request; - super(`${error.message} in "${options.url.toString()}"`, error, response.request); - this.name = 'ParseError'; - this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_BODY_PARSE_FAILURE' : this.code; - } -} -exports.ParseError = ParseError; -/** -An error to be thrown when the request is aborted with `.cancel()`. -*/ -class CancelError extends core_1.RequestError { - constructor(request) { - super('Promise was canceled', {}, request); - this.name = 'CancelError'; - this.code = 'ERR_CANCELED'; - } - get isCanceled() { - return true; - } +function devAssert(condition, message) { + const booleanCondition = Boolean(condition); + + if (!booleanCondition) { + throw new Error(message); + } } -exports.CancelError = CancelError; -__exportStar(__nccwpck_require__(60094), exports); /***/ }), -/***/ 93462: +/***/ 42878: /***/ ((__unused_webpack_module, exports) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.retryAfterStatusCodes = void 0; -exports.retryAfterStatusCodes = new Set([413, 429, 503]); -const calculateRetryDelay = ({ attemptCount, retryOptions, error, retryAfter }) => { - if (attemptCount > retryOptions.limit) { - return 0; - } - const hasMethod = retryOptions.methods.includes(error.options.method); - const hasErrorCode = retryOptions.errorCodes.includes(error.code); - const hasStatusCode = error.response && retryOptions.statusCodes.includes(error.response.statusCode); - if (!hasMethod || (!hasErrorCode && !hasStatusCode)) { - return 0; - } - if (error.response) { - if (retryAfter) { - if (retryOptions.maxRetryAfter === undefined || retryAfter > retryOptions.maxRetryAfter) { - return 0; - } - return retryAfter; - } - if (error.response.statusCode === 413) { - return 0; - } - } - const noise = Math.random() * 100; - return ((2 ** (attemptCount - 1)) * 1000) + noise; -}; -exports["default"] = calculateRetryDelay; +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.didYouMean = didYouMean; +const MAX_SUGGESTIONS = 5; +/** + * Given [ A, B, C ] return ' Did you mean A, B, or C?'. + */ -/***/ }), +function didYouMean(firstArg, secondArg) { + const [subMessage, suggestionsArg] = secondArg + ? [firstArg, secondArg] + : [undefined, firstArg]; + let message = ' Did you mean '; -/***/ 60094: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (subMessage) { + message += subMessage + ' '; + } -"use strict"; + const suggestions = suggestionsArg.map((x) => `"${x}"`); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.UnsupportedProtocolError = exports.ReadError = exports.TimeoutError = exports.UploadError = exports.CacheError = exports.HTTPError = exports.MaxRedirectsError = exports.RequestError = exports.setNonEnumerableProperties = exports.knownHookEvents = exports.withoutBody = exports.kIsNormalizedAlready = void 0; -const util_1 = __nccwpck_require__(73837); -const stream_1 = __nccwpck_require__(12781); -const fs_1 = __nccwpck_require__(57147); -const url_1 = __nccwpck_require__(57310); -const http = __nccwpck_require__(13685); -const http_1 = __nccwpck_require__(13685); -const https = __nccwpck_require__(95687); -const http_timer_1 = __nccwpck_require__(76234); -const cacheable_lookup_1 = __nccwpck_require__(2286); -const CacheableRequest = __nccwpck_require__(69016); -const decompressResponse = __nccwpck_require__(22490); -// @ts-expect-error Missing types -const http2wrapper = __nccwpck_require__(54645); -const lowercaseKeys = __nccwpck_require__(9662); -const is_1 = __nccwpck_require__(68977); -const get_body_size_1 = __nccwpck_require__(94564); -const is_form_data_1 = __nccwpck_require__(90040); -const proxy_events_1 = __nccwpck_require__(53021); -const timed_out_1 = __nccwpck_require__(52454); -const url_to_options_1 = __nccwpck_require__(8026); -const options_to_url_1 = __nccwpck_require__(9219); -const weakable_map_1 = __nccwpck_require__(7288); -const get_buffer_1 = __nccwpck_require__(34500); -const dns_ip_version_1 = __nccwpck_require__(94993); -const is_response_ok_1 = __nccwpck_require__(49298); -const deprecation_warning_1 = __nccwpck_require__(397); -const normalize_arguments_1 = __nccwpck_require__(41048); -const calculate_retry_delay_1 = __nccwpck_require__(93462); -let globalDnsCache; -const kRequest = Symbol('request'); -const kResponse = Symbol('response'); -const kResponseSize = Symbol('responseSize'); -const kDownloadedSize = Symbol('downloadedSize'); -const kBodySize = Symbol('bodySize'); -const kUploadedSize = Symbol('uploadedSize'); -const kServerResponsesPiped = Symbol('serverResponsesPiped'); -const kUnproxyEvents = Symbol('unproxyEvents'); -const kIsFromCache = Symbol('isFromCache'); -const kCancelTimeouts = Symbol('cancelTimeouts'); -const kStartedReading = Symbol('startedReading'); -const kStopReading = Symbol('stopReading'); -const kTriggerRead = Symbol('triggerRead'); -const kBody = Symbol('body'); -const kJobs = Symbol('jobs'); -const kOriginalResponse = Symbol('originalResponse'); -const kRetryTimeout = Symbol('retryTimeout'); -exports.kIsNormalizedAlready = Symbol('isNormalizedAlready'); -const supportsBrotli = is_1.default.string(process.versions.brotli); -exports.withoutBody = new Set(['GET', 'HEAD']); -exports.knownHookEvents = [ - 'init', - 'beforeRequest', - 'beforeRedirect', - 'beforeError', - 'beforeRetry', - // Promise-Only - 'afterResponse' -]; -function validateSearchParameters(searchParameters) { - // eslint-disable-next-line guard-for-in - for (const key in searchParameters) { - const value = searchParameters[key]; - if (!is_1.default.string(value) && !is_1.default.number(value) && !is_1.default.boolean(value) && !is_1.default.null_(value) && !is_1.default.undefined(value)) { - throw new TypeError(`The \`searchParams\` value '${String(value)}' must be a string, number, boolean or null`); - } - } -} -function isClientRequest(clientRequest) { - return is_1.default.object(clientRequest) && !('statusCode' in clientRequest); -} -const cacheableStore = new weakable_map_1.default(); -const waitForOpenFile = async (file) => new Promise((resolve, reject) => { - const onError = (error) => { - reject(error); - }; - // Node.js 12 has incomplete types - if (!file.pending) { - resolve(); - } - file.once('error', onError); - file.once('ready', () => { - file.off('error', onError); - resolve(); - }); -}); -const redirectCodes = new Set([300, 301, 302, 303, 304, 307, 308]); -const nonEnumerableProperties = [ - 'context', - 'body', - 'json', - 'form' -]; -exports.setNonEnumerableProperties = (sources, to) => { - // Non enumerable properties shall not be merged - const properties = {}; - for (const source of sources) { - if (!source) { - continue; - } - for (const name of nonEnumerableProperties) { - if (!(name in source)) { - continue; - } - properties[name] = { - writable: true, - configurable: true, - enumerable: false, - // @ts-expect-error TS doesn't see the check above - value: source[name] - }; - } - } - Object.defineProperties(to, properties); -}; -/** -An error to be thrown when a request fails. -Contains a `code` property with error class code, like `ECONNREFUSED`. -*/ -class RequestError extends Error { - constructor(message, error, self) { - var _a, _b; - super(message); - Error.captureStackTrace(this, this.constructor); - this.name = 'RequestError'; - this.code = (_a = error.code) !== null && _a !== void 0 ? _a : 'ERR_GOT_REQUEST_ERROR'; - if (self instanceof Request) { - Object.defineProperty(this, 'request', { - enumerable: false, - value: self - }); - Object.defineProperty(this, 'response', { - enumerable: false, - value: self[kResponse] - }); - Object.defineProperty(this, 'options', { - // This fails because of TS 3.7.2 useDefineForClassFields - // Ref: https://github.com/microsoft/TypeScript/issues/34972 - enumerable: false, - value: self.options - }); - } - else { - Object.defineProperty(this, 'options', { - // This fails because of TS 3.7.2 useDefineForClassFields - // Ref: https://github.com/microsoft/TypeScript/issues/34972 - enumerable: false, - value: self - }); - } - this.timings = (_b = this.request) === null || _b === void 0 ? void 0 : _b.timings; - // Recover the original stacktrace - if (is_1.default.string(error.stack) && is_1.default.string(this.stack)) { - const indexOfMessage = this.stack.indexOf(this.message) + this.message.length; - const thisStackTrace = this.stack.slice(indexOfMessage).split('\n').reverse(); - const errorStackTrace = error.stack.slice(error.stack.indexOf(error.message) + error.message.length).split('\n').reverse(); - // Remove duplicated traces - while (errorStackTrace.length !== 0 && errorStackTrace[0] === thisStackTrace[0]) { - thisStackTrace.shift(); - } - this.stack = `${this.stack.slice(0, indexOfMessage)}${thisStackTrace.reverse().join('\n')}${errorStackTrace.reverse().join('\n')}`; - } - } -} -exports.RequestError = RequestError; -/** -An error to be thrown when the server redirects you more than ten times. -Includes a `response` property. -*/ -class MaxRedirectsError extends RequestError { - constructor(request) { - super(`Redirected ${request.options.maxRedirects} times. Aborting.`, {}, request); - this.name = 'MaxRedirectsError'; - this.code = 'ERR_TOO_MANY_REDIRECTS'; - } -} -exports.MaxRedirectsError = MaxRedirectsError; -/** -An error to be thrown when the server response code is not 2xx nor 3xx if `options.followRedirect` is `true`, but always except for 304. -Includes a `response` property. -*/ -class HTTPError extends RequestError { - constructor(response) { - super(`Response code ${response.statusCode} (${response.statusMessage})`, {}, response.request); - this.name = 'HTTPError'; - this.code = 'ERR_NON_2XX_3XX_RESPONSE'; - } -} -exports.HTTPError = HTTPError; -/** -An error to be thrown when a cache method fails. -For example, if the database goes down or there's a filesystem error. -*/ -class CacheError extends RequestError { - constructor(error, request) { - super(error.message, error, request); - this.name = 'CacheError'; - this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_CACHE_ACCESS' : this.code; - } -} -exports.CacheError = CacheError; -/** -An error to be thrown when the request body is a stream and an error occurs while reading from that stream. -*/ -class UploadError extends RequestError { - constructor(error, request) { - super(error.message, error, request); - this.name = 'UploadError'; - this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_UPLOAD' : this.code; - } -} -exports.UploadError = UploadError; -/** -An error to be thrown when the request is aborted due to a timeout. -Includes an `event` and `timings` property. -*/ -class TimeoutError extends RequestError { - constructor(error, timings, request) { - super(error.message, error, request); - this.name = 'TimeoutError'; - this.event = error.event; - this.timings = timings; - } -} -exports.TimeoutError = TimeoutError; -/** -An error to be thrown when reading from response stream fails. -*/ -class ReadError extends RequestError { - constructor(error, request) { - super(error.message, error, request); - this.name = 'ReadError'; - this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_READING_RESPONSE_STREAM' : this.code; - } -} -exports.ReadError = ReadError; -/** -An error to be thrown when given an unsupported protocol. -*/ -class UnsupportedProtocolError extends RequestError { - constructor(options) { - super(`Unsupported protocol "${options.url.protocol}"`, {}, options); - this.name = 'UnsupportedProtocolError'; - this.code = 'ERR_UNSUPPORTED_PROTOCOL'; - } + switch (suggestions.length) { + case 0: + return ''; + + case 1: + return message + suggestions[0] + '?'; + + case 2: + return message + suggestions[0] + ' or ' + suggestions[1] + '?'; + } + + const selected = suggestions.slice(0, MAX_SUGGESTIONS); + const lastItem = selected.pop(); + return message + selected.join(', ') + ', or ' + lastItem + '?'; } -exports.UnsupportedProtocolError = UnsupportedProtocolError; -const proxiedRequestEvents = [ - 'socket', - 'connect', - 'continue', - 'information', - 'upgrade', - 'timeout' -]; -class Request extends stream_1.Duplex { - constructor(url, options = {}, defaults) { - super({ - // This must be false, to enable throwing after destroy - // It is used for retry logic in Promise API - autoDestroy: false, - // It needs to be zero because we're just proxying the data to another stream - highWaterMark: 0 - }); - this[kDownloadedSize] = 0; - this[kUploadedSize] = 0; - this.requestInitialized = false; - this[kServerResponsesPiped] = new Set(); - this.redirects = []; - this[kStopReading] = false; - this[kTriggerRead] = false; - this[kJobs] = []; - this.retryCount = 0; - // TODO: Remove this when targeting Node.js >= 12 - this._progressCallbacks = []; - const unlockWrite = () => this._unlockWrite(); - const lockWrite = () => this._lockWrite(); - this.on('pipe', (source) => { - source.prependListener('data', unlockWrite); - source.on('data', lockWrite); - source.prependListener('end', unlockWrite); - source.on('end', lockWrite); - }); - this.on('unpipe', (source) => { - source.off('data', unlockWrite); - source.off('data', lockWrite); - source.off('end', unlockWrite); - source.off('end', lockWrite); - }); - this.on('pipe', source => { - if (source instanceof http_1.IncomingMessage) { - this.options.headers = { - ...source.headers, - ...this.options.headers - }; - } - }); - const { json, body, form } = options; - if (json || body || form) { - this._lockWrite(); - } - if (exports.kIsNormalizedAlready in options) { - this.options = options; - } - else { - try { - // @ts-expect-error Common TypeScript bug saying that `this.constructor` is not accessible - this.options = this.constructor.normalizeArguments(url, options, defaults); - } - catch (error) { - // TODO: Move this to `_destroy()` - if (is_1.default.nodeStream(options.body)) { - options.body.destroy(); - } - this.destroy(error); - return; - } - } - (async () => { - var _a; - try { - if (this.options.body instanceof fs_1.ReadStream) { - await waitForOpenFile(this.options.body); - } - const { url: normalizedURL } = this.options; - if (!normalizedURL) { - throw new TypeError('Missing `url` property'); - } - this.requestUrl = normalizedURL.toString(); - decodeURI(this.requestUrl); - await this._finalizeBody(); - await this._makeRequest(); - if (this.destroyed) { - (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.destroy(); - return; - } - // Queued writes etc. - for (const job of this[kJobs]) { - job(); - } - // Prevent memory leak - this[kJobs].length = 0; - this.requestInitialized = true; - } - catch (error) { - if (error instanceof RequestError) { - this._beforeError(error); - return; - } - // This is a workaround for https://github.com/nodejs/node/issues/33335 - if (!this.destroyed) { - this.destroy(error); - } - } - })(); - } - static normalizeArguments(url, options, defaults) { - var _a, _b, _c, _d, _e; - const rawOptions = options; - if (is_1.default.object(url) && !is_1.default.urlInstance(url)) { - options = { ...defaults, ...url, ...options }; - } - else { - if (url && options && options.url !== undefined) { - throw new TypeError('The `url` option is mutually exclusive with the `input` argument'); - } - options = { ...defaults, ...options }; - if (url !== undefined) { - options.url = url; - } - if (is_1.default.urlInstance(options.url)) { - options.url = new url_1.URL(options.url.toString()); - } - } - // TODO: Deprecate URL options in Got 12. - // Support extend-specific options - if (options.cache === false) { - options.cache = undefined; - } - if (options.dnsCache === false) { - options.dnsCache = undefined; - } - // Nice type assertions - is_1.assert.any([is_1.default.string, is_1.default.undefined], options.method); - is_1.assert.any([is_1.default.object, is_1.default.undefined], options.headers); - is_1.assert.any([is_1.default.string, is_1.default.urlInstance, is_1.default.undefined], options.prefixUrl); - is_1.assert.any([is_1.default.object, is_1.default.undefined], options.cookieJar); - is_1.assert.any([is_1.default.object, is_1.default.string, is_1.default.undefined], options.searchParams); - is_1.assert.any([is_1.default.object, is_1.default.string, is_1.default.undefined], options.cache); - is_1.assert.any([is_1.default.object, is_1.default.number, is_1.default.undefined], options.timeout); - is_1.assert.any([is_1.default.object, is_1.default.undefined], options.context); - is_1.assert.any([is_1.default.object, is_1.default.undefined], options.hooks); - is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.decompress); - is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.ignoreInvalidCookies); - is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.followRedirect); - is_1.assert.any([is_1.default.number, is_1.default.undefined], options.maxRedirects); - is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.throwHttpErrors); - is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.http2); - is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.allowGetBody); - is_1.assert.any([is_1.default.string, is_1.default.undefined], options.localAddress); - is_1.assert.any([dns_ip_version_1.isDnsLookupIpVersion, is_1.default.undefined], options.dnsLookupIpVersion); - is_1.assert.any([is_1.default.object, is_1.default.undefined], options.https); - is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.rejectUnauthorized); - if (options.https) { - is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.https.rejectUnauthorized); - is_1.assert.any([is_1.default.function_, is_1.default.undefined], options.https.checkServerIdentity); - is_1.assert.any([is_1.default.string, is_1.default.object, is_1.default.array, is_1.default.undefined], options.https.certificateAuthority); - is_1.assert.any([is_1.default.string, is_1.default.object, is_1.default.array, is_1.default.undefined], options.https.key); - is_1.assert.any([is_1.default.string, is_1.default.object, is_1.default.array, is_1.default.undefined], options.https.certificate); - is_1.assert.any([is_1.default.string, is_1.default.undefined], options.https.passphrase); - is_1.assert.any([is_1.default.string, is_1.default.buffer, is_1.default.array, is_1.default.undefined], options.https.pfx); - } - is_1.assert.any([is_1.default.object, is_1.default.undefined], options.cacheOptions); - // `options.method` - if (is_1.default.string(options.method)) { - options.method = options.method.toUpperCase(); - } - else { - options.method = 'GET'; - } - // `options.headers` - if (options.headers === (defaults === null || defaults === void 0 ? void 0 : defaults.headers)) { - options.headers = { ...options.headers }; - } - else { - options.headers = lowercaseKeys({ ...(defaults === null || defaults === void 0 ? void 0 : defaults.headers), ...options.headers }); - } - // Disallow legacy `url.Url` - if ('slashes' in options) { - throw new TypeError('The legacy `url.Url` has been deprecated. Use `URL` instead.'); - } - // `options.auth` - if ('auth' in options) { - throw new TypeError('Parameter `auth` is deprecated. Use `username` / `password` instead.'); - } - // `options.searchParams` - if ('searchParams' in options) { - if (options.searchParams && options.searchParams !== (defaults === null || defaults === void 0 ? void 0 : defaults.searchParams)) { - let searchParameters; - if (is_1.default.string(options.searchParams) || (options.searchParams instanceof url_1.URLSearchParams)) { - searchParameters = new url_1.URLSearchParams(options.searchParams); - } - else { - validateSearchParameters(options.searchParams); - searchParameters = new url_1.URLSearchParams(); - // eslint-disable-next-line guard-for-in - for (const key in options.searchParams) { - const value = options.searchParams[key]; - if (value === null) { - searchParameters.append(key, ''); - } - else if (value !== undefined) { - searchParameters.append(key, value); - } - } - } - // `normalizeArguments()` is also used to merge options - (_a = defaults === null || defaults === void 0 ? void 0 : defaults.searchParams) === null || _a === void 0 ? void 0 : _a.forEach((value, key) => { - // Only use default if one isn't already defined - if (!searchParameters.has(key)) { - searchParameters.append(key, value); - } - }); - options.searchParams = searchParameters; - } - } - // `options.username` & `options.password` - options.username = (_b = options.username) !== null && _b !== void 0 ? _b : ''; - options.password = (_c = options.password) !== null && _c !== void 0 ? _c : ''; - // `options.prefixUrl` & `options.url` - if (is_1.default.undefined(options.prefixUrl)) { - options.prefixUrl = (_d = defaults === null || defaults === void 0 ? void 0 : defaults.prefixUrl) !== null && _d !== void 0 ? _d : ''; - } - else { - options.prefixUrl = options.prefixUrl.toString(); - if (options.prefixUrl !== '' && !options.prefixUrl.endsWith('/')) { - options.prefixUrl += '/'; - } - } - if (is_1.default.string(options.url)) { - if (options.url.startsWith('/')) { - throw new Error('`input` must not start with a slash when using `prefixUrl`'); - } - options.url = options_to_url_1.default(options.prefixUrl + options.url, options); - } - else if ((is_1.default.undefined(options.url) && options.prefixUrl !== '') || options.protocol) { - options.url = options_to_url_1.default(options.prefixUrl, options); - } - if (options.url) { - if ('port' in options) { - delete options.port; - } - // Make it possible to change `options.prefixUrl` - let { prefixUrl } = options; - Object.defineProperty(options, 'prefixUrl', { - set: (value) => { - const url = options.url; - if (!url.href.startsWith(value)) { - throw new Error(`Cannot change \`prefixUrl\` from ${prefixUrl} to ${value}: ${url.href}`); - } - options.url = new url_1.URL(value + url.href.slice(prefixUrl.length)); - prefixUrl = value; - }, - get: () => prefixUrl - }); - // Support UNIX sockets - let { protocol } = options.url; - if (protocol === 'unix:') { - protocol = 'http:'; - options.url = new url_1.URL(`http://unix${options.url.pathname}${options.url.search}`); - } - // Set search params - if (options.searchParams) { - // eslint-disable-next-line @typescript-eslint/no-base-to-string - options.url.search = options.searchParams.toString(); - } - // Protocol check - if (protocol !== 'http:' && protocol !== 'https:') { - throw new UnsupportedProtocolError(options); - } - // Update `username` - if (options.username === '') { - options.username = options.url.username; - } - else { - options.url.username = options.username; - } - // Update `password` - if (options.password === '') { - options.password = options.url.password; - } - else { - options.url.password = options.password; - } - } - // `options.cookieJar` - const { cookieJar } = options; - if (cookieJar) { - let { setCookie, getCookieString } = cookieJar; - is_1.assert.function_(setCookie); - is_1.assert.function_(getCookieString); - /* istanbul ignore next: Horrible `tough-cookie` v3 check */ - if (setCookie.length === 4 && getCookieString.length === 0) { - setCookie = util_1.promisify(setCookie.bind(options.cookieJar)); - getCookieString = util_1.promisify(getCookieString.bind(options.cookieJar)); - options.cookieJar = { - setCookie, - getCookieString: getCookieString - }; - } - } - // `options.cache` - const { cache } = options; - if (cache) { - if (!cacheableStore.has(cache)) { - cacheableStore.set(cache, new CacheableRequest(((requestOptions, handler) => { - const result = requestOptions[kRequest](requestOptions, handler); - // TODO: remove this when `cacheable-request` supports async request functions. - if (is_1.default.promise(result)) { - // @ts-expect-error - // We only need to implement the error handler in order to support HTTP2 caching. - // The result will be a promise anyway. - result.once = (event, handler) => { - if (event === 'error') { - result.catch(handler); - } - else if (event === 'abort') { - // The empty catch is needed here in case when - // it rejects before it's `await`ed in `_makeRequest`. - (async () => { - try { - const request = (await result); - request.once('abort', handler); - } - catch (_a) { } - })(); - } - else { - /* istanbul ignore next: safety check */ - throw new Error(`Unknown HTTP2 promise event: ${event}`); - } - return result; - }; - } - return result; - }), cache)); - } - } - // `options.cacheOptions` - options.cacheOptions = { ...options.cacheOptions }; - // `options.dnsCache` - if (options.dnsCache === true) { - if (!globalDnsCache) { - globalDnsCache = new cacheable_lookup_1.default(); - } - options.dnsCache = globalDnsCache; - } - else if (!is_1.default.undefined(options.dnsCache) && !options.dnsCache.lookup) { - throw new TypeError(`Parameter \`dnsCache\` must be a CacheableLookup instance or a boolean, got ${is_1.default(options.dnsCache)}`); - } - // `options.timeout` - if (is_1.default.number(options.timeout)) { - options.timeout = { request: options.timeout }; - } - else if (defaults && options.timeout !== defaults.timeout) { - options.timeout = { - ...defaults.timeout, - ...options.timeout - }; - } - else { - options.timeout = { ...options.timeout }; - } - // `options.context` - if (!options.context) { - options.context = {}; - } - // `options.hooks` - const areHooksDefault = options.hooks === (defaults === null || defaults === void 0 ? void 0 : defaults.hooks); - options.hooks = { ...options.hooks }; - for (const event of exports.knownHookEvents) { - if (event in options.hooks) { - if (is_1.default.array(options.hooks[event])) { - // See https://github.com/microsoft/TypeScript/issues/31445#issuecomment-576929044 - options.hooks[event] = [...options.hooks[event]]; - } - else { - throw new TypeError(`Parameter \`${event}\` must be an Array, got ${is_1.default(options.hooks[event])}`); - } - } - else { - options.hooks[event] = []; - } - } - if (defaults && !areHooksDefault) { - for (const event of exports.knownHookEvents) { - const defaultHooks = defaults.hooks[event]; - if (defaultHooks.length > 0) { - // See https://github.com/microsoft/TypeScript/issues/31445#issuecomment-576929044 - options.hooks[event] = [ - ...defaults.hooks[event], - ...options.hooks[event] - ]; - } - } - } - // DNS options - if ('family' in options) { - deprecation_warning_1.default('"options.family" was never documented, please use "options.dnsLookupIpVersion"'); - } - // HTTPS options - if (defaults === null || defaults === void 0 ? void 0 : defaults.https) { - options.https = { ...defaults.https, ...options.https }; - } - if ('rejectUnauthorized' in options) { - deprecation_warning_1.default('"options.rejectUnauthorized" is now deprecated, please use "options.https.rejectUnauthorized"'); - } - if ('checkServerIdentity' in options) { - deprecation_warning_1.default('"options.checkServerIdentity" was never documented, please use "options.https.checkServerIdentity"'); - } - if ('ca' in options) { - deprecation_warning_1.default('"options.ca" was never documented, please use "options.https.certificateAuthority"'); - } - if ('key' in options) { - deprecation_warning_1.default('"options.key" was never documented, please use "options.https.key"'); - } - if ('cert' in options) { - deprecation_warning_1.default('"options.cert" was never documented, please use "options.https.certificate"'); - } - if ('passphrase' in options) { - deprecation_warning_1.default('"options.passphrase" was never documented, please use "options.https.passphrase"'); - } - if ('pfx' in options) { - deprecation_warning_1.default('"options.pfx" was never documented, please use "options.https.pfx"'); - } - // Other options - if ('followRedirects' in options) { - throw new TypeError('The `followRedirects` option does not exist. Use `followRedirect` instead.'); - } - if (options.agent) { - for (const key in options.agent) { - if (key !== 'http' && key !== 'https' && key !== 'http2') { - throw new TypeError(`Expected the \`options.agent\` properties to be \`http\`, \`https\` or \`http2\`, got \`${key}\``); - } - } - } - options.maxRedirects = (_e = options.maxRedirects) !== null && _e !== void 0 ? _e : 0; - // Set non-enumerable properties - exports.setNonEnumerableProperties([defaults, rawOptions], options); - return normalize_arguments_1.default(options, defaults); - } - _lockWrite() { - const onLockedWrite = () => { - throw new TypeError('The payload has been already provided'); - }; - this.write = onLockedWrite; - this.end = onLockedWrite; - } - _unlockWrite() { - this.write = super.write; - this.end = super.end; - } - async _finalizeBody() { - const { options } = this; - const { headers } = options; - const isForm = !is_1.default.undefined(options.form); - const isJSON = !is_1.default.undefined(options.json); - const isBody = !is_1.default.undefined(options.body); - const hasPayload = isForm || isJSON || isBody; - const cannotHaveBody = exports.withoutBody.has(options.method) && !(options.method === 'GET' && options.allowGetBody); - this._cannotHaveBody = cannotHaveBody; - if (hasPayload) { - if (cannotHaveBody) { - throw new TypeError(`The \`${options.method}\` method cannot be used with a body`); - } - if ([isBody, isForm, isJSON].filter(isTrue => isTrue).length > 1) { - throw new TypeError('The `body`, `json` and `form` options are mutually exclusive'); - } - if (isBody && - !(options.body instanceof stream_1.Readable) && - !is_1.default.string(options.body) && - !is_1.default.buffer(options.body) && - !is_form_data_1.default(options.body)) { - throw new TypeError('The `body` option must be a stream.Readable, string or Buffer'); - } - if (isForm && !is_1.default.object(options.form)) { - throw new TypeError('The `form` option must be an Object'); - } - { - // Serialize body - const noContentType = !is_1.default.string(headers['content-type']); - if (isBody) { - // Special case for https://github.com/form-data/form-data - if (is_form_data_1.default(options.body) && noContentType) { - headers['content-type'] = `multipart/form-data; boundary=${options.body.getBoundary()}`; - } - this[kBody] = options.body; - } - else if (isForm) { - if (noContentType) { - headers['content-type'] = 'application/x-www-form-urlencoded'; - } - this[kBody] = (new url_1.URLSearchParams(options.form)).toString(); - } - else { - if (noContentType) { - headers['content-type'] = 'application/json'; - } - this[kBody] = options.stringifyJson(options.json); - } - const uploadBodySize = await get_body_size_1.default(this[kBody], options.headers); - // See https://tools.ietf.org/html/rfc7230#section-3.3.2 - // A user agent SHOULD send a Content-Length in a request message when - // no Transfer-Encoding is sent and the request method defines a meaning - // for an enclosed payload body. For example, a Content-Length header - // field is normally sent in a POST request even when the value is 0 - // (indicating an empty payload body). A user agent SHOULD NOT send a - // Content-Length header field when the request message does not contain - // a payload body and the method semantics do not anticipate such a - // body. - if (is_1.default.undefined(headers['content-length']) && is_1.default.undefined(headers['transfer-encoding'])) { - if (!cannotHaveBody && !is_1.default.undefined(uploadBodySize)) { - headers['content-length'] = String(uploadBodySize); - } - } - } - } - else if (cannotHaveBody) { - this._lockWrite(); - } - else { - this._unlockWrite(); - } - this[kBodySize] = Number(headers['content-length']) || undefined; - } - async _onResponseBase(response) { - const { options } = this; - const { url } = options; - this[kOriginalResponse] = response; - if (options.decompress) { - response = decompressResponse(response); - } - const statusCode = response.statusCode; - const typedResponse = response; - typedResponse.statusMessage = typedResponse.statusMessage ? typedResponse.statusMessage : http.STATUS_CODES[statusCode]; - typedResponse.url = options.url.toString(); - typedResponse.requestUrl = this.requestUrl; - typedResponse.redirectUrls = this.redirects; - typedResponse.request = this; - typedResponse.isFromCache = response.fromCache || false; - typedResponse.ip = this.ip; - typedResponse.retryCount = this.retryCount; - this[kIsFromCache] = typedResponse.isFromCache; - this[kResponseSize] = Number(response.headers['content-length']) || undefined; - this[kResponse] = response; - response.once('end', () => { - this[kResponseSize] = this[kDownloadedSize]; - this.emit('downloadProgress', this.downloadProgress); - }); - response.once('error', (error) => { - // Force clean-up, because some packages don't do this. - // TODO: Fix decompress-response - response.destroy(); - this._beforeError(new ReadError(error, this)); - }); - response.once('aborted', () => { - this._beforeError(new ReadError({ - name: 'Error', - message: 'The server aborted pending request', - code: 'ECONNRESET' - }, this)); - }); - this.emit('downloadProgress', this.downloadProgress); - const rawCookies = response.headers['set-cookie']; - if (is_1.default.object(options.cookieJar) && rawCookies) { - let promises = rawCookies.map(async (rawCookie) => options.cookieJar.setCookie(rawCookie, url.toString())); - if (options.ignoreInvalidCookies) { - promises = promises.map(async (p) => p.catch(() => { })); - } - try { - await Promise.all(promises); - } - catch (error) { - this._beforeError(error); - return; - } - } - if (options.followRedirect && response.headers.location && redirectCodes.has(statusCode)) { - // We're being redirected, we don't care about the response. - // It'd be best to abort the request, but we can't because - // we would have to sacrifice the TCP connection. We don't want that. - response.resume(); - if (this[kRequest]) { - this[kCancelTimeouts](); - // eslint-disable-next-line @typescript-eslint/no-dynamic-delete - delete this[kRequest]; - this[kUnproxyEvents](); - } - const shouldBeGet = statusCode === 303 && options.method !== 'GET' && options.method !== 'HEAD'; - if (shouldBeGet || !options.methodRewriting) { - // Server responded with "see other", indicating that the resource exists at another location, - // and the client should request it from that location via GET or HEAD. - options.method = 'GET'; - if ('body' in options) { - delete options.body; - } - if ('json' in options) { - delete options.json; - } - if ('form' in options) { - delete options.form; - } - this[kBody] = undefined; - delete options.headers['content-length']; - } - if (this.redirects.length >= options.maxRedirects) { - this._beforeError(new MaxRedirectsError(this)); - return; - } - try { - // Do not remove. See https://github.com/sindresorhus/got/pull/214 - const redirectBuffer = Buffer.from(response.headers.location, 'binary').toString(); - // Handles invalid URLs. See https://github.com/sindresorhus/got/issues/604 - const redirectUrl = new url_1.URL(redirectBuffer, url); - const redirectString = redirectUrl.toString(); - decodeURI(redirectString); - // eslint-disable-next-line no-inner-declarations - function isUnixSocketURL(url) { - return url.protocol === 'unix:' || url.hostname === 'unix'; - } - if (!isUnixSocketURL(url) && isUnixSocketURL(redirectUrl)) { - this._beforeError(new RequestError('Cannot redirect to UNIX socket', {}, this)); - return; - } - // Redirecting to a different site, clear sensitive data. - if (redirectUrl.hostname !== url.hostname || redirectUrl.port !== url.port) { - if ('host' in options.headers) { - delete options.headers.host; - } - if ('cookie' in options.headers) { - delete options.headers.cookie; - } - if ('authorization' in options.headers) { - delete options.headers.authorization; - } - if (options.username || options.password) { - options.username = ''; - options.password = ''; - } - } - else { - redirectUrl.username = options.username; - redirectUrl.password = options.password; - } - this.redirects.push(redirectString); - options.url = redirectUrl; - for (const hook of options.hooks.beforeRedirect) { - // eslint-disable-next-line no-await-in-loop - await hook(options, typedResponse); - } - this.emit('redirect', typedResponse, options); - await this._makeRequest(); - } - catch (error) { - this._beforeError(error); - return; - } - return; - } - if (options.isStream && options.throwHttpErrors && !is_response_ok_1.isResponseOk(typedResponse)) { - this._beforeError(new HTTPError(typedResponse)); - return; - } - response.on('readable', () => { - if (this[kTriggerRead]) { - this._read(); - } - }); - this.on('resume', () => { - response.resume(); - }); - this.on('pause', () => { - response.pause(); - }); - response.once('end', () => { - this.push(null); - }); - this.emit('response', response); - for (const destination of this[kServerResponsesPiped]) { - if (destination.headersSent) { - continue; - } - // eslint-disable-next-line guard-for-in - for (const key in response.headers) { - const isAllowed = options.decompress ? key !== 'content-encoding' : true; - const value = response.headers[key]; - if (isAllowed) { - destination.setHeader(key, value); - } - } - destination.statusCode = statusCode; - } - } - async _onResponse(response) { - try { - await this._onResponseBase(response); - } - catch (error) { - /* istanbul ignore next: better safe than sorry */ - this._beforeError(error); - } + + +/***/ }), + +/***/ 93173: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.groupBy = groupBy; + +/** + * Groups array items into a Map, given a function to produce grouping key. + */ +function groupBy(list, keyFn) { + const result = new Map(); + + for (const item of list) { + const key = keyFn(item); + const group = result.get(key); + + if (group === undefined) { + result.set(key, [item]); + } else { + group.push(item); } - _onRequest(request) { - const { options } = this; - const { timeout, url } = options; - http_timer_1.default(request); - this[kCancelTimeouts] = timed_out_1.default(request, timeout, url); - const responseEventName = options.cache ? 'cacheableResponse' : 'response'; - request.once(responseEventName, (response) => { - void this._onResponse(response); - }); - request.once('error', (error) => { - var _a; - // Force clean-up, because some packages (e.g. nock) don't do this. - request.destroy(); - // Node.js <= 12.18.2 mistakenly emits the response `end` first. - (_a = request.res) === null || _a === void 0 ? void 0 : _a.removeAllListeners('end'); - error = error instanceof timed_out_1.TimeoutError ? new TimeoutError(error, this.timings, this) : new RequestError(error.message, error, this); - this._beforeError(error); - }); - this[kUnproxyEvents] = proxy_events_1.default(request, this, proxiedRequestEvents); - this[kRequest] = request; - this.emit('uploadProgress', this.uploadProgress); - // Send body - const body = this[kBody]; - const currentRequest = this.redirects.length === 0 ? this : request; - if (is_1.default.nodeStream(body)) { - body.pipe(currentRequest); - body.once('error', (error) => { - this._beforeError(new UploadError(error, this)); - }); - } - else { - this._unlockWrite(); - if (!is_1.default.undefined(body)) { - this._writeRequest(body, undefined, () => { }); - currentRequest.end(); - this._lockWrite(); - } - else if (this._cannotHaveBody || this._noPipe) { - currentRequest.end(); - this._lockWrite(); - } - } - this.emit('request', request); + } + + return result; +} + + +/***/ }), + +/***/ 51188: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.identityFunc = identityFunc; + +/** + * Returns the first argument it receives. + */ +function identityFunc(x) { + return x; +} + + +/***/ }), + +/***/ 10102: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.inspect = inspect; +const MAX_ARRAY_LENGTH = 10; +const MAX_RECURSIVE_DEPTH = 2; +/** + * Used to print values in error messages. + */ + +function inspect(value) { + return formatValue(value, []); +} + +function formatValue(value, seenValues) { + switch (typeof value) { + case 'string': + return JSON.stringify(value); + + case 'function': + return value.name ? `[function ${value.name}]` : '[function]'; + + case 'object': + return formatObjectValue(value, seenValues); + + default: + return String(value); + } +} + +function formatObjectValue(value, previouslySeenValues) { + if (value === null) { + return 'null'; + } + + if (previouslySeenValues.includes(value)) { + return '[Circular]'; + } + + const seenValues = [...previouslySeenValues, value]; + + if (isJSONable(value)) { + const jsonValue = value.toJSON(); // check for infinite recursion + + if (jsonValue !== value) { + return typeof jsonValue === 'string' + ? jsonValue + : formatValue(jsonValue, seenValues); } - async _createCacheableRequest(url, options) { - return new Promise((resolve, reject) => { - // TODO: Remove `utils/url-to-options.ts` when `cacheable-request` is fixed - Object.assign(options, url_to_options_1.default(url)); - // `http-cache-semantics` checks this - // TODO: Fix this ignore. - // @ts-expect-error - delete options.url; - let request; - // This is ugly - const cacheRequest = cacheableStore.get(options.cache)(options, async (response) => { - // TODO: Fix `cacheable-response` - response._readableState.autoDestroy = false; - if (request) { - (await request).emit('cacheableResponse', response); - } - resolve(response); - }); - // Restore options - options.url = url; - cacheRequest.once('error', reject); - cacheRequest.once('request', async (requestOrPromise) => { - request = requestOrPromise; - resolve(request); - }); - }); + } else if (Array.isArray(value)) { + return formatArray(value, seenValues); + } + + return formatObject(value, seenValues); +} + +function isJSONable(value) { + return typeof value.toJSON === 'function'; +} + +function formatObject(object, seenValues) { + const entries = Object.entries(object); + + if (entries.length === 0) { + return '{}'; + } + + if (seenValues.length > MAX_RECURSIVE_DEPTH) { + return '[' + getObjectTag(object) + ']'; + } + + const properties = entries.map( + ([key, value]) => key + ': ' + formatValue(value, seenValues), + ); + return '{ ' + properties.join(', ') + ' }'; +} + +function formatArray(array, seenValues) { + if (array.length === 0) { + return '[]'; + } + + if (seenValues.length > MAX_RECURSIVE_DEPTH) { + return '[Array]'; + } + + const len = Math.min(MAX_ARRAY_LENGTH, array.length); + const remaining = array.length - len; + const items = []; + + for (let i = 0; i < len; ++i) { + items.push(formatValue(array[i], seenValues)); + } + + if (remaining === 1) { + items.push('... 1 more item'); + } else if (remaining > 1) { + items.push(`... ${remaining} more items`); + } + + return '[' + items.join(', ') + ']'; +} + +function getObjectTag(object) { + const tag = Object.prototype.toString + .call(object) + .replace(/^\[object /, '') + .replace(/]$/, ''); + + if (tag === 'Object' && typeof object.constructor === 'function') { + const name = object.constructor.name; + + if (typeof name === 'string' && name !== '') { + return name; } - async _makeRequest() { - var _a, _b, _c, _d, _e; - const { options } = this; - const { headers } = options; - for (const key in headers) { - if (is_1.default.undefined(headers[key])) { - // eslint-disable-next-line @typescript-eslint/no-dynamic-delete - delete headers[key]; - } - else if (is_1.default.null_(headers[key])) { - throw new TypeError(`Use \`undefined\` instead of \`null\` to delete the \`${key}\` header`); - } - } - if (options.decompress && is_1.default.undefined(headers['accept-encoding'])) { - headers['accept-encoding'] = supportsBrotli ? 'gzip, deflate, br' : 'gzip, deflate'; - } - // Set cookies - if (options.cookieJar) { - const cookieString = await options.cookieJar.getCookieString(options.url.toString()); - if (is_1.default.nonEmptyString(cookieString)) { - options.headers.cookie = cookieString; - } - } - for (const hook of options.hooks.beforeRequest) { - // eslint-disable-next-line no-await-in-loop - const result = await hook(options); - if (!is_1.default.undefined(result)) { - // @ts-expect-error Skip the type mismatch to support abstract responses - options.request = () => result; - break; - } - } - if (options.body && this[kBody] !== options.body) { - this[kBody] = options.body; - } - const { agent, request, timeout, url } = options; - if (options.dnsCache && !('lookup' in options)) { - options.lookup = options.dnsCache.lookup; - } - // UNIX sockets - if (url.hostname === 'unix') { - const matches = /(?.+?):(?.+)/.exec(`${url.pathname}${url.search}`); - if (matches === null || matches === void 0 ? void 0 : matches.groups) { - const { socketPath, path } = matches.groups; - Object.assign(options, { - socketPath, - path, - host: '' - }); - } - } - const isHttps = url.protocol === 'https:'; - // Fallback function - let fallbackFn; - if (options.http2) { - fallbackFn = http2wrapper.auto; - } - else { - fallbackFn = isHttps ? https.request : http.request; - } - const realFn = (_a = options.request) !== null && _a !== void 0 ? _a : fallbackFn; - // Cache support - const fn = options.cache ? this._createCacheableRequest : realFn; - // Pass an agent directly when HTTP2 is disabled - if (agent && !options.http2) { - options.agent = agent[isHttps ? 'https' : 'http']; - } - // Prepare plain HTTP request options - options[kRequest] = realFn; - delete options.request; - // TODO: Fix this ignore. - // @ts-expect-error - delete options.timeout; - const requestOptions = options; - requestOptions.shared = (_b = options.cacheOptions) === null || _b === void 0 ? void 0 : _b.shared; - requestOptions.cacheHeuristic = (_c = options.cacheOptions) === null || _c === void 0 ? void 0 : _c.cacheHeuristic; - requestOptions.immutableMinTimeToLive = (_d = options.cacheOptions) === null || _d === void 0 ? void 0 : _d.immutableMinTimeToLive; - requestOptions.ignoreCargoCult = (_e = options.cacheOptions) === null || _e === void 0 ? void 0 : _e.ignoreCargoCult; - // If `dnsLookupIpVersion` is not present do not override `family` - if (options.dnsLookupIpVersion !== undefined) { - try { - requestOptions.family = dns_ip_version_1.dnsLookupIpVersionToFamily(options.dnsLookupIpVersion); - } - catch (_f) { - throw new Error('Invalid `dnsLookupIpVersion` option value'); - } - } - // HTTPS options remapping - if (options.https) { - if ('rejectUnauthorized' in options.https) { - requestOptions.rejectUnauthorized = options.https.rejectUnauthorized; - } - if (options.https.checkServerIdentity) { - requestOptions.checkServerIdentity = options.https.checkServerIdentity; - } - if (options.https.certificateAuthority) { - requestOptions.ca = options.https.certificateAuthority; - } - if (options.https.certificate) { - requestOptions.cert = options.https.certificate; - } - if (options.https.key) { - requestOptions.key = options.https.key; - } - if (options.https.passphrase) { - requestOptions.passphrase = options.https.passphrase; - } - if (options.https.pfx) { - requestOptions.pfx = options.https.pfx; - } - } - try { - let requestOrResponse = await fn(url, requestOptions); - if (is_1.default.undefined(requestOrResponse)) { - requestOrResponse = fallbackFn(url, requestOptions); - } - // Restore options - options.request = request; - options.timeout = timeout; - options.agent = agent; - // HTTPS options restore - if (options.https) { - if ('rejectUnauthorized' in options.https) { - delete requestOptions.rejectUnauthorized; - } - if (options.https.checkServerIdentity) { - // @ts-expect-error - This one will be removed when we remove the alias. - delete requestOptions.checkServerIdentity; - } - if (options.https.certificateAuthority) { - delete requestOptions.ca; - } - if (options.https.certificate) { - delete requestOptions.cert; - } - if (options.https.key) { - delete requestOptions.key; - } - if (options.https.passphrase) { - delete requestOptions.passphrase; - } - if (options.https.pfx) { - delete requestOptions.pfx; - } - } - if (isClientRequest(requestOrResponse)) { - this._onRequest(requestOrResponse); - // Emit the response after the stream has been ended - } - else if (this.writable) { - this.once('finish', () => { - void this._onResponse(requestOrResponse); - }); - this._unlockWrite(); - this.end(); - this._lockWrite(); - } - else { - void this._onResponse(requestOrResponse); - } + } + + return tag; +} + + +/***/ }), + +/***/ 93481: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.instanceOf = void 0; + +var _inspect = __nccwpck_require__(10102); + +/* c8 ignore next 3 */ +const isProduction = + globalThis.process && // eslint-disable-next-line no-undef + process.env.NODE_ENV === 'production'; +/** + * A replacement for instanceof which includes an error warning when multi-realm + * constructors are detected. + * See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production + * See: https://webpack.js.org/guides/production/ + */ + +const instanceOf = + /* c8 ignore next 6 */ + // FIXME: https://github.com/graphql/graphql-js/issues/2317 + isProduction + ? function instanceOf(value, constructor) { + return value instanceof constructor; + } + : function instanceOf(value, constructor) { + if (value instanceof constructor) { + return true; } - catch (error) { - if (error instanceof CacheableRequest.CacheError) { - throw new CacheError(error, this); - } - throw new RequestError(error.message, error, this); + + if (typeof value === 'object' && value !== null) { + var _value$constructor; + + // Prefer Symbol.toStringTag since it is immune to minification. + const className = constructor.prototype[Symbol.toStringTag]; + const valueClassName = // We still need to support constructor's name to detect conflicts with older versions of this library. + Symbol.toStringTag in value // @ts-expect-error TS bug see, https://github.com/microsoft/TypeScript/issues/38009 + ? value[Symbol.toStringTag] + : (_value$constructor = value.constructor) === null || + _value$constructor === void 0 + ? void 0 + : _value$constructor.name; + + if (className === valueClassName) { + const stringifiedValue = (0, _inspect.inspect)(value); + throw new Error(`Cannot use ${className} "${stringifiedValue}" from another module or realm. + +Ensure that there is only one instance of "graphql" in the node_modules +directory. If different versions of "graphql" are the dependencies of other +relied on modules, use "resolutions" to ensure only one version is installed. + +https://yarnpkg.com/en/docs/selective-version-resolutions + +Duplicate "graphql" modules cannot be used at the same time since different +versions may have different capabilities and behavior. The data from one +version used in the function from another could produce confusing and +spurious results.`); + } } + + return false; + }; +exports.instanceOf = instanceOf; + + +/***/ }), + +/***/ 28847: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.invariant = invariant; + +function invariant(condition, message) { + const booleanCondition = Boolean(condition); + + if (!booleanCondition) { + throw new Error( + message != null ? message : 'Unexpected invariant triggered.', + ); + } +} + + +/***/ }), + +/***/ 20626: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.isAsyncIterable = isAsyncIterable; + +/** + * Returns true if the provided object implements the AsyncIterator protocol via + * implementing a `Symbol.asyncIterator` method. + */ +function isAsyncIterable(maybeAsyncIterable) { + return ( + typeof (maybeAsyncIterable === null || maybeAsyncIterable === void 0 + ? void 0 + : maybeAsyncIterable[Symbol.asyncIterator]) === 'function' + ); +} + + +/***/ }), + +/***/ 81258: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.isIterableObject = isIterableObject; + +/** + * Returns true if the provided object is an Object (i.e. not a string literal) + * and implements the Iterator protocol. + * + * This may be used in place of [Array.isArray()][isArray] to determine if + * an object should be iterated-over e.g. Array, Map, Set, Int8Array, + * TypedArray, etc. but excludes string literals. + * + * @example + * ```ts + * isIterableObject([ 1, 2, 3 ]) // true + * isIterableObject(new Map()) // true + * isIterableObject('ABC') // false + * isIterableObject({ key: 'value' }) // false + * isIterableObject({ length: 1, 0: 'Alpha' }) // false + * ``` + */ +function isIterableObject(maybeIterable) { + return ( + typeof maybeIterable === 'object' && + typeof (maybeIterable === null || maybeIterable === void 0 + ? void 0 + : maybeIterable[Symbol.iterator]) === 'function' + ); +} + + +/***/ }), + +/***/ 95865: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.isObjectLike = isObjectLike; + +/** + * Return true if `value` is object-like. A value is object-like if it's not + * `null` and has a `typeof` result of "object". + */ +function isObjectLike(value) { + return typeof value == 'object' && value !== null; +} + + +/***/ }), + +/***/ 93910: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.isPromise = isPromise; + +/** + * Returns true if the value acts like a Promise, i.e. has a "then" function, + * otherwise returns false. + */ +function isPromise(value) { + return ( + typeof (value === null || value === void 0 ? void 0 : value.then) === + 'function' + ); +} + + +/***/ }), + +/***/ 10711: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.keyMap = keyMap; + +/** + * Creates a keyed JS object from an array, given a function to produce the keys + * for each value in the array. + * + * This provides a convenient lookup for the array items if the key function + * produces unique results. + * ```ts + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' } + * ] + * + * const entriesByName = keyMap( + * phoneBook, + * entry => entry.name + * ) + * + * // { + * // Jon: { name: 'Jon', num: '555-1234' }, + * // Jenny: { name: 'Jenny', num: '867-5309' } + * // } + * + * const jennyEntry = entriesByName['Jenny'] + * + * // { name: 'Jenny', num: '857-6309' } + * ``` + */ +function keyMap(list, keyFn) { + const result = Object.create(null); + + for (const item of list) { + result[keyFn(item)] = item; + } + + return result; +} + + +/***/ }), + +/***/ 49268: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.keyValMap = keyValMap; + +/** + * Creates a keyed JS object from an array, given a function to produce the keys + * and a function to produce the values from each item in the array. + * ```ts + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' } + * ] + * + * // { Jon: '555-1234', Jenny: '867-5309' } + * const phonesByName = keyValMap( + * phoneBook, + * entry => entry.name, + * entry => entry.num + * ) + * ``` + */ +function keyValMap(list, keyFn, valFn) { + const result = Object.create(null); + + for (const item of list) { + result[keyFn(item)] = valFn(item); + } + + return result; +} + + +/***/ }), + +/***/ 32223: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.mapValue = mapValue; + +/** + * Creates an object map with the same keys as `map` and values generated by + * running each value of `map` thru `fn`. + */ +function mapValue(map, fn) { + const result = Object.create(null); + + for (const key of Object.keys(map)) { + result[key] = fn(map[key], key); + } + + return result; +} + + +/***/ }), + +/***/ 64217: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.memoize3 = memoize3; + +/** + * Memoizes the provided three-argument function. + */ +function memoize3(fn) { + let cache0; + return function memoized(a1, a2, a3) { + if (cache0 === undefined) { + cache0 = new WeakMap(); } - async _error(error) { - try { - for (const hook of this.options.hooks.beforeError) { - // eslint-disable-next-line no-await-in-loop - error = await hook(error); - } - } - catch (error_) { - error = new RequestError(error_.message, error_, this); - } - this.destroy(error); + + let cache1 = cache0.get(a1); + + if (cache1 === undefined) { + cache1 = new WeakMap(); + cache0.set(a1, cache1); } - _beforeError(error) { - if (this[kStopReading]) { - return; - } - const { options } = this; - const retryCount = this.retryCount + 1; - this[kStopReading] = true; - if (!(error instanceof RequestError)) { - error = new RequestError(error.message, error, this); - } - const typedError = error; - const { response } = typedError; - void (async () => { - if (response && !response.body) { - response.setEncoding(this._readableState.encoding); - try { - response.rawBody = await get_buffer_1.default(response); - response.body = response.rawBody.toString(); - } - catch (_a) { } - } - if (this.listenerCount('retry') !== 0) { - let backoff; - try { - let retryAfter; - if (response && 'retry-after' in response.headers) { - retryAfter = Number(response.headers['retry-after']); - if (Number.isNaN(retryAfter)) { - retryAfter = Date.parse(response.headers['retry-after']) - Date.now(); - if (retryAfter <= 0) { - retryAfter = 1; - } - } - else { - retryAfter *= 1000; - } - } - backoff = await options.retry.calculateDelay({ - attemptCount: retryCount, - retryOptions: options.retry, - error: typedError, - retryAfter, - computedValue: calculate_retry_delay_1.default({ - attemptCount: retryCount, - retryOptions: options.retry, - error: typedError, - retryAfter, - computedValue: 0 - }) - }); - } - catch (error_) { - void this._error(new RequestError(error_.message, error_, this)); - return; - } - if (backoff) { - const retry = async () => { - try { - for (const hook of this.options.hooks.beforeRetry) { - // eslint-disable-next-line no-await-in-loop - await hook(this.options, typedError, retryCount); - } - } - catch (error_) { - void this._error(new RequestError(error_.message, error, this)); - return; - } - // Something forced us to abort the retry - if (this.destroyed) { - return; - } - this.destroy(); - this.emit('retry', retryCount, error); - }; - this[kRetryTimeout] = setTimeout(retry, backoff); - return; - } - } - void this._error(typedError); - })(); + + let cache2 = cache1.get(a2); + + if (cache2 === undefined) { + cache2 = new WeakMap(); + cache1.set(a2, cache2); } - _read() { - this[kTriggerRead] = true; - const response = this[kResponse]; - if (response && !this[kStopReading]) { - // We cannot put this in the `if` above - // because `.read()` also triggers the `end` event - if (response.readableLength) { - this[kTriggerRead] = false; - } - let data; - while ((data = response.read()) !== null) { - this[kDownloadedSize] += data.length; - this[kStartedReading] = true; - const progress = this.downloadProgress; - if (progress.percent < 1) { - this.emit('downloadProgress', progress); - } - this.push(data); - } - } + + let fnResult = cache2.get(a3); + + if (fnResult === undefined) { + fnResult = fn(a1, a2, a3); + cache2.set(a3, fnResult); } - // Node.js 12 has incorrect types, so the encoding must be a string - _write(chunk, encoding, callback) { - const write = () => { - this._writeRequest(chunk, encoding, callback); - }; - if (this.requestInitialized) { - write(); - } - else { - this[kJobs].push(write); - } + + return fnResult; + }; +} + + +/***/ }), + +/***/ 20038: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.naturalCompare = naturalCompare; + +/** + * Returns a number indicating whether a reference string comes before, or after, + * or is the same as the given string in natural sort order. + * + * See: https://en.wikipedia.org/wiki/Natural_sort_order + * + */ +function naturalCompare(aStr, bStr) { + let aIndex = 0; + let bIndex = 0; + + while (aIndex < aStr.length && bIndex < bStr.length) { + let aChar = aStr.charCodeAt(aIndex); + let bChar = bStr.charCodeAt(bIndex); + + if (isDigit(aChar) && isDigit(bChar)) { + let aNum = 0; + + do { + ++aIndex; + aNum = aNum * 10 + aChar - DIGIT_0; + aChar = aStr.charCodeAt(aIndex); + } while (isDigit(aChar) && aNum > 0); + + let bNum = 0; + + do { + ++bIndex; + bNum = bNum * 10 + bChar - DIGIT_0; + bChar = bStr.charCodeAt(bIndex); + } while (isDigit(bChar) && bNum > 0); + + if (aNum < bNum) { + return -1; + } + + if (aNum > bNum) { + return 1; + } + } else { + if (aChar < bChar) { + return -1; + } + + if (aChar > bChar) { + return 1; + } + + ++aIndex; + ++bIndex; } - _writeRequest(chunk, encoding, callback) { - if (this[kRequest].destroyed) { - // Probably the `ClientRequest` instance will throw - return; - } - this._progressCallbacks.push(() => { - this[kUploadedSize] += Buffer.byteLength(chunk, encoding); - const progress = this.uploadProgress; - if (progress.percent < 1) { - this.emit('uploadProgress', progress); - } - }); - // TODO: What happens if it's from cache? Then this[kRequest] won't be defined. - this[kRequest].write(chunk, encoding, (error) => { - if (!error && this._progressCallbacks.length > 0) { - this._progressCallbacks.shift()(); - } - callback(error); - }); + } + + return aStr.length - bStr.length; +} + +const DIGIT_0 = 48; +const DIGIT_9 = 57; + +function isDigit(code) { + return !isNaN(code) && DIGIT_0 <= code && code <= DIGIT_9; +} + + +/***/ }), + +/***/ 94281: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.printPathArray = printPathArray; + +/** + * Build a string describing the path. + */ +function printPathArray(path) { + return path + .map((key) => + typeof key === 'number' ? '[' + key.toString() + ']' : '.' + key, + ) + .join(''); +} + + +/***/ }), + +/***/ 46804: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.promiseForObject = promiseForObject; + +/** + * This function transforms a JS object `ObjMap>` into + * a `Promise>` + * + * This is akin to bluebird's `Promise.props`, but implemented only using + * `Promise.all` so it will work with any implementation of ES6 promises. + */ +function promiseForObject(object) { + return Promise.all(Object.values(object)).then((resolvedValues) => { + const resolvedObject = Object.create(null); + + for (const [i, key] of Object.keys(object).entries()) { + resolvedObject[key] = resolvedValues[i]; } - _final(callback) { - const endRequest = () => { - // FIX: Node.js 10 calls the write callback AFTER the end callback! - while (this._progressCallbacks.length !== 0) { - this._progressCallbacks.shift()(); - } - // We need to check if `this[kRequest]` is present, - // because it isn't when we use cache. - if (!(kRequest in this)) { - callback(); - return; - } - if (this[kRequest].destroyed) { - callback(); - return; - } - this[kRequest].end((error) => { - if (!error) { - this[kBodySize] = this[kUploadedSize]; - this.emit('uploadProgress', this.uploadProgress); - this[kRequest].emit('upload-complete'); - } - callback(error); - }); - }; - if (this.requestInitialized) { - endRequest(); - } - else { - this[kJobs].push(endRequest); - } + + return resolvedObject; + }); +} + + +/***/ }), + +/***/ 63925: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.promiseReduce = promiseReduce; + +var _isPromise = __nccwpck_require__(93910); + +/** + * Similar to Array.prototype.reduce(), however the reducing callback may return + * a Promise, in which case reduction will continue after each promise resolves. + * + * If the callback does not return a Promise, then this function will also not + * return a Promise. + */ +function promiseReduce(values, callbackFn, initialValue) { + let accumulator = initialValue; + + for (const value of values) { + accumulator = (0, _isPromise.isPromise)(accumulator) + ? accumulator.then((resolved) => callbackFn(resolved, value)) + : callbackFn(accumulator, value); + } + + return accumulator; +} + + +/***/ }), + +/***/ 57704: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.suggestionList = suggestionList; + +var _naturalCompare = __nccwpck_require__(20038); + +/** + * Given an invalid input string and a list of valid options, returns a filtered + * list of valid options sorted based on their similarity with the input. + */ +function suggestionList(input, options) { + const optionsByDistance = Object.create(null); + const lexicalDistance = new LexicalDistance(input); + const threshold = Math.floor(input.length * 0.4) + 1; + + for (const option of options) { + const distance = lexicalDistance.measure(option, threshold); + + if (distance !== undefined) { + optionsByDistance[option] = distance; } - _destroy(error, callback) { - var _a; - this[kStopReading] = true; - // Prevent further retries - clearTimeout(this[kRetryTimeout]); - if (kRequest in this) { - this[kCancelTimeouts](); - // TODO: Remove the next `if` when these get fixed: - // - https://github.com/nodejs/node/issues/32851 - if (!((_a = this[kResponse]) === null || _a === void 0 ? void 0 : _a.complete)) { - this[kRequest].destroy(); - } - } - if (error !== null && !is_1.default.undefined(error) && !(error instanceof RequestError)) { - error = new RequestError(error.message, error, this); - } - callback(error); + } + + return Object.keys(optionsByDistance).sort((a, b) => { + const distanceDiff = optionsByDistance[a] - optionsByDistance[b]; + return distanceDiff !== 0 + ? distanceDiff + : (0, _naturalCompare.naturalCompare)(a, b); + }); +} +/** + * Computes the lexical distance between strings A and B. + * + * The "distance" between two strings is given by counting the minimum number + * of edits needed to transform string A into string B. An edit can be an + * insertion, deletion, or substitution of a single character, or a swap of two + * adjacent characters. + * + * Includes a custom alteration from Damerau-Levenshtein to treat case changes + * as a single edit which helps identify mis-cased values with an edit distance + * of 1. + * + * This distance can be useful for detecting typos in input or sorting + */ + +class LexicalDistance { + constructor(input) { + this._input = input; + this._inputLowerCase = input.toLowerCase(); + this._inputArray = stringToArray(this._inputLowerCase); + this._rows = [ + new Array(input.length + 1).fill(0), + new Array(input.length + 1).fill(0), + new Array(input.length + 1).fill(0), + ]; + } + + measure(option, threshold) { + if (this._input === option) { + return 0; } - get _isAboutToError() { - return this[kStopReading]; + + const optionLowerCase = option.toLowerCase(); // Any case change counts as a single edit + + if (this._inputLowerCase === optionLowerCase) { + return 1; } - /** - The remote IP address. - */ - get ip() { - var _a; - return (_a = this.socket) === null || _a === void 0 ? void 0 : _a.remoteAddress; + + let a = stringToArray(optionLowerCase); + let b = this._inputArray; + + if (a.length < b.length) { + const tmp = a; + a = b; + b = tmp; } - /** - Indicates whether the request has been aborted or not. - */ - get aborted() { - var _a, _b, _c; - return ((_b = (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.destroyed) !== null && _b !== void 0 ? _b : this.destroyed) && !((_c = this[kOriginalResponse]) === null || _c === void 0 ? void 0 : _c.complete); + + const aLength = a.length; + const bLength = b.length; + + if (aLength - bLength > threshold) { + return undefined; } - get socket() { - var _a, _b; - return (_b = (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.socket) !== null && _b !== void 0 ? _b : undefined; + + const rows = this._rows; + + for (let j = 0; j <= bLength; j++) { + rows[0][j] = j; } - /** - Progress event for downloading (receiving a response). - */ - get downloadProgress() { - let percent; - if (this[kResponseSize]) { - percent = this[kDownloadedSize] / this[kResponseSize]; - } - else if (this[kResponseSize] === this[kDownloadedSize]) { - percent = 1; + + for (let i = 1; i <= aLength; i++) { + const upRow = rows[(i - 1) % 3]; + const currentRow = rows[i % 3]; + let smallestCell = (currentRow[0] = i); + + for (let j = 1; j <= bLength; j++) { + const cost = a[i - 1] === b[j - 1] ? 0 : 1; + let currentCell = Math.min( + upRow[j] + 1, // delete + currentRow[j - 1] + 1, // insert + upRow[j - 1] + cost, // substitute + ); + + if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { + // transposition + const doubleDiagonalCell = rows[(i - 2) % 3][j - 2]; + currentCell = Math.min(currentCell, doubleDiagonalCell + 1); } - else { - percent = 0; + + if (currentCell < smallestCell) { + smallestCell = currentCell; } - return { - percent, - transferred: this[kDownloadedSize], - total: this[kResponseSize] - }; + + currentRow[j] = currentCell; + } // Early exit, since distance can't go smaller than smallest element of the previous row. + + if (smallestCell > threshold) { + return undefined; + } } - /** - Progress event for uploading (sending a request). - */ - get uploadProgress() { - let percent; - if (this[kBodySize]) { - percent = this[kUploadedSize] / this[kBodySize]; - } - else if (this[kBodySize] === this[kUploadedSize]) { - percent = 1; - } - else { - percent = 0; + + const distance = rows[aLength % 3][bLength]; + return distance <= threshold ? distance : undefined; + } +} + +function stringToArray(str) { + const strLength = str.length; + const array = new Array(strLength); + + for (let i = 0; i < strLength; ++i) { + array[i] = str.charCodeAt(i); + } + + return array; +} + + +/***/ }), + +/***/ 15472: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.toError = toError; + +var _inspect = __nccwpck_require__(10102); + +/** + * Sometimes a non-error is thrown, wrap it as an Error instance to ensure a consistent Error interface. + */ +function toError(thrownValue) { + return thrownValue instanceof Error + ? thrownValue + : new NonErrorThrown(thrownValue); +} + +class NonErrorThrown extends Error { + constructor(thrownValue) { + super('Unexpected error value: ' + (0, _inspect.inspect)(thrownValue)); + this.name = 'NonErrorThrown'; + this.thrownValue = thrownValue; + } +} + + +/***/ }), + +/***/ 74728: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.toObjMap = toObjMap; + +function toObjMap(obj) { + if (obj == null) { + return Object.create(null); + } + + if (Object.getPrototypeOf(obj) === null) { + return obj; + } + + const map = Object.create(null); + + for (const [key, value] of Object.entries(obj)) { + map[key] = value; + } + + return map; +} + + +/***/ }), + +/***/ 45494: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.Token = + exports.QueryDocumentKeys = + exports.OperationTypeNode = + exports.Location = + void 0; +exports.isNode = isNode; + +/** + * Contains a range of UTF-8 character offsets and token references that + * identify the region of the source from which the AST derived. + */ +class Location { + /** + * The character offset at which this Node begins. + */ + + /** + * The character offset at which this Node ends. + */ + + /** + * The Token at which this Node begins. + */ + + /** + * The Token at which this Node ends. + */ + + /** + * The Source document the AST represents. + */ + constructor(startToken, endToken, source) { + this.start = startToken.start; + this.end = endToken.end; + this.startToken = startToken; + this.endToken = endToken; + this.source = source; + } + + get [Symbol.toStringTag]() { + return 'Location'; + } + + toJSON() { + return { + start: this.start, + end: this.end, + }; + } +} +/** + * Represents a range of characters represented by a lexical token + * within a Source. + */ + +exports.Location = Location; + +class Token { + /** + * The kind of Token. + */ + + /** + * The character offset at which this Node begins. + */ + + /** + * The character offset at which this Node ends. + */ + + /** + * The 1-indexed line number on which this Token appears. + */ + + /** + * The 1-indexed column number at which this Token begins. + */ + + /** + * For non-punctuation tokens, represents the interpreted value of the token. + * + * Note: is undefined for punctuation tokens, but typed as string for + * convenience in the parser. + */ + + /** + * Tokens exist as nodes in a double-linked-list amongst all tokens + * including ignored tokens. is always the first node and + * the last. + */ + constructor(kind, start, end, line, column, value) { + this.kind = kind; + this.start = start; + this.end = end; + this.line = line; + this.column = column; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + + this.value = value; + this.prev = null; + this.next = null; + } + + get [Symbol.toStringTag]() { + return 'Token'; + } + + toJSON() { + return { + kind: this.kind, + value: this.value, + line: this.line, + column: this.column, + }; + } +} +/** + * The list of all possible AST node types. + */ + +exports.Token = Token; + +/** + * @internal + */ +const QueryDocumentKeys = { + Name: [], + Document: ['definitions'], + OperationDefinition: [ + 'name', + 'variableDefinitions', + 'directives', + 'selectionSet', + ], + VariableDefinition: ['variable', 'type', 'defaultValue', 'directives'], + Variable: ['name'], + SelectionSet: ['selections'], + Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'], + Argument: ['name', 'value'], + FragmentSpread: ['name', 'directives'], + InlineFragment: ['typeCondition', 'directives', 'selectionSet'], + FragmentDefinition: [ + 'name', // Note: fragment variable definitions are deprecated and will removed in v17.0.0 + 'variableDefinitions', + 'typeCondition', + 'directives', + 'selectionSet', + ], + IntValue: [], + FloatValue: [], + StringValue: [], + BooleanValue: [], + NullValue: [], + EnumValue: [], + ListValue: ['values'], + ObjectValue: ['fields'], + ObjectField: ['name', 'value'], + Directive: ['name', 'arguments'], + NamedType: ['name'], + ListType: ['type'], + NonNullType: ['type'], + SchemaDefinition: ['description', 'directives', 'operationTypes'], + OperationTypeDefinition: ['type'], + ScalarTypeDefinition: ['description', 'name', 'directives'], + ObjectTypeDefinition: [ + 'description', + 'name', + 'interfaces', + 'directives', + 'fields', + ], + FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'], + InputValueDefinition: [ + 'description', + 'name', + 'type', + 'defaultValue', + 'directives', + ], + InterfaceTypeDefinition: [ + 'description', + 'name', + 'interfaces', + 'directives', + 'fields', + ], + UnionTypeDefinition: ['description', 'name', 'directives', 'types'], + EnumTypeDefinition: ['description', 'name', 'directives', 'values'], + EnumValueDefinition: ['description', 'name', 'directives'], + InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'], + DirectiveDefinition: ['description', 'name', 'arguments', 'locations'], + SchemaExtension: ['directives', 'operationTypes'], + ScalarTypeExtension: ['name', 'directives'], + ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'], + InterfaceTypeExtension: ['name', 'interfaces', 'directives', 'fields'], + UnionTypeExtension: ['name', 'directives', 'types'], + EnumTypeExtension: ['name', 'directives', 'values'], + InputObjectTypeExtension: ['name', 'directives', 'fields'], +}; +exports.QueryDocumentKeys = QueryDocumentKeys; +const kindValues = new Set(Object.keys(QueryDocumentKeys)); +/** + * @internal + */ + +function isNode(maybeNode) { + const maybeKind = + maybeNode === null || maybeNode === void 0 ? void 0 : maybeNode.kind; + return typeof maybeKind === 'string' && kindValues.has(maybeKind); +} +/** Name */ + +var OperationTypeNode; +exports.OperationTypeNode = OperationTypeNode; + +(function (OperationTypeNode) { + OperationTypeNode['QUERY'] = 'query'; + OperationTypeNode['MUTATION'] = 'mutation'; + OperationTypeNode['SUBSCRIPTION'] = 'subscription'; +})(OperationTypeNode || (exports.OperationTypeNode = OperationTypeNode = {})); + + +/***/ }), + +/***/ 52671: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.dedentBlockStringLines = dedentBlockStringLines; +exports.isPrintableAsBlockString = isPrintableAsBlockString; +exports.printBlockString = printBlockString; + +var _characterClasses = __nccwpck_require__(7234); + +/** + * Produces the value of a block string from its parsed raw value, similar to + * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc. + * + * This implements the GraphQL spec's BlockStringValue() static algorithm. + * + * @internal + */ +function dedentBlockStringLines(lines) { + var _firstNonEmptyLine2; + + let commonIndent = Number.MAX_SAFE_INTEGER; + let firstNonEmptyLine = null; + let lastNonEmptyLine = -1; + + for (let i = 0; i < lines.length; ++i) { + var _firstNonEmptyLine; + + const line = lines[i]; + const indent = leadingWhitespace(line); + + if (indent === line.length) { + continue; // skip empty lines + } + + firstNonEmptyLine = + (_firstNonEmptyLine = firstNonEmptyLine) !== null && + _firstNonEmptyLine !== void 0 + ? _firstNonEmptyLine + : i; + lastNonEmptyLine = i; + + if (i !== 0 && indent < commonIndent) { + commonIndent = indent; + } + } + + return lines // Remove common indentation from all lines but first. + .map((line, i) => (i === 0 ? line : line.slice(commonIndent))) // Remove leading and trailing blank lines. + .slice( + (_firstNonEmptyLine2 = firstNonEmptyLine) !== null && + _firstNonEmptyLine2 !== void 0 + ? _firstNonEmptyLine2 + : 0, + lastNonEmptyLine + 1, + ); +} + +function leadingWhitespace(str) { + let i = 0; + + while ( + i < str.length && + (0, _characterClasses.isWhiteSpace)(str.charCodeAt(i)) + ) { + ++i; + } + + return i; +} +/** + * @internal + */ + +function isPrintableAsBlockString(value) { + if (value === '') { + return true; // empty string is printable + } + + let isEmptyLine = true; + let hasIndent = false; + let hasCommonIndent = true; + let seenNonEmptyLine = false; + + for (let i = 0; i < value.length; ++i) { + switch (value.codePointAt(i)) { + case 0x0000: + case 0x0001: + case 0x0002: + case 0x0003: + case 0x0004: + case 0x0005: + case 0x0006: + case 0x0007: + case 0x0008: + case 0x000b: + case 0x000c: + case 0x000e: + case 0x000f: + return false; + // Has non-printable characters + + case 0x000d: + // \r + return false; + // Has \r or \r\n which will be replaced as \n + + case 10: + // \n + if (isEmptyLine && !seenNonEmptyLine) { + return false; // Has leading new line } - return { - percent, - transferred: this[kUploadedSize], - total: this[kBodySize] - }; + + seenNonEmptyLine = true; + isEmptyLine = true; + hasIndent = false; + break; + + case 9: // \t + + case 32: + // + hasIndent || (hasIndent = isEmptyLine); + break; + + default: + hasCommonIndent && (hasCommonIndent = hasIndent); + isEmptyLine = false; } - /** - The object contains the following properties: + } - - `start` - Time when the request started. - - `socket` - Time when a socket was assigned to the request. - - `lookup` - Time when the DNS lookup finished. - - `connect` - Time when the socket successfully connected. - - `secureConnect` - Time when the socket securely connected. - - `upload` - Time when the request finished uploading. - - `response` - Time when the request fired `response` event. - - `end` - Time when the response fired `end` event. - - `error` - Time when the request fired `error` event. - - `abort` - Time when the request fired `abort` event. - - `phases` - - `wait` - `timings.socket - timings.start` - - `dns` - `timings.lookup - timings.socket` - - `tcp` - `timings.connect - timings.lookup` - - `tls` - `timings.secureConnect - timings.connect` - - `request` - `timings.upload - (timings.secureConnect || timings.connect)` - - `firstByte` - `timings.response - timings.upload` - - `download` - `timings.end - timings.response` - - `total` - `(timings.end || timings.error || timings.abort) - timings.start` + if (isEmptyLine) { + return false; // Has trailing empty lines + } + + if (hasCommonIndent && seenNonEmptyLine) { + return false; // Has internal indent + } + + return true; +} +/** + * Print a block string in the indented block form by adding a leading and + * trailing blank line. However, if a block string starts with whitespace and is + * a single-line, adding a leading blank line would strip that whitespace. + * + * @internal + */ + +function printBlockString(value, options) { + const escapedValue = value.replace(/"""/g, '\\"""'); // Expand a block string's raw value into independent lines. + + const lines = escapedValue.split(/\r\n|[\n\r]/g); + const isSingleLine = lines.length === 1; // If common indentation is found we can fix some of those cases by adding leading new line + + const forceLeadingNewLine = + lines.length > 1 && + lines + .slice(1) + .every( + (line) => + line.length === 0 || + (0, _characterClasses.isWhiteSpace)(line.charCodeAt(0)), + ); // Trailing triple quotes just looks confusing but doesn't force trailing new line + + const hasTrailingTripleQuotes = escapedValue.endsWith('\\"""'); // Trailing quote (single or double) or slash forces trailing new line + + const hasTrailingQuote = value.endsWith('"') && !hasTrailingTripleQuotes; + const hasTrailingSlash = value.endsWith('\\'); + const forceTrailingNewline = hasTrailingQuote || hasTrailingSlash; + const printAsMultipleLines = + !(options !== null && options !== void 0 && options.minimize) && // add leading and trailing new lines only if it improves readability + (!isSingleLine || + value.length > 70 || + forceTrailingNewline || + forceLeadingNewLine || + hasTrailingTripleQuotes); + let result = ''; // Format a multi-line block quote to account for leading space. + + const skipLeadingNewLine = + isSingleLine && (0, _characterClasses.isWhiteSpace)(value.charCodeAt(0)); + + if ((printAsMultipleLines && !skipLeadingNewLine) || forceLeadingNewLine) { + result += '\n'; + } + + result += escapedValue; + + if (printAsMultipleLines || forceTrailingNewline) { + result += '\n'; + } + + return '"""' + result + '"""'; +} + + +/***/ }), + +/***/ 7234: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.isDigit = isDigit; +exports.isLetter = isLetter; +exports.isNameContinue = isNameContinue; +exports.isNameStart = isNameStart; +exports.isWhiteSpace = isWhiteSpace; + +/** + * ``` + * WhiteSpace :: + * - "Horizontal Tab (U+0009)" + * - "Space (U+0020)" + * ``` + * @internal + */ +function isWhiteSpace(code) { + return code === 0x0009 || code === 0x0020; +} +/** + * ``` + * Digit :: one of + * - `0` `1` `2` `3` `4` `5` `6` `7` `8` `9` + * ``` + * @internal + */ + +function isDigit(code) { + return code >= 0x0030 && code <= 0x0039; +} +/** + * ``` + * Letter :: one of + * - `A` `B` `C` `D` `E` `F` `G` `H` `I` `J` `K` `L` `M` + * - `N` `O` `P` `Q` `R` `S` `T` `U` `V` `W` `X` `Y` `Z` + * - `a` `b` `c` `d` `e` `f` `g` `h` `i` `j` `k` `l` `m` + * - `n` `o` `p` `q` `r` `s` `t` `u` `v` `w` `x` `y` `z` + * ``` + * @internal + */ + +function isLetter(code) { + return ( + (code >= 0x0061 && code <= 0x007a) || // A-Z + (code >= 0x0041 && code <= 0x005a) // a-z + ); +} +/** + * ``` + * NameStart :: + * - Letter + * - `_` + * ``` + * @internal + */ + +function isNameStart(code) { + return isLetter(code) || code === 0x005f; +} +/** + * ``` + * NameContinue :: + * - Letter + * - Digit + * - `_` + * ``` + * @internal + */ + +function isNameContinue(code) { + return isLetter(code) || isDigit(code) || code === 0x005f; +} + + +/***/ }), + +/***/ 71553: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.DirectiveLocation = void 0; + +/** + * The set of allowed directive location values. + */ +var DirectiveLocation; +exports.DirectiveLocation = DirectiveLocation; + +(function (DirectiveLocation) { + DirectiveLocation['QUERY'] = 'QUERY'; + DirectiveLocation['MUTATION'] = 'MUTATION'; + DirectiveLocation['SUBSCRIPTION'] = 'SUBSCRIPTION'; + DirectiveLocation['FIELD'] = 'FIELD'; + DirectiveLocation['FRAGMENT_DEFINITION'] = 'FRAGMENT_DEFINITION'; + DirectiveLocation['FRAGMENT_SPREAD'] = 'FRAGMENT_SPREAD'; + DirectiveLocation['INLINE_FRAGMENT'] = 'INLINE_FRAGMENT'; + DirectiveLocation['VARIABLE_DEFINITION'] = 'VARIABLE_DEFINITION'; + DirectiveLocation['SCHEMA'] = 'SCHEMA'; + DirectiveLocation['SCALAR'] = 'SCALAR'; + DirectiveLocation['OBJECT'] = 'OBJECT'; + DirectiveLocation['FIELD_DEFINITION'] = 'FIELD_DEFINITION'; + DirectiveLocation['ARGUMENT_DEFINITION'] = 'ARGUMENT_DEFINITION'; + DirectiveLocation['INTERFACE'] = 'INTERFACE'; + DirectiveLocation['UNION'] = 'UNION'; + DirectiveLocation['ENUM'] = 'ENUM'; + DirectiveLocation['ENUM_VALUE'] = 'ENUM_VALUE'; + DirectiveLocation['INPUT_OBJECT'] = 'INPUT_OBJECT'; + DirectiveLocation['INPUT_FIELD_DEFINITION'] = 'INPUT_FIELD_DEFINITION'; +})(DirectiveLocation || (exports.DirectiveLocation = DirectiveLocation = {})); +/** + * The enum type representing the directive location values. + * + * @deprecated Please use `DirectiveLocation`. Will be remove in v17. + */ + + +/***/ }), + +/***/ 89537: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +Object.defineProperty(exports, "BREAK", ({ + enumerable: true, + get: function () { + return _visitor.BREAK; + }, +})); +Object.defineProperty(exports, "DirectiveLocation", ({ + enumerable: true, + get: function () { + return _directiveLocation.DirectiveLocation; + }, +})); +Object.defineProperty(exports, "Kind", ({ + enumerable: true, + get: function () { + return _kinds.Kind; + }, +})); +Object.defineProperty(exports, "Lexer", ({ + enumerable: true, + get: function () { + return _lexer.Lexer; + }, +})); +Object.defineProperty(exports, "Location", ({ + enumerable: true, + get: function () { + return _ast.Location; + }, +})); +Object.defineProperty(exports, "OperationTypeNode", ({ + enumerable: true, + get: function () { + return _ast.OperationTypeNode; + }, +})); +Object.defineProperty(exports, "Source", ({ + enumerable: true, + get: function () { + return _source.Source; + }, +})); +Object.defineProperty(exports, "Token", ({ + enumerable: true, + get: function () { + return _ast.Token; + }, +})); +Object.defineProperty(exports, "TokenKind", ({ + enumerable: true, + get: function () { + return _tokenKind.TokenKind; + }, +})); +Object.defineProperty(exports, "getEnterLeaveForKind", ({ + enumerable: true, + get: function () { + return _visitor.getEnterLeaveForKind; + }, +})); +Object.defineProperty(exports, "getLocation", ({ + enumerable: true, + get: function () { + return _location.getLocation; + }, +})); +Object.defineProperty(exports, "getVisitFn", ({ + enumerable: true, + get: function () { + return _visitor.getVisitFn; + }, +})); +Object.defineProperty(exports, "isConstValueNode", ({ + enumerable: true, + get: function () { + return _predicates.isConstValueNode; + }, +})); +Object.defineProperty(exports, "isDefinitionNode", ({ + enumerable: true, + get: function () { + return _predicates.isDefinitionNode; + }, +})); +Object.defineProperty(exports, "isExecutableDefinitionNode", ({ + enumerable: true, + get: function () { + return _predicates.isExecutableDefinitionNode; + }, +})); +Object.defineProperty(exports, "isSelectionNode", ({ + enumerable: true, + get: function () { + return _predicates.isSelectionNode; + }, +})); +Object.defineProperty(exports, "isTypeDefinitionNode", ({ + enumerable: true, + get: function () { + return _predicates.isTypeDefinitionNode; + }, +})); +Object.defineProperty(exports, "isTypeExtensionNode", ({ + enumerable: true, + get: function () { + return _predicates.isTypeExtensionNode; + }, +})); +Object.defineProperty(exports, "isTypeNode", ({ + enumerable: true, + get: function () { + return _predicates.isTypeNode; + }, +})); +Object.defineProperty(exports, "isTypeSystemDefinitionNode", ({ + enumerable: true, + get: function () { + return _predicates.isTypeSystemDefinitionNode; + }, +})); +Object.defineProperty(exports, "isTypeSystemExtensionNode", ({ + enumerable: true, + get: function () { + return _predicates.isTypeSystemExtensionNode; + }, +})); +Object.defineProperty(exports, "isValueNode", ({ + enumerable: true, + get: function () { + return _predicates.isValueNode; + }, +})); +Object.defineProperty(exports, "parse", ({ + enumerable: true, + get: function () { + return _parser.parse; + }, +})); +Object.defineProperty(exports, "parseConstValue", ({ + enumerable: true, + get: function () { + return _parser.parseConstValue; + }, +})); +Object.defineProperty(exports, "parseType", ({ + enumerable: true, + get: function () { + return _parser.parseType; + }, +})); +Object.defineProperty(exports, "parseValue", ({ + enumerable: true, + get: function () { + return _parser.parseValue; + }, +})); +Object.defineProperty(exports, "print", ({ + enumerable: true, + get: function () { + return _printer.print; + }, +})); +Object.defineProperty(exports, "printLocation", ({ + enumerable: true, + get: function () { + return _printLocation.printLocation; + }, +})); +Object.defineProperty(exports, "printSourceLocation", ({ + enumerable: true, + get: function () { + return _printLocation.printSourceLocation; + }, +})); +Object.defineProperty(exports, "visit", ({ + enumerable: true, + get: function () { + return _visitor.visit; + }, +})); +Object.defineProperty(exports, "visitInParallel", ({ + enumerable: true, + get: function () { + return _visitor.visitInParallel; + }, +})); - If something has not been measured yet, it will be `undefined`. +var _source = __nccwpck_require__(65521); - __Note__: The time is a `number` representing the milliseconds elapsed since the UNIX epoch. - */ - get timings() { - var _a; - return (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.timings; - } - /** - Whether the response was retrieved from the cache. - */ - get isFromCache() { - return this[kIsFromCache]; - } - pipe(destination, options) { - if (this[kStartedReading]) { - throw new Error('Failed to pipe. The response has been emitted already.'); - } - if (destination instanceof http_1.ServerResponse) { - this[kServerResponsesPiped].add(destination); - } - return super.pipe(destination, options); - } - unpipe(destination) { - if (destination instanceof http_1.ServerResponse) { - this[kServerResponsesPiped].delete(destination); - } - super.unpipe(destination); - return this; - } -} -exports["default"] = Request; +var _location = __nccwpck_require__(61922); +var _printLocation = __nccwpck_require__(35250); -/***/ }), +var _kinds = __nccwpck_require__(11927); -/***/ 94993: -/***/ ((__unused_webpack_module, exports) => { +var _tokenKind = __nccwpck_require__(91565); -"use strict"; +var _lexer = __nccwpck_require__(24605); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.dnsLookupIpVersionToFamily = exports.isDnsLookupIpVersion = void 0; -const conversionTable = { - auto: 0, - ipv4: 4, - ipv6: 6 -}; -exports.isDnsLookupIpVersion = (value) => { - return value in conversionTable; -}; -exports.dnsLookupIpVersionToFamily = (dnsLookupIpVersion) => { - if (exports.isDnsLookupIpVersion(dnsLookupIpVersion)) { - return conversionTable[dnsLookupIpVersion]; - } - throw new Error('Invalid DNS lookup IP version'); -}; +var _parser = __nccwpck_require__(50655); +var _printer = __nccwpck_require__(68203); -/***/ }), +var _visitor = __nccwpck_require__(5678); -/***/ 94564: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +var _ast = __nccwpck_require__(45494); -"use strict"; +var _predicates = __nccwpck_require__(20535); -Object.defineProperty(exports, "__esModule", ({ value: true })); -const fs_1 = __nccwpck_require__(57147); -const util_1 = __nccwpck_require__(73837); -const is_1 = __nccwpck_require__(68977); -const is_form_data_1 = __nccwpck_require__(90040); -const statAsync = util_1.promisify(fs_1.stat); -exports["default"] = async (body, headers) => { - if (headers && 'content-length' in headers) { - return Number(headers['content-length']); - } - if (!body) { - return 0; - } - if (is_1.default.string(body)) { - return Buffer.byteLength(body); - } - if (is_1.default.buffer(body)) { - return body.length; - } - if (is_form_data_1.default(body)) { - return util_1.promisify(body.getLength.bind(body))(); - } - if (body instanceof fs_1.ReadStream) { - const { size } = await statAsync(body.path); - if (size === 0) { - return undefined; - } - return size; - } - return undefined; -}; +var _directiveLocation = __nccwpck_require__(71553); /***/ }), -/***/ 34500: +/***/ 11927: /***/ ((__unused_webpack_module, exports) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -// TODO: Update https://github.com/sindresorhus/get-stream -const getBuffer = async (stream) => { - const chunks = []; - let length = 0; - for await (const chunk of stream) { - chunks.push(chunk); - length += Buffer.byteLength(chunk); - } - if (Buffer.isBuffer(chunks[0])) { - return Buffer.concat(chunks, length); - } - return Buffer.from(chunks.join('')); -}; -exports["default"] = getBuffer; - - -/***/ }), - -/***/ 90040: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const is_1 = __nccwpck_require__(68977); -exports["default"] = (body) => is_1.default.nodeStream(body) && is_1.default.function_(body.getBoundary); - -/***/ }), - -/***/ 49298: -/***/ ((__unused_webpack_module, exports) => { +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.Kind = void 0; -"use strict"; +/** + * The set of allowed kind values for AST nodes. + */ +var Kind; +exports.Kind = Kind; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isResponseOk = void 0; -exports.isResponseOk = (response) => { - const { statusCode } = response; - const limitStatusCode = response.request.options.followRedirect ? 299 : 399; - return (statusCode >= 200 && statusCode <= limitStatusCode) || statusCode === 304; -}; +(function (Kind) { + Kind['NAME'] = 'Name'; + Kind['DOCUMENT'] = 'Document'; + Kind['OPERATION_DEFINITION'] = 'OperationDefinition'; + Kind['VARIABLE_DEFINITION'] = 'VariableDefinition'; + Kind['SELECTION_SET'] = 'SelectionSet'; + Kind['FIELD'] = 'Field'; + Kind['ARGUMENT'] = 'Argument'; + Kind['FRAGMENT_SPREAD'] = 'FragmentSpread'; + Kind['INLINE_FRAGMENT'] = 'InlineFragment'; + Kind['FRAGMENT_DEFINITION'] = 'FragmentDefinition'; + Kind['VARIABLE'] = 'Variable'; + Kind['INT'] = 'IntValue'; + Kind['FLOAT'] = 'FloatValue'; + Kind['STRING'] = 'StringValue'; + Kind['BOOLEAN'] = 'BooleanValue'; + Kind['NULL'] = 'NullValue'; + Kind['ENUM'] = 'EnumValue'; + Kind['LIST'] = 'ListValue'; + Kind['OBJECT'] = 'ObjectValue'; + Kind['OBJECT_FIELD'] = 'ObjectField'; + Kind['DIRECTIVE'] = 'Directive'; + Kind['NAMED_TYPE'] = 'NamedType'; + Kind['LIST_TYPE'] = 'ListType'; + Kind['NON_NULL_TYPE'] = 'NonNullType'; + Kind['SCHEMA_DEFINITION'] = 'SchemaDefinition'; + Kind['OPERATION_TYPE_DEFINITION'] = 'OperationTypeDefinition'; + Kind['SCALAR_TYPE_DEFINITION'] = 'ScalarTypeDefinition'; + Kind['OBJECT_TYPE_DEFINITION'] = 'ObjectTypeDefinition'; + Kind['FIELD_DEFINITION'] = 'FieldDefinition'; + Kind['INPUT_VALUE_DEFINITION'] = 'InputValueDefinition'; + Kind['INTERFACE_TYPE_DEFINITION'] = 'InterfaceTypeDefinition'; + Kind['UNION_TYPE_DEFINITION'] = 'UnionTypeDefinition'; + Kind['ENUM_TYPE_DEFINITION'] = 'EnumTypeDefinition'; + Kind['ENUM_VALUE_DEFINITION'] = 'EnumValueDefinition'; + Kind['INPUT_OBJECT_TYPE_DEFINITION'] = 'InputObjectTypeDefinition'; + Kind['DIRECTIVE_DEFINITION'] = 'DirectiveDefinition'; + Kind['SCHEMA_EXTENSION'] = 'SchemaExtension'; + Kind['SCALAR_TYPE_EXTENSION'] = 'ScalarTypeExtension'; + Kind['OBJECT_TYPE_EXTENSION'] = 'ObjectTypeExtension'; + Kind['INTERFACE_TYPE_EXTENSION'] = 'InterfaceTypeExtension'; + Kind['UNION_TYPE_EXTENSION'] = 'UnionTypeExtension'; + Kind['ENUM_TYPE_EXTENSION'] = 'EnumTypeExtension'; + Kind['INPUT_OBJECT_TYPE_EXTENSION'] = 'InputObjectTypeExtension'; +})(Kind || (exports.Kind = Kind = {})); +/** + * The enum type representing the possible kind values of AST nodes. + * + * @deprecated Please use `Kind`. Will be remove in v17. + */ /***/ }), -/***/ 9219: +/***/ 24605: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -/* istanbul ignore file: deprecated */ -const url_1 = __nccwpck_require__(57310); -const keys = [ - 'protocol', - 'host', - 'hostname', - 'port', - 'pathname', - 'search' -]; -exports["default"] = (origin, options) => { - var _a, _b; - if (options.path) { - if (options.pathname) { - throw new TypeError('Parameters `path` and `pathname` are mutually exclusive.'); - } - if (options.search) { - throw new TypeError('Parameters `path` and `search` are mutually exclusive.'); - } - if (options.searchParams) { - throw new TypeError('Parameters `path` and `searchParams` are mutually exclusive.'); - } - } - if (options.search && options.searchParams) { - throw new TypeError('Parameters `search` and `searchParams` are mutually exclusive.'); - } - if (!origin) { - if (!options.protocol) { - throw new TypeError('No URL protocol specified'); - } - origin = `${options.protocol}//${(_b = (_a = options.hostname) !== null && _a !== void 0 ? _a : options.host) !== null && _b !== void 0 ? _b : ''}`; - } - const url = new url_1.URL(origin); - if (options.path) { - const searchIndex = options.path.indexOf('?'); - if (searchIndex === -1) { - options.pathname = options.path; - } - else { - options.pathname = options.path.slice(0, searchIndex); - options.search = options.path.slice(searchIndex + 1); - } - delete options.path; - } - for (const key of keys) { - if (options[key]) { - url[key] = options[key].toString(); - } - } - return url; -}; - - -/***/ }), -/***/ 53021: -/***/ ((__unused_webpack_module, exports) => { +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.Lexer = void 0; +exports.isPunctuatorTokenKind = isPunctuatorTokenKind; -"use strict"; +var _syntaxError = __nccwpck_require__(52295); -Object.defineProperty(exports, "__esModule", ({ value: true })); -function default_1(from, to, events) { - const fns = {}; - for (const event of events) { - fns[event] = (...args) => { - to.emit(event, ...args); - }; - from.on(event, fns[event]); - } - return () => { - for (const event of events) { - from.off(event, fns[event]); - } - }; -} -exports["default"] = default_1; +var _ast = __nccwpck_require__(45494); +var _blockString = __nccwpck_require__(52671); -/***/ }), +var _characterClasses = __nccwpck_require__(7234); -/***/ 52454: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +var _tokenKind = __nccwpck_require__(91565); -"use strict"; +/** + * Given a Source object, creates a Lexer for that source. + * A Lexer is a stateful stream generator in that every time + * it is advanced, it returns the next token in the Source. Assuming the + * source lexes, the final Token emitted by the lexer will be of kind + * EOF, after which the lexer will repeatedly return the same EOF token + * whenever called. + */ +class Lexer { + /** + * The previously focused non-ignored token. + */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.TimeoutError = void 0; -const net = __nccwpck_require__(41808); -const unhandle_1 = __nccwpck_require__(81593); -const reentry = Symbol('reentry'); -const noop = () => { }; -class TimeoutError extends Error { - constructor(threshold, event) { - super(`Timeout awaiting '${event}' for ${threshold}ms`); - this.event = event; - this.name = 'TimeoutError'; - this.code = 'ETIMEDOUT'; - } -} -exports.TimeoutError = TimeoutError; -exports["default"] = (request, delays, options) => { - if (reentry in request) { - return noop; - } - request[reentry] = true; - const cancelers = []; - const { once, unhandleAll } = unhandle_1.default(); - const addTimeout = (delay, callback, event) => { - var _a; - const timeout = setTimeout(callback, delay, delay, event); - (_a = timeout.unref) === null || _a === void 0 ? void 0 : _a.call(timeout); - const cancel = () => { - clearTimeout(timeout); - }; - cancelers.push(cancel); - return cancel; - }; - const { host, hostname } = options; - const timeoutHandler = (delay, event) => { - request.destroy(new TimeoutError(delay, event)); - }; - const cancelTimeouts = () => { - for (const cancel of cancelers) { - cancel(); - } - unhandleAll(); - }; - request.once('error', error => { - cancelTimeouts(); - // Save original behavior - /* istanbul ignore next */ - if (request.listenerCount('error') === 0) { - throw error; - } - }); - request.once('close', cancelTimeouts); - once(request, 'response', (response) => { - once(response, 'end', cancelTimeouts); - }); - if (typeof delays.request !== 'undefined') { - addTimeout(delays.request, timeoutHandler, 'request'); - } - if (typeof delays.socket !== 'undefined') { - const socketTimeoutHandler = () => { - timeoutHandler(delays.socket, 'socket'); - }; - request.setTimeout(delays.socket, socketTimeoutHandler); - // `request.setTimeout(0)` causes a memory leak. - // We can just remove the listener and forget about the timer - it's unreffed. - // See https://github.com/sindresorhus/got/issues/690 - cancelers.push(() => { - request.removeListener('timeout', socketTimeoutHandler); - }); - } - once(request, 'socket', (socket) => { - var _a; - const { socketPath } = request; - /* istanbul ignore next: hard to test */ - if (socket.connecting) { - const hasPath = Boolean(socketPath !== null && socketPath !== void 0 ? socketPath : net.isIP((_a = hostname !== null && hostname !== void 0 ? hostname : host) !== null && _a !== void 0 ? _a : '') !== 0); - if (typeof delays.lookup !== 'undefined' && !hasPath && typeof socket.address().address === 'undefined') { - const cancelTimeout = addTimeout(delays.lookup, timeoutHandler, 'lookup'); - once(socket, 'lookup', cancelTimeout); - } - if (typeof delays.connect !== 'undefined') { - const timeConnect = () => addTimeout(delays.connect, timeoutHandler, 'connect'); - if (hasPath) { - once(socket, 'connect', timeConnect()); - } - else { - once(socket, 'lookup', (error) => { - if (error === null) { - once(socket, 'connect', timeConnect()); - } - }); - } - } - if (typeof delays.secureConnect !== 'undefined' && options.protocol === 'https:') { - once(socket, 'connect', () => { - const cancelTimeout = addTimeout(delays.secureConnect, timeoutHandler, 'secureConnect'); - once(socket, 'secureConnect', cancelTimeout); - }); - } - } - if (typeof delays.send !== 'undefined') { - const timeRequest = () => addTimeout(delays.send, timeoutHandler, 'send'); - /* istanbul ignore next: hard to test */ - if (socket.connecting) { - once(socket, 'connect', () => { - once(request, 'upload-complete', timeRequest()); - }); - } - else { - once(request, 'upload-complete', timeRequest()); - } - } - }); - if (typeof delays.response !== 'undefined') { - once(request, 'upload-complete', () => { - const cancelTimeout = addTimeout(delays.response, timeoutHandler, 'response'); - once(request, 'response', cancelTimeout); - }); - } - return cancelTimeouts; -}; + /** + * The currently focused non-ignored token. + */ + /** + * The (1-indexed) line containing the current token. + */ -/***/ }), + /** + * The character offset at which the current line begins. + */ + constructor(source) { + const startOfFileToken = new _ast.Token( + _tokenKind.TokenKind.SOF, + 0, + 0, + 0, + 0, + ); + this.source = source; + this.lastToken = startOfFileToken; + this.token = startOfFileToken; + this.line = 1; + this.lineStart = 0; + } -/***/ 81593: -/***/ ((__unused_webpack_module, exports) => { + get [Symbol.toStringTag]() { + return 'Lexer'; + } + /** + * Advances the token stream to the next non-ignored token. + */ -"use strict"; + advance() { + this.lastToken = this.token; + const token = (this.token = this.lookahead()); + return token; + } + /** + * Looks ahead and returns the next non-ignored token, but does not change + * the state of Lexer. + */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -// When attaching listeners, it's very easy to forget about them. -// Especially if you do error handling and set timeouts. -// So instead of checking if it's proper to throw an error on every timeout ever, -// use this simple tool which will remove all listeners you have attached. -exports["default"] = () => { - const handlers = []; - return { - once(origin, event, fn) { - origin.once(event, fn); - handlers.push({ origin, event, fn }); - }, - unhandleAll() { - for (const handler of handlers) { - const { origin, event, fn } = handler; - origin.removeListener(event, fn); - } - handlers.length = 0; - } - }; -}; + lookahead() { + let token = this.token; + if (token.kind !== _tokenKind.TokenKind.EOF) { + do { + if (token.next) { + token = token.next; + } else { + // Read the next token and form a link in the token linked-list. + const nextToken = readNextToken(this, token.end); // @ts-expect-error next is only mutable during parsing. -/***/ }), + token.next = nextToken; // @ts-expect-error prev is only mutable during parsing. -/***/ 8026: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + nextToken.prev = token; + token = nextToken; + } + } while (token.kind === _tokenKind.TokenKind.COMMENT); + } -"use strict"; + return token; + } +} +/** + * @internal + */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -const is_1 = __nccwpck_require__(68977); -exports["default"] = (url) => { - // Cast to URL - url = url; - const options = { - protocol: url.protocol, - hostname: is_1.default.string(url.hostname) && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname, - host: url.host, - hash: url.hash, - search: url.search, - pathname: url.pathname, - href: url.href, - path: `${url.pathname || ''}${url.search || ''}` - }; - if (is_1.default.string(url.port) && url.port.length > 0) { - options.port = Number(url.port); - } - if (url.username || url.password) { - options.auth = `${url.username || ''}:${url.password || ''}`; - } - return options; -}; +exports.Lexer = Lexer; +function isPunctuatorTokenKind(kind) { + return ( + kind === _tokenKind.TokenKind.BANG || + kind === _tokenKind.TokenKind.DOLLAR || + kind === _tokenKind.TokenKind.AMP || + kind === _tokenKind.TokenKind.PAREN_L || + kind === _tokenKind.TokenKind.PAREN_R || + kind === _tokenKind.TokenKind.SPREAD || + kind === _tokenKind.TokenKind.COLON || + kind === _tokenKind.TokenKind.EQUALS || + kind === _tokenKind.TokenKind.AT || + kind === _tokenKind.TokenKind.BRACKET_L || + kind === _tokenKind.TokenKind.BRACKET_R || + kind === _tokenKind.TokenKind.BRACE_L || + kind === _tokenKind.TokenKind.PIPE || + kind === _tokenKind.TokenKind.BRACE_R + ); +} +/** + * A Unicode scalar value is any Unicode code point except surrogate code + * points. In other words, the inclusive ranges of values 0x0000 to 0xD7FF and + * 0xE000 to 0x10FFFF. + * + * SourceCharacter :: + * - "Any Unicode scalar value" + */ -/***/ }), +function isUnicodeScalarValue(code) { + return ( + (code >= 0x0000 && code <= 0xd7ff) || (code >= 0xe000 && code <= 0x10ffff) + ); +} +/** + * The GraphQL specification defines source text as a sequence of unicode scalar + * values (which Unicode defines to exclude surrogate code points). However + * JavaScript defines strings as a sequence of UTF-16 code units which may + * include surrogates. A surrogate pair is a valid source character as it + * encodes a supplementary code point (above U+FFFF), but unpaired surrogate + * code points are not valid source characters. + */ -/***/ 7288: -/***/ ((__unused_webpack_module, exports) => { +function isSupplementaryCodePoint(body, location) { + return ( + isLeadingSurrogate(body.charCodeAt(location)) && + isTrailingSurrogate(body.charCodeAt(location + 1)) + ); +} -"use strict"; +function isLeadingSurrogate(code) { + return code >= 0xd800 && code <= 0xdbff; +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -class WeakableMap { - constructor() { - this.weakMap = new WeakMap(); - this.map = new Map(); - } - set(key, value) { - if (typeof key === 'object') { - this.weakMap.set(key, value); - } - else { - this.map.set(key, value); - } - } - get(key) { - if (typeof key === 'object') { - return this.weakMap.get(key); - } - return this.map.get(key); - } - has(key) { - if (typeof key === 'object') { - return this.weakMap.has(key); - } - return this.map.has(key); - } +function isTrailingSurrogate(code) { + return code >= 0xdc00 && code <= 0xdfff; } -exports["default"] = WeakableMap; +/** + * Prints the code point (or end of file reference) at a given location in a + * source for use in error messages. + * + * Printable ASCII is printed quoted, while other points are printed in Unicode + * code point form (ie. U+1234). + */ +function printCodePointAt(lexer, location) { + const code = lexer.source.body.codePointAt(location); -/***/ }), + if (code === undefined) { + return _tokenKind.TokenKind.EOF; + } else if (code >= 0x0020 && code <= 0x007e) { + // Printable ASCII + const char = String.fromCodePoint(code); + return char === '"' ? "'\"'" : `"${char}"`; + } // Unicode code point -/***/ 34337: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + return 'U+' + code.toString(16).toUpperCase().padStart(4, '0'); +} +/** + * Create a token with line and column location information. + */ -"use strict"; +function createToken(lexer, kind, start, end, value) { + const line = lexer.line; + const col = 1 + start - lexer.lineStart; + return new _ast.Token(kind, start, end, line, col, value); +} +/** + * Gets the next token from the source starting at the given position. + * + * This skips over whitespace until it finds the next lexable token, then lexes + * punctuators immediately or calls the appropriate helper function for more + * complicated tokens. + */ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (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 })); -exports.defaultHandler = void 0; -const is_1 = __nccwpck_require__(68977); -const as_promise_1 = __nccwpck_require__(36056); -const create_rejection_1 = __nccwpck_require__(26457); -const core_1 = __nccwpck_require__(60094); -const deep_freeze_1 = __nccwpck_require__(70285); -const errors = { - RequestError: as_promise_1.RequestError, - CacheError: as_promise_1.CacheError, - ReadError: as_promise_1.ReadError, - HTTPError: as_promise_1.HTTPError, - MaxRedirectsError: as_promise_1.MaxRedirectsError, - TimeoutError: as_promise_1.TimeoutError, - ParseError: as_promise_1.ParseError, - CancelError: as_promise_1.CancelError, - UnsupportedProtocolError: as_promise_1.UnsupportedProtocolError, - UploadError: as_promise_1.UploadError -}; -// The `delay` package weighs 10KB (!) -const delay = async (ms) => new Promise(resolve => { - setTimeout(resolve, ms); -}); -const { normalizeArguments } = core_1.default; -const mergeOptions = (...sources) => { - let mergedOptions; - for (const source of sources) { - mergedOptions = normalizeArguments(undefined, source, mergedOptions); - } - return mergedOptions; -}; -const getPromiseOrStream = (options) => options.isStream ? new core_1.default(undefined, options) : as_promise_1.default(options); -const isGotInstance = (value) => ('defaults' in value && 'options' in value.defaults); -const aliases = [ - 'get', - 'post', - 'put', - 'patch', - 'head', - 'delete' -]; -exports.defaultHandler = (options, next) => next(options); -const callInitHooks = (hooks, options) => { - if (hooks) { - for (const hook of hooks) { - hook(options); - } - } -}; -const create = (defaults) => { - // Proxy properties from next handlers - defaults._rawHandlers = defaults.handlers; - defaults.handlers = defaults.handlers.map(fn => ((options, next) => { - // This will be assigned by assigning result - let root; - const result = fn(options, newOptions => { - root = next(newOptions); - return root; - }); - if (result !== root && !options.isStream && root) { - const typedResult = result; - const { then: promiseThen, catch: promiseCatch, finally: promiseFianlly } = typedResult; - Object.setPrototypeOf(typedResult, Object.getPrototypeOf(root)); - Object.defineProperties(typedResult, Object.getOwnPropertyDescriptors(root)); - // These should point to the new promise - // eslint-disable-next-line promise/prefer-await-to-then - typedResult.then = promiseThen; - typedResult.catch = promiseCatch; - typedResult.finally = promiseFianlly; - } - return result; - })); - // Got interface - const got = ((url, options = {}, _defaults) => { - var _a, _b; - let iteration = 0; - const iterateHandlers = (newOptions) => { - return defaults.handlers[iteration++](newOptions, iteration === defaults.handlers.length ? getPromiseOrStream : iterateHandlers); - }; - // TODO: Remove this in Got 12. - if (is_1.default.plainObject(url)) { - const mergedOptions = { - ...url, - ...options - }; - core_1.setNonEnumerableProperties([url, options], mergedOptions); - options = mergedOptions; - url = undefined; - } - try { - // Call `init` hooks - let initHookError; - try { - callInitHooks(defaults.options.hooks.init, options); - callInitHooks((_a = options.hooks) === null || _a === void 0 ? void 0 : _a.init, options); - } - catch (error) { - initHookError = error; - } - // Normalize options & call handlers - const normalizedOptions = normalizeArguments(url, options, _defaults !== null && _defaults !== void 0 ? _defaults : defaults.options); - normalizedOptions[core_1.kIsNormalizedAlready] = true; - if (initHookError) { - throw new as_promise_1.RequestError(initHookError.message, initHookError, normalizedOptions); - } - return iterateHandlers(normalizedOptions); - } - catch (error) { - if (options.isStream) { - throw error; - } - else { - return create_rejection_1.default(error, defaults.options.hooks.beforeError, (_b = options.hooks) === null || _b === void 0 ? void 0 : _b.beforeError); - } - } - }); - got.extend = (...instancesOrOptions) => { - const optionsArray = [defaults.options]; - let handlers = [...defaults._rawHandlers]; - let isMutableDefaults; - for (const value of instancesOrOptions) { - if (isGotInstance(value)) { - optionsArray.push(value.defaults.options); - handlers.push(...value.defaults._rawHandlers); - isMutableDefaults = value.defaults.mutableDefaults; - } - else { - optionsArray.push(value); - if ('handlers' in value) { - handlers.push(...value.handlers); - } - isMutableDefaults = value.mutableDefaults; - } - } - handlers = handlers.filter(handler => handler !== exports.defaultHandler); - if (handlers.length === 0) { - handlers.push(exports.defaultHandler); - } - return create({ - options: mergeOptions(...optionsArray), - handlers, - mutableDefaults: Boolean(isMutableDefaults) - }); - }; - // Pagination - const paginateEach = (async function* (url, options) { - // TODO: Remove this `@ts-expect-error` when upgrading to TypeScript 4. - // Error: Argument of type 'Merge> | undefined' is not assignable to parameter of type 'Options | undefined'. - // @ts-expect-error - let normalizedOptions = normalizeArguments(url, options, defaults.options); - normalizedOptions.resolveBodyOnly = false; - const pagination = normalizedOptions.pagination; - if (!is_1.default.object(pagination)) { - throw new TypeError('`options.pagination` must be implemented'); - } - const all = []; - let { countLimit } = pagination; - let numberOfRequests = 0; - while (numberOfRequests < pagination.requestLimit) { - if (numberOfRequests !== 0) { - // eslint-disable-next-line no-await-in-loop - await delay(pagination.backoff); - } - // @ts-expect-error FIXME! - // TODO: Throw when result is not an instance of Response - // eslint-disable-next-line no-await-in-loop - const result = (await got(undefined, undefined, normalizedOptions)); - // eslint-disable-next-line no-await-in-loop - const parsed = await pagination.transform(result); - const current = []; - for (const item of parsed) { - if (pagination.filter(item, all, current)) { - if (!pagination.shouldContinue(item, all, current)) { - return; - } - yield item; - if (pagination.stackAllItems) { - all.push(item); - } - current.push(item); - if (--countLimit <= 0) { - return; - } - } - } - const optionsToMerge = pagination.paginate(result, all, current); - if (optionsToMerge === false) { - return; - } - if (optionsToMerge === result.request.options) { - normalizedOptions = result.request.options; - } - else if (optionsToMerge !== undefined) { - normalizedOptions = normalizeArguments(undefined, optionsToMerge, normalizedOptions); - } - numberOfRequests++; - } - }); - got.paginate = paginateEach; - got.paginate.all = (async (url, options) => { - const results = []; - for await (const item of paginateEach(url, options)) { - results.push(item); - } - return results; - }); - // For those who like very descriptive names - got.paginate.each = paginateEach; - // Stream API - got.stream = ((url, options) => got(url, { ...options, isStream: true })); - // Shortcuts - for (const method of aliases) { - got[method] = ((url, options) => got(url, { ...options, method })); - got.stream[method] = ((url, options) => { - return got(url, { ...options, method, isStream: true }); - }); - } - Object.assign(got, errors); - Object.defineProperty(got, 'defaults', { - value: defaults.mutableDefaults ? defaults : deep_freeze_1.default(defaults), - writable: defaults.mutableDefaults, - configurable: defaults.mutableDefaults, - enumerable: true - }); - got.mergeOptions = mergeOptions; - return got; -}; -exports["default"] = create; -__exportStar(__nccwpck_require__(72613), exports); +function readNextToken(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let position = start; + while (position < bodyLength) { + const code = body.charCodeAt(position); // SourceCharacter -/***/ }), + switch (code) { + // Ignored :: + // - UnicodeBOM + // - WhiteSpace + // - LineTerminator + // - Comment + // - Comma + // + // UnicodeBOM :: "Byte Order Mark (U+FEFF)" + // + // WhiteSpace :: + // - "Horizontal Tab (U+0009)" + // - "Space (U+0020)" + // + // Comma :: , + case 0xfeff: // -/***/ 93061: -/***/ (function(module, exports, __nccwpck_require__) { + case 0x0009: // \t -"use strict"; + case 0x0020: // -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (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 })); -const url_1 = __nccwpck_require__(57310); -const create_1 = __nccwpck_require__(34337); -const defaults = { - options: { - method: 'GET', - retry: { - limit: 2, - methods: [ - 'GET', - 'PUT', - 'HEAD', - 'DELETE', - 'OPTIONS', - 'TRACE' - ], - statusCodes: [ - 408, - 413, - 429, - 500, - 502, - 503, - 504, - 521, - 522, - 524 - ], - errorCodes: [ - 'ETIMEDOUT', - 'ECONNRESET', - 'EADDRINUSE', - 'ECONNREFUSED', - 'EPIPE', - 'ENOTFOUND', - 'ENETUNREACH', - 'EAI_AGAIN' - ], - maxRetryAfter: undefined, - calculateDelay: ({ computedValue }) => computedValue - }, - timeout: {}, - headers: { - 'user-agent': 'got (https://github.com/sindresorhus/got)' - }, - hooks: { - init: [], - beforeRequest: [], - beforeRedirect: [], - beforeRetry: [], - beforeError: [], - afterResponse: [] - }, - cache: undefined, - dnsCache: undefined, - decompress: true, - throwHttpErrors: true, - followRedirect: true, - isStream: false, - responseType: 'text', - resolveBodyOnly: false, - maxRedirects: 10, - prefixUrl: '', - methodRewriting: true, - ignoreInvalidCookies: false, - context: {}, - // TODO: Set this to `true` when Got 12 gets released - http2: false, - allowGetBody: false, - https: undefined, - pagination: { - transform: (response) => { - if (response.request.options.responseType === 'json') { - return response.body; - } - return JSON.parse(response.body); - }, - paginate: response => { - if (!Reflect.has(response.headers, 'link')) { - return false; - } - const items = response.headers.link.split(','); - let next; - for (const item of items) { - const parsed = item.split(';'); - if (parsed[1].includes('next')) { - next = parsed[0].trimStart().trim(); - next = next.slice(1, -1); - break; - } - } - if (next) { - const options = { - url: new url_1.URL(next) - }; - return options; - } - return false; - }, - filter: () => true, - shouldContinue: () => true, - countLimit: Infinity, - backoff: 0, - requestLimit: 10000, - stackAllItems: true - }, - parseJson: (text) => JSON.parse(text), - stringifyJson: (object) => JSON.stringify(object), - cacheOptions: {} - }, - handlers: [create_1.defaultHandler], - mutableDefaults: false -}; -const got = create_1.default(defaults); -exports["default"] = got; -// For CommonJS default export support -module.exports = got; -module.exports["default"] = got; -module.exports.__esModule = true; // Workaround for TS issue: https://github.com/sindresorhus/got/pull/1267 -__exportStar(__nccwpck_require__(34337), exports); -__exportStar(__nccwpck_require__(36056), exports); + case 0x002c: + // , + ++position; + continue; + // LineTerminator :: + // - "New Line (U+000A)" + // - "Carriage Return (U+000D)" [lookahead != "New Line (U+000A)"] + // - "Carriage Return (U+000D)" "New Line (U+000A)" + case 0x000a: + // \n + ++position; + ++lexer.line; + lexer.lineStart = position; + continue; -/***/ }), + case 0x000d: + // \r + if (body.charCodeAt(position + 1) === 0x000a) { + position += 2; + } else { + ++position; + } -/***/ 72613: -/***/ ((__unused_webpack_module, exports) => { + ++lexer.line; + lexer.lineStart = position; + continue; + // Comment -"use strict"; + case 0x0023: + // # + return readComment(lexer, position); + // Token :: + // - Punctuator + // - Name + // - IntValue + // - FloatValue + // - StringValue + // + // Punctuator :: one of ! $ & ( ) ... : = @ [ ] { | } -Object.defineProperty(exports, "__esModule", ({ value: true })); + case 0x0021: + // ! + return createToken( + lexer, + _tokenKind.TokenKind.BANG, + position, + position + 1, + ); + case 0x0024: + // $ + return createToken( + lexer, + _tokenKind.TokenKind.DOLLAR, + position, + position + 1, + ); -/***/ }), + case 0x0026: + // & + return createToken( + lexer, + _tokenKind.TokenKind.AMP, + position, + position + 1, + ); -/***/ 70285: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + case 0x0028: + // ( + return createToken( + lexer, + _tokenKind.TokenKind.PAREN_L, + position, + position + 1, + ); -"use strict"; + case 0x0029: + // ) + return createToken( + lexer, + _tokenKind.TokenKind.PAREN_R, + position, + position + 1, + ); -Object.defineProperty(exports, "__esModule", ({ value: true })); -const is_1 = __nccwpck_require__(68977); -function deepFreeze(object) { - for (const value of Object.values(object)) { - if (is_1.default.plainObject(value) || is_1.default.array(value)) { - deepFreeze(value); + case 0x002e: + // . + if ( + body.charCodeAt(position + 1) === 0x002e && + body.charCodeAt(position + 2) === 0x002e + ) { + return createToken( + lexer, + _tokenKind.TokenKind.SPREAD, + position, + position + 3, + ); } - } - return Object.freeze(object); -} -exports["default"] = deepFreeze; + break; -/***/ }), + case 0x003a: + // : + return createToken( + lexer, + _tokenKind.TokenKind.COLON, + position, + position + 1, + ); -/***/ 397: -/***/ ((__unused_webpack_module, exports) => { + case 0x003d: + // = + return createToken( + lexer, + _tokenKind.TokenKind.EQUALS, + position, + position + 1, + ); -"use strict"; + case 0x0040: + // @ + return createToken( + lexer, + _tokenKind.TokenKind.AT, + position, + position + 1, + ); -Object.defineProperty(exports, "__esModule", ({ value: true })); -const alreadyWarned = new Set(); -exports["default"] = (message) => { - if (alreadyWarned.has(message)) { - return; - } - alreadyWarned.add(message); - // @ts-expect-error Missing types. - process.emitWarning(`Got: ${message}`, { - type: 'DeprecationWarning' - }); -}; + case 0x005b: + // [ + return createToken( + lexer, + _tokenKind.TokenKind.BRACKET_L, + position, + position + 1, + ); + case 0x005d: + // ] + return createToken( + lexer, + _tokenKind.TokenKind.BRACKET_R, + position, + position + 1, + ); -/***/ }), + case 0x007b: + // { + return createToken( + lexer, + _tokenKind.TokenKind.BRACE_L, + position, + position + 1, + ); -/***/ 68977: -/***/ ((module, exports) => { + case 0x007c: + // | + return createToken( + lexer, + _tokenKind.TokenKind.PIPE, + position, + position + 1, + ); -"use strict"; + case 0x007d: + // } + return createToken( + lexer, + _tokenKind.TokenKind.BRACE_R, + position, + position + 1, + ); + // StringValue -/// -/// -/// -Object.defineProperty(exports, "__esModule", ({ value: true })); -const typedArrayTypeNames = [ - 'Int8Array', - 'Uint8Array', - 'Uint8ClampedArray', - 'Int16Array', - 'Uint16Array', - 'Int32Array', - 'Uint32Array', - 'Float32Array', - 'Float64Array', - 'BigInt64Array', - 'BigUint64Array' -]; -function isTypedArrayName(name) { - return typedArrayTypeNames.includes(name); -} -const objectTypeNames = [ - 'Function', - 'Generator', - 'AsyncGenerator', - 'GeneratorFunction', - 'AsyncGeneratorFunction', - 'AsyncFunction', - 'Observable', - 'Array', - 'Buffer', - 'Blob', - 'Object', - 'RegExp', - 'Date', - 'Error', - 'Map', - 'Set', - 'WeakMap', - 'WeakSet', - 'ArrayBuffer', - 'SharedArrayBuffer', - 'DataView', - 'Promise', - 'URL', - 'FormData', - 'URLSearchParams', - 'HTMLElement', - ...typedArrayTypeNames -]; -function isObjectTypeName(name) { - return objectTypeNames.includes(name); -} -const primitiveTypeNames = [ - 'null', - 'undefined', - 'string', - 'number', - 'bigint', - 'boolean', - 'symbol' -]; -function isPrimitiveTypeName(name) { - return primitiveTypeNames.includes(name); -} -// eslint-disable-next-line @typescript-eslint/ban-types -function isOfType(type) { - return (value) => typeof value === type; -} -const { toString } = Object.prototype; -const getObjectType = (value) => { - const objectTypeName = toString.call(value).slice(8, -1); - if (/HTML\w+Element/.test(objectTypeName) && is.domElement(value)) { - return 'HTMLElement'; - } - if (isObjectTypeName(objectTypeName)) { - return objectTypeName; - } - return undefined; -}; -const isObjectOfType = (type) => (value) => getObjectType(value) === type; -function is(value) { - if (value === null) { - return 'null'; - } - switch (typeof value) { - case 'undefined': - return 'undefined'; - case 'string': - return 'string'; - case 'number': - return 'number'; - case 'boolean': - return 'boolean'; - case 'function': - return 'Function'; - case 'bigint': - return 'bigint'; - case 'symbol': - return 'symbol'; - default: - } - if (is.observable(value)) { - return 'Observable'; - } - if (is.array(value)) { - return 'Array'; - } - if (is.buffer(value)) { - return 'Buffer'; - } - const tagType = getObjectType(value); - if (tagType) { - return tagType; - } - if (value instanceof String || value instanceof Boolean || value instanceof Number) { - throw new TypeError('Please don\'t use object wrappers for primitive types'); - } - return 'Object'; -} -is.undefined = isOfType('undefined'); -is.string = isOfType('string'); -const isNumberType = isOfType('number'); -is.number = (value) => isNumberType(value) && !is.nan(value); -is.bigint = isOfType('bigint'); -// eslint-disable-next-line @typescript-eslint/ban-types -is.function_ = isOfType('function'); -is.null_ = (value) => value === null; -is.class_ = (value) => is.function_(value) && value.toString().startsWith('class '); -is.boolean = (value) => value === true || value === false; -is.symbol = isOfType('symbol'); -is.numericString = (value) => is.string(value) && !is.emptyStringOrWhitespace(value) && !Number.isNaN(Number(value)); -is.array = (value, assertion) => { - if (!Array.isArray(value)) { - return false; - } - if (!is.function_(assertion)) { - return true; - } - return value.every(assertion); -}; -is.buffer = (value) => { var _a, _b, _c, _d; return (_d = (_c = (_b = (_a = value) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.isBuffer) === null || _c === void 0 ? void 0 : _c.call(_b, value)) !== null && _d !== void 0 ? _d : false; }; -is.blob = (value) => isObjectOfType('Blob')(value); -is.nullOrUndefined = (value) => is.null_(value) || is.undefined(value); -is.object = (value) => !is.null_(value) && (typeof value === 'object' || is.function_(value)); -is.iterable = (value) => { var _a; return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a[Symbol.iterator]); }; -is.asyncIterable = (value) => { var _a; return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a[Symbol.asyncIterator]); }; -is.generator = (value) => { var _a, _b; return is.iterable(value) && is.function_((_a = value) === null || _a === void 0 ? void 0 : _a.next) && is.function_((_b = value) === null || _b === void 0 ? void 0 : _b.throw); }; -is.asyncGenerator = (value) => is.asyncIterable(value) && is.function_(value.next) && is.function_(value.throw); -is.nativePromise = (value) => isObjectOfType('Promise')(value); -const hasPromiseAPI = (value) => { - var _a, _b; - return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a.then) && - is.function_((_b = value) === null || _b === void 0 ? void 0 : _b.catch); -}; -is.promise = (value) => is.nativePromise(value) || hasPromiseAPI(value); -is.generatorFunction = isObjectOfType('GeneratorFunction'); -is.asyncGeneratorFunction = (value) => getObjectType(value) === 'AsyncGeneratorFunction'; -is.asyncFunction = (value) => getObjectType(value) === 'AsyncFunction'; -// eslint-disable-next-line no-prototype-builtins, @typescript-eslint/ban-types -is.boundFunction = (value) => is.function_(value) && !value.hasOwnProperty('prototype'); -is.regExp = isObjectOfType('RegExp'); -is.date = isObjectOfType('Date'); -is.error = isObjectOfType('Error'); -is.map = (value) => isObjectOfType('Map')(value); -is.set = (value) => isObjectOfType('Set')(value); -is.weakMap = (value) => isObjectOfType('WeakMap')(value); -is.weakSet = (value) => isObjectOfType('WeakSet')(value); -is.int8Array = isObjectOfType('Int8Array'); -is.uint8Array = isObjectOfType('Uint8Array'); -is.uint8ClampedArray = isObjectOfType('Uint8ClampedArray'); -is.int16Array = isObjectOfType('Int16Array'); -is.uint16Array = isObjectOfType('Uint16Array'); -is.int32Array = isObjectOfType('Int32Array'); -is.uint32Array = isObjectOfType('Uint32Array'); -is.float32Array = isObjectOfType('Float32Array'); -is.float64Array = isObjectOfType('Float64Array'); -is.bigInt64Array = isObjectOfType('BigInt64Array'); -is.bigUint64Array = isObjectOfType('BigUint64Array'); -is.arrayBuffer = isObjectOfType('ArrayBuffer'); -is.sharedArrayBuffer = isObjectOfType('SharedArrayBuffer'); -is.dataView = isObjectOfType('DataView'); -is.enumCase = (value, targetEnum) => Object.values(targetEnum).includes(value); -is.directInstanceOf = (instance, class_) => Object.getPrototypeOf(instance) === class_.prototype; -is.urlInstance = (value) => isObjectOfType('URL')(value); -is.urlString = (value) => { - if (!is.string(value)) { - return false; - } - try { - new URL(value); // eslint-disable-line no-new - return true; - } - catch (_a) { - return false; - } -}; -// Example: `is.truthy = (value: unknown): value is (not false | not 0 | not '' | not undefined | not null) => Boolean(value);` -is.truthy = (value) => Boolean(value); -// Example: `is.falsy = (value: unknown): value is (not true | 0 | '' | undefined | null) => Boolean(value);` -is.falsy = (value) => !value; -is.nan = (value) => Number.isNaN(value); -is.primitive = (value) => is.null_(value) || isPrimitiveTypeName(typeof value); -is.integer = (value) => Number.isInteger(value); -is.safeInteger = (value) => Number.isSafeInteger(value); -is.plainObject = (value) => { - // From: https://github.com/sindresorhus/is-plain-obj/blob/main/index.js - if (toString.call(value) !== '[object Object]') { - return false; - } - const prototype = Object.getPrototypeOf(value); - return prototype === null || prototype === Object.getPrototypeOf({}); -}; -is.typedArray = (value) => isTypedArrayName(getObjectType(value)); -const isValidLength = (value) => is.safeInteger(value) && value >= 0; -is.arrayLike = (value) => !is.nullOrUndefined(value) && !is.function_(value) && isValidLength(value.length); -is.inRange = (value, range) => { - if (is.number(range)) { - return value >= Math.min(0, range) && value <= Math.max(range, 0); - } - if (is.array(range) && range.length === 2) { - return value >= Math.min(...range) && value <= Math.max(...range); - } - throw new TypeError(`Invalid range: ${JSON.stringify(range)}`); -}; -const NODE_TYPE_ELEMENT = 1; -const DOM_PROPERTIES_TO_CHECK = [ - 'innerHTML', - 'ownerDocument', - 'style', - 'attributes', - 'nodeValue' -]; -is.domElement = (value) => { - return is.object(value) && - value.nodeType === NODE_TYPE_ELEMENT && - is.string(value.nodeName) && - !is.plainObject(value) && - DOM_PROPERTIES_TO_CHECK.every(property => property in value); -}; -is.observable = (value) => { - var _a, _b, _c, _d; - if (!value) { - return false; - } - // eslint-disable-next-line no-use-extend-native/no-use-extend-native - if (value === ((_b = (_a = value)[Symbol.observable]) === null || _b === void 0 ? void 0 : _b.call(_a))) { - return true; - } - if (value === ((_d = (_c = value)['@@observable']) === null || _d === void 0 ? void 0 : _d.call(_c))) { - return true; - } - return false; -}; -is.nodeStream = (value) => is.object(value) && is.function_(value.pipe) && !is.observable(value); -is.infinite = (value) => value === Infinity || value === -Infinity; -const isAbsoluteMod2 = (remainder) => (value) => is.integer(value) && Math.abs(value % 2) === remainder; -is.evenInteger = isAbsoluteMod2(0); -is.oddInteger = isAbsoluteMod2(1); -is.emptyArray = (value) => is.array(value) && value.length === 0; -is.nonEmptyArray = (value) => is.array(value) && value.length > 0; -is.emptyString = (value) => is.string(value) && value.length === 0; -const isWhiteSpaceString = (value) => is.string(value) && !/\S/.test(value); -is.emptyStringOrWhitespace = (value) => is.emptyString(value) || isWhiteSpaceString(value); -// TODO: Use `not ''` when the `not` operator is available. -is.nonEmptyString = (value) => is.string(value) && value.length > 0; -// TODO: Use `not ''` when the `not` operator is available. -is.nonEmptyStringAndNotWhitespace = (value) => is.string(value) && !is.emptyStringOrWhitespace(value); -is.emptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length === 0; -// TODO: Use `not` operator here to remove `Map` and `Set` from type guard: -// - https://github.com/Microsoft/TypeScript/pull/29317 -is.nonEmptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length > 0; -is.emptySet = (value) => is.set(value) && value.size === 0; -is.nonEmptySet = (value) => is.set(value) && value.size > 0; -is.emptyMap = (value) => is.map(value) && value.size === 0; -is.nonEmptyMap = (value) => is.map(value) && value.size > 0; -// `PropertyKey` is any value that can be used as an object key (string, number, or symbol) -is.propertyKey = (value) => is.any([is.string, is.number, is.symbol], value); -is.formData = (value) => isObjectOfType('FormData')(value); -is.urlSearchParams = (value) => isObjectOfType('URLSearchParams')(value); -const predicateOnArray = (method, predicate, values) => { - if (!is.function_(predicate)) { - throw new TypeError(`Invalid predicate: ${JSON.stringify(predicate)}`); - } - if (values.length === 0) { - throw new TypeError('Invalid number of values'); - } - return method.call(values, predicate); -}; -is.any = (predicate, ...values) => { - const predicates = is.array(predicate) ? predicate : [predicate]; - return predicates.some(singlePredicate => predicateOnArray(Array.prototype.some, singlePredicate, values)); -}; -is.all = (predicate, ...values) => predicateOnArray(Array.prototype.every, predicate, values); -const assertType = (condition, description, value, options = {}) => { - if (!condition) { - const { multipleValues } = options; - const valuesMessage = multipleValues ? - `received values of types ${[ - ...new Set(value.map(singleValue => `\`${is(singleValue)}\``)) - ].join(', ')}` : - `received value of type \`${is(value)}\``; - throw new TypeError(`Expected value which is \`${description}\`, ${valuesMessage}.`); - } -}; -exports.assert = { - // Unknowns. - undefined: (value) => assertType(is.undefined(value), 'undefined', value), - string: (value) => assertType(is.string(value), 'string', value), - number: (value) => assertType(is.number(value), 'number', value), - bigint: (value) => assertType(is.bigint(value), 'bigint', value), - // eslint-disable-next-line @typescript-eslint/ban-types - function_: (value) => assertType(is.function_(value), 'Function', value), - null_: (value) => assertType(is.null_(value), 'null', value), - class_: (value) => assertType(is.class_(value), "Class" /* class_ */, value), - boolean: (value) => assertType(is.boolean(value), 'boolean', value), - symbol: (value) => assertType(is.symbol(value), 'symbol', value), - numericString: (value) => assertType(is.numericString(value), "string with a number" /* numericString */, value), - array: (value, assertion) => { - const assert = assertType; - assert(is.array(value), 'Array', value); - if (assertion) { - value.forEach(assertion); + case 0x0022: + // " + if ( + body.charCodeAt(position + 1) === 0x0022 && + body.charCodeAt(position + 2) === 0x0022 + ) { + return readBlockString(lexer, position); } - }, - buffer: (value) => assertType(is.buffer(value), 'Buffer', value), - blob: (value) => assertType(is.blob(value), 'Blob', value), - nullOrUndefined: (value) => assertType(is.nullOrUndefined(value), "null or undefined" /* nullOrUndefined */, value), - object: (value) => assertType(is.object(value), 'Object', value), - iterable: (value) => assertType(is.iterable(value), "Iterable" /* iterable */, value), - asyncIterable: (value) => assertType(is.asyncIterable(value), "AsyncIterable" /* asyncIterable */, value), - generator: (value) => assertType(is.generator(value), 'Generator', value), - asyncGenerator: (value) => assertType(is.asyncGenerator(value), 'AsyncGenerator', value), - nativePromise: (value) => assertType(is.nativePromise(value), "native Promise" /* nativePromise */, value), - promise: (value) => assertType(is.promise(value), 'Promise', value), - generatorFunction: (value) => assertType(is.generatorFunction(value), 'GeneratorFunction', value), - asyncGeneratorFunction: (value) => assertType(is.asyncGeneratorFunction(value), 'AsyncGeneratorFunction', value), - // eslint-disable-next-line @typescript-eslint/ban-types - asyncFunction: (value) => assertType(is.asyncFunction(value), 'AsyncFunction', value), - // eslint-disable-next-line @typescript-eslint/ban-types - boundFunction: (value) => assertType(is.boundFunction(value), 'Function', value), - regExp: (value) => assertType(is.regExp(value), 'RegExp', value), - date: (value) => assertType(is.date(value), 'Date', value), - error: (value) => assertType(is.error(value), 'Error', value), - map: (value) => assertType(is.map(value), 'Map', value), - set: (value) => assertType(is.set(value), 'Set', value), - weakMap: (value) => assertType(is.weakMap(value), 'WeakMap', value), - weakSet: (value) => assertType(is.weakSet(value), 'WeakSet', value), - int8Array: (value) => assertType(is.int8Array(value), 'Int8Array', value), - uint8Array: (value) => assertType(is.uint8Array(value), 'Uint8Array', value), - uint8ClampedArray: (value) => assertType(is.uint8ClampedArray(value), 'Uint8ClampedArray', value), - int16Array: (value) => assertType(is.int16Array(value), 'Int16Array', value), - uint16Array: (value) => assertType(is.uint16Array(value), 'Uint16Array', value), - int32Array: (value) => assertType(is.int32Array(value), 'Int32Array', value), - uint32Array: (value) => assertType(is.uint32Array(value), 'Uint32Array', value), - float32Array: (value) => assertType(is.float32Array(value), 'Float32Array', value), - float64Array: (value) => assertType(is.float64Array(value), 'Float64Array', value), - bigInt64Array: (value) => assertType(is.bigInt64Array(value), 'BigInt64Array', value), - bigUint64Array: (value) => assertType(is.bigUint64Array(value), 'BigUint64Array', value), - arrayBuffer: (value) => assertType(is.arrayBuffer(value), 'ArrayBuffer', value), - sharedArrayBuffer: (value) => assertType(is.sharedArrayBuffer(value), 'SharedArrayBuffer', value), - dataView: (value) => assertType(is.dataView(value), 'DataView', value), - enumCase: (value, targetEnum) => assertType(is.enumCase(value, targetEnum), 'EnumCase', value), - urlInstance: (value) => assertType(is.urlInstance(value), 'URL', value), - urlString: (value) => assertType(is.urlString(value), "string with a URL" /* urlString */, value), - truthy: (value) => assertType(is.truthy(value), "truthy" /* truthy */, value), - falsy: (value) => assertType(is.falsy(value), "falsy" /* falsy */, value), - nan: (value) => assertType(is.nan(value), "NaN" /* nan */, value), - primitive: (value) => assertType(is.primitive(value), "primitive" /* primitive */, value), - integer: (value) => assertType(is.integer(value), "integer" /* integer */, value), - safeInteger: (value) => assertType(is.safeInteger(value), "integer" /* safeInteger */, value), - plainObject: (value) => assertType(is.plainObject(value), "plain object" /* plainObject */, value), - typedArray: (value) => assertType(is.typedArray(value), "TypedArray" /* typedArray */, value), - arrayLike: (value) => assertType(is.arrayLike(value), "array-like" /* arrayLike */, value), - domElement: (value) => assertType(is.domElement(value), "HTMLElement" /* domElement */, value), - observable: (value) => assertType(is.observable(value), 'Observable', value), - nodeStream: (value) => assertType(is.nodeStream(value), "Node.js Stream" /* nodeStream */, value), - infinite: (value) => assertType(is.infinite(value), "infinite number" /* infinite */, value), - emptyArray: (value) => assertType(is.emptyArray(value), "empty array" /* emptyArray */, value), - nonEmptyArray: (value) => assertType(is.nonEmptyArray(value), "non-empty array" /* nonEmptyArray */, value), - emptyString: (value) => assertType(is.emptyString(value), "empty string" /* emptyString */, value), - emptyStringOrWhitespace: (value) => assertType(is.emptyStringOrWhitespace(value), "empty string or whitespace" /* emptyStringOrWhitespace */, value), - nonEmptyString: (value) => assertType(is.nonEmptyString(value), "non-empty string" /* nonEmptyString */, value), - nonEmptyStringAndNotWhitespace: (value) => assertType(is.nonEmptyStringAndNotWhitespace(value), "non-empty string and not whitespace" /* nonEmptyStringAndNotWhitespace */, value), - emptyObject: (value) => assertType(is.emptyObject(value), "empty object" /* emptyObject */, value), - nonEmptyObject: (value) => assertType(is.nonEmptyObject(value), "non-empty object" /* nonEmptyObject */, value), - emptySet: (value) => assertType(is.emptySet(value), "empty set" /* emptySet */, value), - nonEmptySet: (value) => assertType(is.nonEmptySet(value), "non-empty set" /* nonEmptySet */, value), - emptyMap: (value) => assertType(is.emptyMap(value), "empty map" /* emptyMap */, value), - nonEmptyMap: (value) => assertType(is.nonEmptyMap(value), "non-empty map" /* nonEmptyMap */, value), - propertyKey: (value) => assertType(is.propertyKey(value), 'PropertyKey', value), - formData: (value) => assertType(is.formData(value), 'FormData', value), - urlSearchParams: (value) => assertType(is.urlSearchParams(value), 'URLSearchParams', value), - // Numbers. - evenInteger: (value) => assertType(is.evenInteger(value), "even integer" /* evenInteger */, value), - oddInteger: (value) => assertType(is.oddInteger(value), "odd integer" /* oddInteger */, value), - // Two arguments. - directInstanceOf: (instance, class_) => assertType(is.directInstanceOf(instance, class_), "T" /* directInstanceOf */, instance), - inRange: (value, range) => assertType(is.inRange(value, range), "in range" /* inRange */, value), - // Variadic functions. - any: (predicate, ...values) => { - return assertType(is.any(predicate, ...values), "predicate returns truthy for any value" /* any */, values, { multipleValues: true }); - }, - all: (predicate, ...values) => assertType(is.all(predicate, ...values), "predicate returns truthy for all values" /* all */, values, { multipleValues: true }) -}; -// Some few keywords are reserved, but we'll populate them for Node.js users -// See https://github.com/Microsoft/TypeScript/issues/2536 -Object.defineProperties(is, { - class: { - value: is.class_ - }, - function: { - value: is.function_ - }, - null: { - value: is.null_ - } -}); -Object.defineProperties(exports.assert, { - class: { - value: exports.assert.class_ - }, - function: { - value: exports.assert.function_ - }, - null: { - value: exports.assert.null_ + + return readString(lexer, position); + } // IntValue | FloatValue (Digit | -) + + if ((0, _characterClasses.isDigit)(code) || code === 0x002d) { + return readNumber(lexer, position, code); + } // Name + + if ((0, _characterClasses.isNameStart)(code)) { + return readName(lexer, position); } -}); -exports["default"] = is; -// For CommonJS default export support -module.exports = is; -module.exports["default"] = is; -module.exports.assert = exports.assert; + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + code === 0x0027 + ? 'Unexpected single quote character (\'), did you mean to use a double quote (")?' + : isUnicodeScalarValue(code) || isSupplementaryCodePoint(body, position) + ? `Unexpected character: ${printCodePointAt(lexer, position)}.` + : `Invalid character: ${printCodePointAt(lexer, position)}.`, + ); + } -/***/ }), + return createToken(lexer, _tokenKind.TokenKind.EOF, bodyLength, bodyLength); +} +/** + * Reads a comment token from the source file. + * + * ``` + * Comment :: # CommentChar* [lookahead != CommentChar] + * + * CommentChar :: SourceCharacter but not LineTerminator + * ``` + */ -/***/ 76234: -/***/ ((module, exports, __nccwpck_require__) => { +function readComment(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let position = start + 1; -"use strict"; + while (position < bodyLength) { + const code = body.charCodeAt(position); // LineTerminator (\n | \r) -Object.defineProperty(exports, "__esModule", ({ value: true })); -const defer_to_connect_1 = __nccwpck_require__(98183); -const util_1 = __nccwpck_require__(73837); -const nodejsMajorVersion = Number(process.versions.node.split('.')[0]); -const timer = (request) => { - if (request.timings) { - return request.timings; - } - const timings = { - start: Date.now(), - socket: undefined, - lookup: undefined, - connect: undefined, - secureConnect: undefined, - upload: undefined, - response: undefined, - end: undefined, - error: undefined, - abort: undefined, - phases: { - wait: undefined, - dns: undefined, - tcp: undefined, - tls: undefined, - request: undefined, - firstByte: undefined, - download: undefined, - total: undefined - } - }; - request.timings = timings; - const handleError = (origin) => { - const emit = origin.emit.bind(origin); - origin.emit = (event, ...args) => { - // Catches the `error` event - if (event === 'error') { - timings.error = Date.now(); - timings.phases.total = timings.error - timings.start; - origin.emit = emit; - } - // Saves the original behavior - return emit(event, ...args); - }; - }; - handleError(request); - const onAbort = () => { - timings.abort = Date.now(); - // Let the `end` response event be responsible for setting the total phase, - // unless the Node.js major version is >= 13. - if (!timings.response || nodejsMajorVersion >= 13) { - timings.phases.total = Date.now() - timings.start; - } - }; - request.prependOnceListener('abort', onAbort); - const onSocket = (socket) => { - timings.socket = Date.now(); - timings.phases.wait = timings.socket - timings.start; - if (util_1.types.isProxy(socket)) { - return; - } - const lookupListener = () => { - timings.lookup = Date.now(); - timings.phases.dns = timings.lookup - timings.socket; - }; - socket.prependOnceListener('lookup', lookupListener); - defer_to_connect_1.default(socket, { - connect: () => { - timings.connect = Date.now(); - if (timings.lookup === undefined) { - socket.removeListener('lookup', lookupListener); - timings.lookup = timings.connect; - timings.phases.dns = timings.lookup - timings.socket; - } - timings.phases.tcp = timings.connect - timings.lookup; - // This callback is called before flushing any data, - // so we don't need to set `timings.phases.request` here. - }, - secureConnect: () => { - timings.secureConnect = Date.now(); - timings.phases.tls = timings.secureConnect - timings.connect; - } - }); - }; - if (request.socket) { - onSocket(request.socket); - } - else { - request.prependOnceListener('socket', onSocket); - } - const onUpload = () => { - var _a; - timings.upload = Date.now(); - timings.phases.request = timings.upload - ((_a = timings.secureConnect) !== null && _a !== void 0 ? _a : timings.connect); - }; - const writableFinished = () => { - if (typeof request.writableFinished === 'boolean') { - return request.writableFinished; - } - // Node.js doesn't have `request.writableFinished` property - return request.finished && request.outputSize === 0 && (!request.socket || request.socket.writableLength === 0); - }; - if (writableFinished()) { - onUpload(); - } - else { - request.prependOnceListener('finish', onUpload); + if (code === 0x000a || code === 0x000d) { + break; + } // SourceCharacter + + if (isUnicodeScalarValue(code)) { + ++position; + } else if (isSupplementaryCodePoint(body, position)) { + position += 2; + } else { + break; } - request.prependOnceListener('response', (response) => { - timings.response = Date.now(); - timings.phases.firstByte = timings.response - timings.upload; - response.timings = timings; - handleError(response); - response.prependOnceListener('end', () => { - timings.end = Date.now(); - timings.phases.download = timings.end - timings.response; - timings.phases.total = timings.end - timings.start; - }); - response.prependOnceListener('aborted', onAbort); - }); - return timings; -}; -exports["default"] = timer; -// For CommonJS default export support -module.exports = timer; -module.exports["default"] = timer; + } + return createToken( + lexer, + _tokenKind.TokenKind.COMMENT, + start, + position, + body.slice(start + 1, position), + ); +} +/** + * Reads a number token from the source file, either a FloatValue or an IntValue + * depending on whether a FractionalPart or ExponentPart is encountered. + * + * ``` + * IntValue :: IntegerPart [lookahead != {Digit, `.`, NameStart}] + * + * IntegerPart :: + * - NegativeSign? 0 + * - NegativeSign? NonZeroDigit Digit* + * + * NegativeSign :: - + * + * NonZeroDigit :: Digit but not `0` + * + * FloatValue :: + * - IntegerPart FractionalPart ExponentPart [lookahead != {Digit, `.`, NameStart}] + * - IntegerPart FractionalPart [lookahead != {Digit, `.`, NameStart}] + * - IntegerPart ExponentPart [lookahead != {Digit, `.`, NameStart}] + * + * FractionalPart :: . Digit+ + * + * ExponentPart :: ExponentIndicator Sign? Digit+ + * + * ExponentIndicator :: one of `e` `E` + * + * Sign :: one of + - + * ``` + */ -/***/ }), +function readNumber(lexer, start, firstCode) { + const body = lexer.source.body; + let position = start; + let code = firstCode; + let isFloat = false; // NegativeSign (-) -/***/ 69016: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (code === 0x002d) { + code = body.charCodeAt(++position); + } // Zero (0) -"use strict"; + if (code === 0x0030) { + code = body.charCodeAt(++position); + if ((0, _characterClasses.isDigit)(code)) { + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + `Invalid number, unexpected digit after 0: ${printCodePointAt( + lexer, + position, + )}.`, + ); + } + } else { + position = readDigits(lexer, position, code); + code = body.charCodeAt(position); + } // Full stop (.) -const EventEmitter = __nccwpck_require__(82361); -const urlLib = __nccwpck_require__(57310); -const normalizeUrl = __nccwpck_require__(88580); -const getStream = __nccwpck_require__(86741); -const CachePolicy = __nccwpck_require__(61002); -const Response = __nccwpck_require__(9004); -const lowercaseKeys = __nccwpck_require__(9662); -const cloneResponse = __nccwpck_require__(81312); -const Keyv = __nccwpck_require__(94432); + if (code === 0x002e) { + isFloat = true; + code = body.charCodeAt(++position); + position = readDigits(lexer, position, code); + code = body.charCodeAt(position); + } // E e -class CacheableRequest { - constructor(request, cacheAdapter) { - if (typeof request !== 'function') { - throw new TypeError('Parameter `request` must be a function'); - } + if (code === 0x0045 || code === 0x0065) { + isFloat = true; + code = body.charCodeAt(++position); // + - - this.cache = new Keyv({ - uri: typeof cacheAdapter === 'string' && cacheAdapter, - store: typeof cacheAdapter !== 'string' && cacheAdapter, - namespace: 'cacheable-request' - }); + if (code === 0x002b || code === 0x002d) { + code = body.charCodeAt(++position); + } - return this.createCacheableRequest(request); - } + position = readDigits(lexer, position, code); + code = body.charCodeAt(position); + } // Numbers cannot be followed by . or NameStart - createCacheableRequest(request) { - return (opts, cb) => { - let url; - if (typeof opts === 'string') { - url = normalizeUrlObject(urlLib.parse(opts)); - opts = {}; - } else if (opts instanceof urlLib.URL) { - url = normalizeUrlObject(urlLib.parse(opts.toString())); - opts = {}; - } else { - const [pathname, ...searchParts] = (opts.path || '').split('?'); - const search = searchParts.length > 0 ? - `?${searchParts.join('?')}` : - ''; - url = normalizeUrlObject({ ...opts, pathname, search }); - } + if (code === 0x002e || (0, _characterClasses.isNameStart)(code)) { + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + `Invalid number, expected digit but got: ${printCodePointAt( + lexer, + position, + )}.`, + ); + } - opts = { - headers: {}, - method: 'GET', - cache: true, - strictTtl: false, - automaticFailover: false, - ...opts, - ...urlObjectToRequestOptions(url) - }; - opts.headers = lowercaseKeys(opts.headers); + return createToken( + lexer, + isFloat ? _tokenKind.TokenKind.FLOAT : _tokenKind.TokenKind.INT, + start, + position, + body.slice(start, position), + ); +} +/** + * Returns the new position in the source after reading one or more digits. + */ - const ee = new EventEmitter(); - const normalizedUrlString = normalizeUrl( - urlLib.format(url), - { - stripWWW: false, - removeTrailingSlash: false, - stripAuthentication: false - } - ); - const key = `${opts.method}:${normalizedUrlString}`; - let revalidate = false; - let madeRequest = false; +function readDigits(lexer, start, firstCode) { + if (!(0, _characterClasses.isDigit)(firstCode)) { + throw (0, _syntaxError.syntaxError)( + lexer.source, + start, + `Invalid number, expected digit but got: ${printCodePointAt( + lexer, + start, + )}.`, + ); + } - const makeRequest = opts => { - madeRequest = true; - let requestErrored = false; - let requestErrorCallback; + const body = lexer.source.body; + let position = start + 1; // +1 to skip first firstCode - const requestErrorPromise = new Promise(resolve => { - requestErrorCallback = () => { - if (!requestErrored) { - requestErrored = true; - resolve(); - } - }; - }); + while ((0, _characterClasses.isDigit)(body.charCodeAt(position))) { + ++position; + } - const handler = response => { - if (revalidate && !opts.forceRefresh) { - response.status = response.statusCode; - const revalidatedPolicy = CachePolicy.fromObject(revalidate.cachePolicy).revalidatedPolicy(opts, response); - if (!revalidatedPolicy.modified) { - const headers = revalidatedPolicy.policy.responseHeaders(); - response = new Response(revalidate.statusCode, headers, revalidate.body, revalidate.url); - response.cachePolicy = revalidatedPolicy.policy; - response.fromCache = true; - } - } + return position; +} +/** + * Reads a single-quote string token from the source file. + * + * ``` + * StringValue :: + * - `""` [lookahead != `"`] + * - `"` StringCharacter+ `"` + * + * StringCharacter :: + * - SourceCharacter but not `"` or `\` or LineTerminator + * - `\u` EscapedUnicode + * - `\` EscapedCharacter + * + * EscapedUnicode :: + * - `{` HexDigit+ `}` + * - HexDigit HexDigit HexDigit HexDigit + * + * EscapedCharacter :: one of `"` `\` `/` `b` `f` `n` `r` `t` + * ``` + */ - if (!response.fromCache) { - response.cachePolicy = new CachePolicy(opts, response, opts); - response.fromCache = false; - } +function readString(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let position = start + 1; + let chunkStart = position; + let value = ''; - let clonedResponse; - if (opts.cache && response.cachePolicy.storable()) { - clonedResponse = cloneResponse(response); + while (position < bodyLength) { + const code = body.charCodeAt(position); // Closing Quote (") - (async () => { - try { - const bodyPromise = getStream.buffer(response); + if (code === 0x0022) { + value += body.slice(chunkStart, position); + return createToken( + lexer, + _tokenKind.TokenKind.STRING, + start, + position + 1, + value, + ); + } // Escape Sequence (\) - await Promise.race([ - requestErrorPromise, - new Promise(resolve => response.once('end', resolve)) - ]); + if (code === 0x005c) { + value += body.slice(chunkStart, position); + const escape = + body.charCodeAt(position + 1) === 0x0075 // u + ? body.charCodeAt(position + 2) === 0x007b // { + ? readEscapedUnicodeVariableWidth(lexer, position) + : readEscapedUnicodeFixedWidth(lexer, position) + : readEscapedCharacter(lexer, position); + value += escape.value; + position += escape.size; + chunkStart = position; + continue; + } // LineTerminator (\n | \r) - if (requestErrored) { - return; - } + if (code === 0x000a || code === 0x000d) { + break; + } // SourceCharacter - const body = await bodyPromise; + if (isUnicodeScalarValue(code)) { + ++position; + } else if (isSupplementaryCodePoint(body, position)) { + position += 2; + } else { + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + `Invalid character within String: ${printCodePointAt( + lexer, + position, + )}.`, + ); + } + } - const value = { - cachePolicy: response.cachePolicy.toObject(), - url: response.url, - statusCode: response.fromCache ? revalidate.statusCode : response.statusCode, - body - }; + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + 'Unterminated string.', + ); +} // The string value and lexed size of an escape sequence. - let ttl = opts.strictTtl ? response.cachePolicy.timeToLive() : undefined; - if (opts.maxTtl) { - ttl = ttl ? Math.min(ttl, opts.maxTtl) : opts.maxTtl; - } +function readEscapedUnicodeVariableWidth(lexer, position) { + const body = lexer.source.body; + let point = 0; + let size = 3; // Cannot be larger than 12 chars (\u{00000000}). - await this.cache.set(key, value, ttl); - } catch (error) { - ee.emit('error', new CacheableRequest.CacheError(error)); - } - })(); - } else if (opts.cache && revalidate) { - (async () => { - try { - await this.cache.delete(key); - } catch (error) { - ee.emit('error', new CacheableRequest.CacheError(error)); - } - })(); - } + while (size < 12) { + const code = body.charCodeAt(position + size++); // Closing Brace (}) - ee.emit('response', clonedResponse || response); - if (typeof cb === 'function') { - cb(clonedResponse || response); - } - }; + if (code === 0x007d) { + // Must be at least 5 chars (\u{0}) and encode a Unicode scalar value. + if (size < 5 || !isUnicodeScalarValue(point)) { + break; + } - try { - const req = request(opts, handler); - req.once('error', requestErrorCallback); - req.once('abort', requestErrorCallback); - ee.emit('request', req); - } catch (error) { - ee.emit('error', new CacheableRequest.RequestError(error)); - } - }; + return { + value: String.fromCodePoint(point), + size, + }; + } // Append this hex digit to the code point. - (async () => { - const get = async opts => { - await Promise.resolve(); + point = (point << 4) | readHexDigit(code); - const cacheEntry = opts.cache ? await this.cache.get(key) : undefined; - if (typeof cacheEntry === 'undefined') { - return makeRequest(opts); - } + if (point < 0) { + break; + } + } - const policy = CachePolicy.fromObject(cacheEntry.cachePolicy); - if (policy.satisfiesWithoutRevalidation(opts) && !opts.forceRefresh) { - const headers = policy.responseHeaders(); - const response = new Response(cacheEntry.statusCode, headers, cacheEntry.body, cacheEntry.url); - response.cachePolicy = policy; - response.fromCache = true; + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + `Invalid Unicode escape sequence: "${body.slice( + position, + position + size, + )}".`, + ); +} - ee.emit('response', response); - if (typeof cb === 'function') { - cb(response); - } - } else { - revalidate = cacheEntry; - opts.headers = policy.revalidationHeaders(opts); - makeRequest(opts); - } - }; +function readEscapedUnicodeFixedWidth(lexer, position) { + const body = lexer.source.body; + const code = read16BitHexCode(body, position + 2); - const errorHandler = error => ee.emit('error', new CacheableRequest.CacheError(error)); - this.cache.once('error', errorHandler); - ee.on('response', () => this.cache.removeListener('error', errorHandler)); + if (isUnicodeScalarValue(code)) { + return { + value: String.fromCodePoint(code), + size: 6, + }; + } // GraphQL allows JSON-style surrogate pair escape sequences, but only when + // a valid pair is formed. - try { - await get(opts); - } catch (error) { - if (opts.automaticFailover && !madeRequest) { - makeRequest(opts); - } + if (isLeadingSurrogate(code)) { + // \u + if ( + body.charCodeAt(position + 6) === 0x005c && + body.charCodeAt(position + 7) === 0x0075 + ) { + const trailingCode = read16BitHexCode(body, position + 8); - ee.emit('error', new CacheableRequest.CacheError(error)); - } - })(); + if (isTrailingSurrogate(trailingCode)) { + // JavaScript defines strings as a sequence of UTF-16 code units and + // encodes Unicode code points above U+FFFF using a surrogate pair of + // code units. Since this is a surrogate pair escape sequence, just + // include both codes into the JavaScript string value. Had JavaScript + // not been internally based on UTF-16, then this surrogate pair would + // be decoded to retrieve the supplementary code point. + return { + value: String.fromCodePoint(code, trailingCode), + size: 12, + }; + } + } + } - return ee; - }; - } + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + `Invalid Unicode escape sequence: "${body.slice(position, position + 6)}".`, + ); } +/** + * Reads four hexadecimal characters and returns the positive integer that 16bit + * hexadecimal string represents. For example, "000f" will return 15, and "dead" + * will return 57005. + * + * Returns a negative number if any char was not a valid hexadecimal digit. + */ -function urlObjectToRequestOptions(url) { - const options = { ...url }; - options.path = `${url.pathname || '/'}${url.search || ''}`; - delete options.pathname; - delete options.search; - return options; +function read16BitHexCode(body, position) { + // readHexDigit() returns -1 on error. ORing a negative value with any other + // value always produces a negative value. + return ( + (readHexDigit(body.charCodeAt(position)) << 12) | + (readHexDigit(body.charCodeAt(position + 1)) << 8) | + (readHexDigit(body.charCodeAt(position + 2)) << 4) | + readHexDigit(body.charCodeAt(position + 3)) + ); } +/** + * Reads a hexadecimal character and returns its positive integer value (0-15). + * + * '0' becomes 0, '9' becomes 9 + * 'A' becomes 10, 'F' becomes 15 + * 'a' becomes 10, 'f' becomes 15 + * + * Returns -1 if the provided character code was not a valid hexadecimal digit. + * + * HexDigit :: one of + * - `0` `1` `2` `3` `4` `5` `6` `7` `8` `9` + * - `A` `B` `C` `D` `E` `F` + * - `a` `b` `c` `d` `e` `f` + */ -function normalizeUrlObject(url) { - // If url was parsed by url.parse or new URL: - // - hostname will be set - // - host will be hostname[:port] - // - port will be set if it was explicit in the parsed string - // Otherwise, url was from request options: - // - hostname or host may be set - // - host shall not have port encoded - return { - protocol: url.protocol, - auth: url.auth, - hostname: url.hostname || url.host || 'localhost', - port: url.port, - pathname: url.pathname, - search: url.search - }; +function readHexDigit(code) { + return code >= 0x0030 && code <= 0x0039 // 0-9 + ? code - 0x0030 + : code >= 0x0041 && code <= 0x0046 // A-F + ? code - 0x0037 + : code >= 0x0061 && code <= 0x0066 // a-f + ? code - 0x0057 + : -1; } +/** + * | Escaped Character | Code Point | Character Name | + * | ----------------- | ---------- | ---------------------------- | + * | `"` | U+0022 | double quote | + * | `\` | U+005C | reverse solidus (back slash) | + * | `/` | U+002F | solidus (forward slash) | + * | `b` | U+0008 | backspace | + * | `f` | U+000C | form feed | + * | `n` | U+000A | line feed (new line) | + * | `r` | U+000D | carriage return | + * | `t` | U+0009 | horizontal tab | + */ -CacheableRequest.RequestError = class extends Error { - constructor(error) { - super(error.message); - this.name = 'RequestError'; - Object.assign(this, error); - } -}; - -CacheableRequest.CacheError = class extends Error { - constructor(error) { - super(error.message); - this.name = 'CacheError'; - Object.assign(this, error); - } -}; - -module.exports = CacheableRequest; - +function readEscapedCharacter(lexer, position) { + const body = lexer.source.body; + const code = body.charCodeAt(position + 1); -/***/ }), + switch (code) { + case 0x0022: + // " + return { + value: '\u0022', + size: 2, + }; -/***/ 22490: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + case 0x005c: + // \ + return { + value: '\u005c', + size: 2, + }; -"use strict"; + case 0x002f: + // / + return { + value: '\u002f', + size: 2, + }; -const {Transform, PassThrough} = __nccwpck_require__(12781); -const zlib = __nccwpck_require__(59796); -const mimicResponse = __nccwpck_require__(35039); + case 0x0062: + // b + return { + value: '\u0008', + size: 2, + }; -module.exports = response => { - const contentEncoding = (response.headers['content-encoding'] || '').toLowerCase(); + case 0x0066: + // f + return { + value: '\u000c', + size: 2, + }; - if (!['gzip', 'deflate', 'br'].includes(contentEncoding)) { - return response; - } + case 0x006e: + // n + return { + value: '\u000a', + size: 2, + }; - // TODO: Remove this when targeting Node.js 12. - const isBrotli = contentEncoding === 'br'; - if (isBrotli && typeof zlib.createBrotliDecompress !== 'function') { - response.destroy(new Error('Brotli is not supported on Node.js < 12')); - return response; - } + case 0x0072: + // r + return { + value: '\u000d', + size: 2, + }; - let isEmpty = true; + case 0x0074: + // t + return { + value: '\u0009', + size: 2, + }; + } - const checker = new Transform({ - transform(data, _encoding, callback) { - isEmpty = false; + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + `Invalid character escape sequence: "${body.slice( + position, + position + 2, + )}".`, + ); +} +/** + * Reads a block string token from the source file. + * + * ``` + * StringValue :: + * - `"""` BlockStringCharacter* `"""` + * + * BlockStringCharacter :: + * - SourceCharacter but not `"""` or `\"""` + * - `\"""` + * ``` + */ - callback(null, data); - }, +function readBlockString(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let lineStart = lexer.lineStart; + let position = start + 3; + let chunkStart = position; + let currentLine = ''; + const blockLines = []; - flush(callback) { - callback(); - } - }); + while (position < bodyLength) { + const code = body.charCodeAt(position); // Closing Triple-Quote (""") - const finalStream = new PassThrough({ - autoDestroy: false, - destroy(error, callback) { - response.destroy(); + if ( + code === 0x0022 && + body.charCodeAt(position + 1) === 0x0022 && + body.charCodeAt(position + 2) === 0x0022 + ) { + currentLine += body.slice(chunkStart, position); + blockLines.push(currentLine); + const token = createToken( + lexer, + _tokenKind.TokenKind.BLOCK_STRING, + start, + position + 3, // Return a string of the lines joined with U+000A. + (0, _blockString.dedentBlockStringLines)(blockLines).join('\n'), + ); + lexer.line += blockLines.length - 1; + lexer.lineStart = lineStart; + return token; + } // Escaped Triple-Quote (\""") - callback(error); - } - }); + if ( + code === 0x005c && + body.charCodeAt(position + 1) === 0x0022 && + body.charCodeAt(position + 2) === 0x0022 && + body.charCodeAt(position + 3) === 0x0022 + ) { + currentLine += body.slice(chunkStart, position); + chunkStart = position + 1; // skip only slash - const decompressStream = isBrotli ? zlib.createBrotliDecompress() : zlib.createUnzip(); + position += 4; + continue; + } // LineTerminator - decompressStream.once('error', error => { - if (isEmpty && !response.readable) { - finalStream.end(); - return; - } + if (code === 0x000a || code === 0x000d) { + currentLine += body.slice(chunkStart, position); + blockLines.push(currentLine); - finalStream.destroy(error); - }); + if (code === 0x000d && body.charCodeAt(position + 1) === 0x000a) { + position += 2; + } else { + ++position; + } - mimicResponse(response, finalStream); - response.pipe(checker).pipe(decompressStream).pipe(finalStream); + currentLine = ''; + chunkStart = position; + lineStart = position; + continue; + } // SourceCharacter - return finalStream; -}; + if (isUnicodeScalarValue(code)) { + ++position; + } else if (isSupplementaryCodePoint(body, position)) { + position += 2; + } else { + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + `Invalid character within String: ${printCodePointAt( + lexer, + position, + )}.`, + ); + } + } + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + 'Unterminated string.', + ); +} +/** + * Reads an alphanumeric + underscore name from the source. + * + * ``` + * Name :: + * - NameStart NameContinue* [lookahead != NameContinue] + * ``` + */ -/***/ }), +function readName(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let position = start + 1; -/***/ 98183: -/***/ ((module, exports) => { + while (position < bodyLength) { + const code = body.charCodeAt(position); -"use strict"; + if ((0, _characterClasses.isNameContinue)(code)) { + ++position; + } else { + break; + } + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -function isTLSSocket(socket) { - return socket.encrypted; + return createToken( + lexer, + _tokenKind.TokenKind.NAME, + start, + position, + body.slice(start, position), + ); } -const deferToConnect = (socket, fn) => { - let listeners; - if (typeof fn === 'function') { - const connect = fn; - listeners = { connect }; - } - else { - listeners = fn; - } - const hasConnectListener = typeof listeners.connect === 'function'; - const hasSecureConnectListener = typeof listeners.secureConnect === 'function'; - const hasCloseListener = typeof listeners.close === 'function'; - const onConnect = () => { - if (hasConnectListener) { - listeners.connect(); - } - if (isTLSSocket(socket) && hasSecureConnectListener) { - if (socket.authorized) { - listeners.secureConnect(); - } - else if (!socket.authorizationError) { - socket.once('secureConnect', listeners.secureConnect); - } - } - if (hasCloseListener) { - socket.once('close', listeners.close); - } - }; - if (socket.writable && !socket.connecting) { - onConnect(); - } - else if (socket.connecting) { - socket.once('connect', onConnect); - } - else if (socket.destroyed && hasCloseListener) { - listeners.close(socket._hadError); - } -}; -exports["default"] = deferToConnect; -// For CommonJS default export support -module.exports = deferToConnect; -module.exports["default"] = deferToConnect; /***/ }), -/***/ 65066: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 61922: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -const {PassThrough: PassThroughStream} = __nccwpck_require__(12781); -module.exports = options => { - options = {...options}; +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.getLocation = getLocation; - const {array} = options; - let {encoding} = options; - const isBuffer = encoding === 'buffer'; - let objectMode = false; +var _invariant = __nccwpck_require__(28847); - if (array) { - objectMode = !(encoding || isBuffer); - } else { - encoding = encoding || 'utf8'; - } +const LineRegExp = /\r\n|[\n\r]/g; +/** + * Represents a location in a Source. + */ - if (isBuffer) { - encoding = null; - } +/** + * Takes a Source and a UTF-8 character offset, and returns the corresponding + * line and column as a SourceLocation. + */ +function getLocation(source, position) { + let lastLineStart = 0; + let line = 1; - const stream = new PassThroughStream({objectMode}); + for (const match of source.body.matchAll(LineRegExp)) { + typeof match.index === 'number' || (0, _invariant.invariant)(false); - if (encoding) { - stream.setEncoding(encoding); - } + if (match.index >= position) { + break; + } - let length = 0; - const chunks = []; + lastLineStart = match.index + match[0].length; + line += 1; + } - stream.on('data', chunk => { - chunks.push(chunk); + return { + line, + column: position + 1 - lastLineStart, + }; +} - if (objectMode) { - length = chunks.length; - } else { - length += chunk.length; - } - }); - stream.getBufferedValue = () => { - if (array) { - return chunks; - } +/***/ }), - return isBuffer ? Buffer.concat(chunks, length) : chunks.join(''); - }; +/***/ 50655: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - stream.getBufferedLength = () => length; +"use strict"; - return stream; -}; +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.Parser = void 0; +exports.parse = parse; +exports.parseConstValue = parseConstValue; +exports.parseType = parseType; +exports.parseValue = parseValue; -/***/ }), +var _syntaxError = __nccwpck_require__(52295); -/***/ 86741: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var _ast = __nccwpck_require__(45494); -"use strict"; +var _directiveLocation = __nccwpck_require__(71553); -const {constants: BufferConstants} = __nccwpck_require__(14300); -const pump = __nccwpck_require__(18341); -const bufferStream = __nccwpck_require__(65066); +var _kinds = __nccwpck_require__(11927); -class MaxBufferError extends Error { - constructor() { - super('maxBuffer exceeded'); - this.name = 'MaxBufferError'; - } -} +var _lexer = __nccwpck_require__(24605); -async function getStream(inputStream, options) { - if (!inputStream) { - return Promise.reject(new Error('Expected a stream')); - } +var _source = __nccwpck_require__(65521); - options = { - maxBuffer: Infinity, - ...options - }; +var _tokenKind = __nccwpck_require__(91565); - const {maxBuffer} = options; +/** + * Given a GraphQL source, parses it into a Document. + * Throws GraphQLError if a syntax error is encountered. + */ +function parse(source, options) { + const parser = new Parser(source, options); + const document = parser.parseDocument(); + Object.defineProperty(document, 'tokenCount', { + enumerable: false, + value: parser.tokenCount, + }); + return document; +} +/** + * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for + * that value. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Values directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: valueFromAST(). + */ - let stream; - await new Promise((resolve, reject) => { - const rejectPromise = error => { - // Don't retrieve an oversized buffer. - if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) { - error.bufferedData = stream.getBufferedValue(); - } +function parseValue(source, options) { + const parser = new Parser(source, options); + parser.expectToken(_tokenKind.TokenKind.SOF); + const value = parser.parseValueLiteral(false); + parser.expectToken(_tokenKind.TokenKind.EOF); + return value; +} +/** + * Similar to parseValue(), but raises a parse error if it encounters a + * variable. The return type will be a constant value. + */ - reject(error); - }; +function parseConstValue(source, options) { + const parser = new Parser(source, options); + parser.expectToken(_tokenKind.TokenKind.SOF); + const value = parser.parseConstValueLiteral(); + parser.expectToken(_tokenKind.TokenKind.EOF); + return value; +} +/** + * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for + * that type. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Types directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: typeFromAST(). + */ - stream = pump(inputStream, bufferStream(options), error => { - if (error) { - rejectPromise(error); - return; - } +function parseType(source, options) { + const parser = new Parser(source, options); + parser.expectToken(_tokenKind.TokenKind.SOF); + const type = parser.parseTypeReference(); + parser.expectToken(_tokenKind.TokenKind.EOF); + return type; +} +/** + * This class is exported only to assist people in implementing their own parsers + * without duplicating too much code and should be used only as last resort for cases + * such as experimental syntax or if certain features could not be contributed upstream. + * + * It is still part of the internal API and is versioned, so any changes to it are never + * considered breaking changes. If you still need to support multiple versions of the + * library, please use the `versionInfo` variable for version detection. + * + * @internal + */ - resolve(); - }); +class Parser { + constructor(source, options = {}) { + const sourceObj = (0, _source.isSource)(source) + ? source + : new _source.Source(source); + this._lexer = new _lexer.Lexer(sourceObj); + this._options = options; + this._tokenCounter = 0; + } - stream.on('data', () => { - if (stream.getBufferedLength() > maxBuffer) { - rejectPromise(new MaxBufferError()); - } - }); - }); + get tokenCount() { + return this._tokenCounter; + } + /** + * Converts a name lex token into a name parse node. + */ - return stream.getBufferedValue(); -} + parseName() { + const token = this.expectToken(_tokenKind.TokenKind.NAME); + return this.node(token, { + kind: _kinds.Kind.NAME, + value: token.value, + }); + } // Implements the parsing rules in the Document section. -module.exports = getStream; -// TODO: Remove this for the next major release -module.exports["default"] = getStream; -module.exports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'}); -module.exports.array = (stream, options) => getStream(stream, {...options, array: true}); -module.exports.MaxBufferError = MaxBufferError; + /** + * Document : Definition+ + */ + + parseDocument() { + return this.node(this._lexer.token, { + kind: _kinds.Kind.DOCUMENT, + definitions: this.many( + _tokenKind.TokenKind.SOF, + this.parseDefinition, + _tokenKind.TokenKind.EOF, + ), + }); + } + /** + * Definition : + * - ExecutableDefinition + * - TypeSystemDefinition + * - TypeSystemExtension + * + * ExecutableDefinition : + * - OperationDefinition + * - FragmentDefinition + * + * TypeSystemDefinition : + * - SchemaDefinition + * - TypeDefinition + * - DirectiveDefinition + * + * TypeDefinition : + * - ScalarTypeDefinition + * - ObjectTypeDefinition + * - InterfaceTypeDefinition + * - UnionTypeDefinition + * - EnumTypeDefinition + * - InputObjectTypeDefinition + */ + parseDefinition() { + if (this.peek(_tokenKind.TokenKind.BRACE_L)) { + return this.parseOperationDefinition(); + } // Many definitions begin with a description and require a lookahead. -/***/ }), + const hasDescription = this.peekDescription(); + const keywordToken = hasDescription + ? this._lexer.lookahead() + : this._lexer.token; -/***/ 11460: -/***/ ((__unused_webpack_module, exports) => { + if (keywordToken.kind === _tokenKind.TokenKind.NAME) { + switch (keywordToken.value) { + case 'schema': + return this.parseSchemaDefinition(); -//TODO: handle reviver/dehydrate function like normal -//and handle indentation, like normal. -//if anyone needs this... please send pull request. + case 'scalar': + return this.parseScalarTypeDefinition(); -exports.stringify = function stringify (o) { - if('undefined' == typeof o) return o + case 'type': + return this.parseObjectTypeDefinition(); - if(o && Buffer.isBuffer(o)) - return JSON.stringify(':base64:' + o.toString('base64')) + case 'interface': + return this.parseInterfaceTypeDefinition(); - if(o && o.toJSON) - o = o.toJSON() + case 'union': + return this.parseUnionTypeDefinition(); - if(o && 'object' === typeof o) { - var s = '' - var array = Array.isArray(o) - s = array ? '[' : '{' - var first = true + case 'enum': + return this.parseEnumTypeDefinition(); - for(var k in o) { - var ignore = 'function' == typeof o[k] || (!array && 'undefined' === typeof o[k]) - if(Object.hasOwnProperty.call(o, k) && !ignore) { - if(!first) - s += ',' - first = false - if (array) { - if(o[k] == undefined) - s += 'null' - else - s += stringify(o[k]) - } else if (o[k] !== void(0)) { - s += stringify(k) + ':' + stringify(o[k]) - } + case 'input': + return this.parseInputObjectTypeDefinition(); + + case 'directive': + return this.parseDirectiveDefinition(); } - } - s += array ? ']' : '}' + if (hasDescription) { + throw (0, _syntaxError.syntaxError)( + this._lexer.source, + this._lexer.token.start, + 'Unexpected description, descriptions are supported only on type definitions.', + ); + } - return s - } else if ('string' === typeof o) { - return JSON.stringify(/^:/.test(o) ? ':' + o : o) - } else if ('undefined' === typeof o) { - return 'null'; - } else - return JSON.stringify(o) -} + switch (keywordToken.value) { + case 'query': + case 'mutation': + case 'subscription': + return this.parseOperationDefinition(); -exports.parse = function (s) { - return JSON.parse(s, function (key, value) { - if('string' === typeof value) { - if(/^:base64:/.test(value)) - return Buffer.from(value.substring(8), 'base64') - else - return /^:/.test(value) ? value.substring(1) : value + case 'fragment': + return this.parseFragmentDefinition(); + + case 'extend': + return this.parseTypeSystemExtension(); + } } - return value - }) -} + throw this.unexpected(keywordToken); + } // Implements the parsing rules in the Operations section. -/***/ }), + /** + * OperationDefinition : + * - SelectionSet + * - OperationType Name? VariableDefinitions? Directives? SelectionSet + */ -/***/ 94432: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + parseOperationDefinition() { + const start = this._lexer.token; -"use strict"; + if (this.peek(_tokenKind.TokenKind.BRACE_L)) { + return this.node(start, { + kind: _kinds.Kind.OPERATION_DEFINITION, + operation: _ast.OperationTypeNode.QUERY, + name: undefined, + variableDefinitions: [], + directives: [], + selectionSet: this.parseSelectionSet(), + }); + } + const operation = this.parseOperationType(); + let name; -const EventEmitter = __nccwpck_require__(82361); -const JSONB = __nccwpck_require__(11460); + if (this.peek(_tokenKind.TokenKind.NAME)) { + name = this.parseName(); + } -const loadStore = options => { - const adapters = { - redis: '@keyv/redis', - rediss: '@keyv/redis', - mongodb: '@keyv/mongo', - mongo: '@keyv/mongo', - sqlite: '@keyv/sqlite', - postgresql: '@keyv/postgres', - postgres: '@keyv/postgres', - mysql: '@keyv/mysql', - etcd: '@keyv/etcd', - offline: '@keyv/offline', - tiered: '@keyv/tiered', - }; - if (options.adapter || options.uri) { - const adapter = options.adapter || /^[^:+]*/.exec(options.uri)[0]; - return new (require(adapters[adapter]))(options); - } + return this.node(start, { + kind: _kinds.Kind.OPERATION_DEFINITION, + operation, + name, + variableDefinitions: this.parseVariableDefinitions(), + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet(), + }); + } + /** + * OperationType : one of query mutation subscription + */ - return new Map(); -}; + parseOperationType() { + const operationToken = this.expectToken(_tokenKind.TokenKind.NAME); -const iterableAdapters = [ - 'sqlite', - 'postgres', - 'mysql', - 'mongo', - 'redis', - 'tiered', -]; + switch (operationToken.value) { + case 'query': + return _ast.OperationTypeNode.QUERY; -class Keyv extends EventEmitter { - constructor(uri, {emitErrors = true, ...options} = {}) { - super(); - this.opts = { - namespace: 'keyv', - serialize: JSONB.stringify, - deserialize: JSONB.parse, - ...((typeof uri === 'string') ? {uri} : uri), - ...options, - }; + case 'mutation': + return _ast.OperationTypeNode.MUTATION; - if (!this.opts.store) { - const adapterOptions = {...this.opts}; - this.opts.store = loadStore(adapterOptions); - } + case 'subscription': + return _ast.OperationTypeNode.SUBSCRIPTION; + } - if (this.opts.compression) { - const compression = this.opts.compression; - this.opts.serialize = compression.serialize.bind(compression); - this.opts.deserialize = compression.deserialize.bind(compression); - } + throw this.unexpected(operationToken); + } + /** + * VariableDefinitions : ( VariableDefinition+ ) + */ - if (typeof this.opts.store.on === 'function' && emitErrors) { - this.opts.store.on('error', error => this.emit('error', error)); - } + parseVariableDefinitions() { + return this.optionalMany( + _tokenKind.TokenKind.PAREN_L, + this.parseVariableDefinition, + _tokenKind.TokenKind.PAREN_R, + ); + } + /** + * VariableDefinition : Variable : Type DefaultValue? Directives[Const]? + */ - this.opts.store.namespace = this.opts.namespace; + parseVariableDefinition() { + return this.node(this._lexer.token, { + kind: _kinds.Kind.VARIABLE_DEFINITION, + variable: this.parseVariable(), + type: + (this.expectToken(_tokenKind.TokenKind.COLON), + this.parseTypeReference()), + defaultValue: this.expectOptionalToken(_tokenKind.TokenKind.EQUALS) + ? this.parseConstValueLiteral() + : undefined, + directives: this.parseConstDirectives(), + }); + } + /** + * Variable : $ Name + */ - const generateIterator = iterator => async function * () { - for await (const [key, raw] of typeof iterator === 'function' - ? iterator(this.opts.store.namespace) - : iterator) { - const data = await this.opts.deserialize(raw); - if (this.opts.store.namespace && !key.includes(this.opts.store.namespace)) { - continue; - } + parseVariable() { + const start = this._lexer.token; + this.expectToken(_tokenKind.TokenKind.DOLLAR); + return this.node(start, { + kind: _kinds.Kind.VARIABLE, + name: this.parseName(), + }); + } + /** + * ``` + * SelectionSet : { Selection+ } + * ``` + */ - if (typeof data.expires === 'number' && Date.now() > data.expires) { - this.delete(key); - continue; - } + parseSelectionSet() { + return this.node(this._lexer.token, { + kind: _kinds.Kind.SELECTION_SET, + selections: this.many( + _tokenKind.TokenKind.BRACE_L, + this.parseSelection, + _tokenKind.TokenKind.BRACE_R, + ), + }); + } + /** + * Selection : + * - Field + * - FragmentSpread + * - InlineFragment + */ - yield [this._getKeyUnprefix(key), data.value]; - } - }; + parseSelection() { + return this.peek(_tokenKind.TokenKind.SPREAD) + ? this.parseFragment() + : this.parseField(); + } + /** + * Field : Alias? Name Arguments? Directives? SelectionSet? + * + * Alias : Name : + */ - // Attach iterators - if (typeof this.opts.store[Symbol.iterator] === 'function' && this.opts.store instanceof Map) { - this.iterator = generateIterator(this.opts.store); - } else if (typeof this.opts.store.iterator === 'function' && this.opts.store.opts - && this._checkIterableAdaptar()) { - this.iterator = generateIterator(this.opts.store.iterator.bind(this.opts.store)); - } - } + parseField() { + const start = this._lexer.token; + const nameOrAlias = this.parseName(); + let alias; + let name; - _checkIterableAdaptar() { - return iterableAdapters.includes(this.opts.store.opts.dialect) - || iterableAdapters.findIndex(element => this.opts.store.opts.url.includes(element)) >= 0; - } + if (this.expectOptionalToken(_tokenKind.TokenKind.COLON)) { + alias = nameOrAlias; + name = this.parseName(); + } else { + name = nameOrAlias; + } - _getKeyPrefix(key) { - return `${this.opts.namespace}:${key}`; - } + return this.node(start, { + kind: _kinds.Kind.FIELD, + alias, + name, + arguments: this.parseArguments(false), + directives: this.parseDirectives(false), + selectionSet: this.peek(_tokenKind.TokenKind.BRACE_L) + ? this.parseSelectionSet() + : undefined, + }); + } + /** + * Arguments[Const] : ( Argument[?Const]+ ) + */ - _getKeyPrefixArray(keys) { - return keys.map(key => `${this.opts.namespace}:${key}`); - } + parseArguments(isConst) { + const item = isConst ? this.parseConstArgument : this.parseArgument; + return this.optionalMany( + _tokenKind.TokenKind.PAREN_L, + item, + _tokenKind.TokenKind.PAREN_R, + ); + } + /** + * Argument[Const] : Name : Value[?Const] + */ - _getKeyUnprefix(key) { - return key - .split(':') - .splice(1) - .join(':'); - } + parseArgument(isConst = false) { + const start = this._lexer.token; + const name = this.parseName(); + this.expectToken(_tokenKind.TokenKind.COLON); + return this.node(start, { + kind: _kinds.Kind.ARGUMENT, + name, + value: this.parseValueLiteral(isConst), + }); + } - get(key, options) { - const {store} = this.opts; - const isArray = Array.isArray(key); - const keyPrefixed = isArray ? this._getKeyPrefixArray(key) : this._getKeyPrefix(key); - if (isArray && store.getMany === undefined) { - const promises = []; - for (const key of keyPrefixed) { - promises.push(Promise.resolve() - .then(() => store.get(key)) - .then(data => (typeof data === 'string') ? this.opts.deserialize(data) : (this.opts.compression ? this.opts.deserialize(data) : data)) - .then(data => { - if (data === undefined || data === null) { - return undefined; - } + parseConstArgument() { + return this.parseArgument(true); + } // Implements the parsing rules in the Fragments section. - if (typeof data.expires === 'number' && Date.now() > data.expires) { - return this.delete(key).then(() => undefined); - } + /** + * Corresponds to both FragmentSpread and InlineFragment in the spec. + * + * FragmentSpread : ... FragmentName Directives? + * + * InlineFragment : ... TypeCondition? Directives? SelectionSet + */ - return (options && options.raw) ? data : data.value; - }), - ); - } + parseFragment() { + const start = this._lexer.token; + this.expectToken(_tokenKind.TokenKind.SPREAD); + const hasTypeCondition = this.expectOptionalKeyword('on'); - return Promise.allSettled(promises) - .then(values => { - const data = []; - for (const value of values) { - data.push(value.value); - } + if (!hasTypeCondition && this.peek(_tokenKind.TokenKind.NAME)) { + return this.node(start, { + kind: _kinds.Kind.FRAGMENT_SPREAD, + name: this.parseFragmentName(), + directives: this.parseDirectives(false), + }); + } - return data; - }); - } + return this.node(start, { + kind: _kinds.Kind.INLINE_FRAGMENT, + typeCondition: hasTypeCondition ? this.parseNamedType() : undefined, + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet(), + }); + } + /** + * FragmentDefinition : + * - fragment FragmentName on TypeCondition Directives? SelectionSet + * + * TypeCondition : NamedType + */ - return Promise.resolve() - .then(() => isArray ? store.getMany(keyPrefixed) : store.get(keyPrefixed)) - .then(data => (typeof data === 'string') ? this.opts.deserialize(data) : (this.opts.compression ? this.opts.deserialize(data) : data)) - .then(data => { - if (data === undefined || data === null) { - return undefined; - } + parseFragmentDefinition() { + const start = this._lexer.token; + this.expectKeyword('fragment'); // Legacy support for defining variables within fragments changes + // the grammar of FragmentDefinition: + // - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet - if (isArray) { - const result = []; + if (this._options.allowLegacyFragmentVariables === true) { + return this.node(start, { + kind: _kinds.Kind.FRAGMENT_DEFINITION, + name: this.parseFragmentName(), + variableDefinitions: this.parseVariableDefinitions(), + typeCondition: (this.expectKeyword('on'), this.parseNamedType()), + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet(), + }); + } - for (let row of data) { - if ((typeof row === 'string')) { - row = this.opts.deserialize(row); - } + return this.node(start, { + kind: _kinds.Kind.FRAGMENT_DEFINITION, + name: this.parseFragmentName(), + typeCondition: (this.expectKeyword('on'), this.parseNamedType()), + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet(), + }); + } + /** + * FragmentName : Name but not `on` + */ - if (row === undefined || row === null) { - result.push(undefined); - continue; - } + parseFragmentName() { + if (this._lexer.token.value === 'on') { + throw this.unexpected(); + } - if (typeof row.expires === 'number' && Date.now() > row.expires) { - this.delete(key).then(() => undefined); - result.push(undefined); - } else { - result.push((options && options.raw) ? row : row.value); - } - } + return this.parseName(); + } // Implements the parsing rules in the Values section. - return result; - } + /** + * Value[Const] : + * - [~Const] Variable + * - IntValue + * - FloatValue + * - StringValue + * - BooleanValue + * - NullValue + * - EnumValue + * - ListValue[?Const] + * - ObjectValue[?Const] + * + * BooleanValue : one of `true` `false` + * + * NullValue : `null` + * + * EnumValue : Name but not `true`, `false` or `null` + */ - if (typeof data.expires === 'number' && Date.now() > data.expires) { - return this.delete(key).then(() => undefined); - } + parseValueLiteral(isConst) { + const token = this._lexer.token; - return (options && options.raw) ? data : data.value; - }); - } + switch (token.kind) { + case _tokenKind.TokenKind.BRACKET_L: + return this.parseList(isConst); - set(key, value, ttl) { - const keyPrefixed = this._getKeyPrefix(key); - if (typeof ttl === 'undefined') { - ttl = this.opts.ttl; - } + case _tokenKind.TokenKind.BRACE_L: + return this.parseObject(isConst); - if (ttl === 0) { - ttl = undefined; - } + case _tokenKind.TokenKind.INT: + this.advanceLexer(); + return this.node(token, { + kind: _kinds.Kind.INT, + value: token.value, + }); - const {store} = this.opts; + case _tokenKind.TokenKind.FLOAT: + this.advanceLexer(); + return this.node(token, { + kind: _kinds.Kind.FLOAT, + value: token.value, + }); - return Promise.resolve() - .then(() => { - const expires = (typeof ttl === 'number') ? (Date.now() + ttl) : null; - if (typeof value === 'symbol') { - this.emit('error', 'symbol cannot be serialized'); - } + case _tokenKind.TokenKind.STRING: + case _tokenKind.TokenKind.BLOCK_STRING: + return this.parseStringLiteral(); - value = {value, expires}; - return this.opts.serialize(value); - }) - .then(value => store.set(keyPrefixed, value, ttl)) - .then(() => true); - } + case _tokenKind.TokenKind.NAME: + this.advanceLexer(); - delete(key) { - const {store} = this.opts; - if (Array.isArray(key)) { - const keyPrefixed = this._getKeyPrefixArray(key); - if (store.deleteMany === undefined) { - const promises = []; - for (const key of keyPrefixed) { - promises.push(store.delete(key)); - } + switch (token.value) { + case 'true': + return this.node(token, { + kind: _kinds.Kind.BOOLEAN, + value: true, + }); - return Promise.allSettled(promises) - .then(values => values.every(x => x.value === true)); - } + case 'false': + return this.node(token, { + kind: _kinds.Kind.BOOLEAN, + value: false, + }); - return Promise.resolve() - .then(() => store.deleteMany(keyPrefixed)); - } + case 'null': + return this.node(token, { + kind: _kinds.Kind.NULL, + }); - const keyPrefixed = this._getKeyPrefix(key); - return Promise.resolve() - .then(() => store.delete(keyPrefixed)); - } + default: + return this.node(token, { + kind: _kinds.Kind.ENUM, + value: token.value, + }); + } - clear() { - const {store} = this.opts; - return Promise.resolve() - .then(() => store.clear()); - } + case _tokenKind.TokenKind.DOLLAR: + if (isConst) { + this.expectToken(_tokenKind.TokenKind.DOLLAR); - has(key) { - const keyPrefixed = this._getKeyPrefix(key); - const {store} = this.opts; - return Promise.resolve() - .then(async () => { - if (typeof store.has === 'function') { - return store.has(keyPrefixed); - } + if (this._lexer.token.kind === _tokenKind.TokenKind.NAME) { + const varName = this._lexer.token.value; + throw (0, _syntaxError.syntaxError)( + this._lexer.source, + token.start, + `Unexpected variable "$${varName}" in constant value.`, + ); + } else { + throw this.unexpected(token); + } + } - const value = await store.get(keyPrefixed); - return value !== undefined; - }); - } + return this.parseVariable(); - disconnect() { - const {store} = this.opts; - if (typeof store.disconnect === 'function') { - return store.disconnect(); - } - } -} + default: + throw this.unexpected(); + } + } -module.exports = Keyv; + parseConstValueLiteral() { + return this.parseValueLiteral(true); + } + parseStringLiteral() { + const token = this._lexer.token; + this.advanceLexer(); + return this.node(token, { + kind: _kinds.Kind.STRING, + value: token.value, + block: token.kind === _tokenKind.TokenKind.BLOCK_STRING, + }); + } + /** + * ListValue[Const] : + * - [ ] + * - [ Value[?Const]+ ] + */ -/***/ }), + parseList(isConst) { + const item = () => this.parseValueLiteral(isConst); -/***/ 35039: -/***/ ((module) => { + return this.node(this._lexer.token, { + kind: _kinds.Kind.LIST, + values: this.any( + _tokenKind.TokenKind.BRACKET_L, + item, + _tokenKind.TokenKind.BRACKET_R, + ), + }); + } + /** + * ``` + * ObjectValue[Const] : + * - { } + * - { ObjectField[?Const]+ } + * ``` + */ -"use strict"; + parseObject(isConst) { + const item = () => this.parseObjectField(isConst); + return this.node(this._lexer.token, { + kind: _kinds.Kind.OBJECT, + fields: this.any( + _tokenKind.TokenKind.BRACE_L, + item, + _tokenKind.TokenKind.BRACE_R, + ), + }); + } + /** + * ObjectField[Const] : Name : Value[?Const] + */ -// We define these manually to ensure they're always copied -// even if they would move up the prototype chain -// https://nodejs.org/api/http.html#http_class_http_incomingmessage -const knownProperties = [ - 'aborted', - 'complete', - 'headers', - 'httpVersion', - 'httpVersionMinor', - 'httpVersionMajor', - 'method', - 'rawHeaders', - 'rawTrailers', - 'setTimeout', - 'socket', - 'statusCode', - 'statusMessage', - 'trailers', - 'url' -]; + parseObjectField(isConst) { + const start = this._lexer.token; + const name = this.parseName(); + this.expectToken(_tokenKind.TokenKind.COLON); + return this.node(start, { + kind: _kinds.Kind.OBJECT_FIELD, + name, + value: this.parseValueLiteral(isConst), + }); + } // Implements the parsing rules in the Directives section. -module.exports = (fromStream, toStream) => { - if (toStream._readableState.autoDestroy) { - throw new Error('The second stream must have the `autoDestroy` option set to `false`'); - } + /** + * Directives[Const] : Directive[?Const]+ + */ - const fromProperties = new Set(Object.keys(fromStream).concat(knownProperties)); + parseDirectives(isConst) { + const directives = []; - const properties = {}; + while (this.peek(_tokenKind.TokenKind.AT)) { + directives.push(this.parseDirective(isConst)); + } - for (const property of fromProperties) { - // Don't overwrite existing properties. - if (property in toStream) { - continue; - } + return directives; + } - properties[property] = { - get() { - const value = fromStream[property]; - const isFunction = typeof value === 'function'; + parseConstDirectives() { + return this.parseDirectives(true); + } + /** + * ``` + * Directive[Const] : @ Name Arguments[?Const]? + * ``` + */ - return isFunction ? value.bind(fromStream) : value; - }, - set(value) { - fromStream[property] = value; - }, - enumerable: true, - configurable: false - }; - } + parseDirective(isConst) { + const start = this._lexer.token; + this.expectToken(_tokenKind.TokenKind.AT); + return this.node(start, { + kind: _kinds.Kind.DIRECTIVE, + name: this.parseName(), + arguments: this.parseArguments(isConst), + }); + } // Implements the parsing rules in the Types section. - Object.defineProperties(toStream, properties); + /** + * Type : + * - NamedType + * - ListType + * - NonNullType + */ - fromStream.once('aborted', () => { - toStream.destroy(); + parseTypeReference() { + const start = this._lexer.token; + let type; - toStream.emit('aborted'); - }); + if (this.expectOptionalToken(_tokenKind.TokenKind.BRACKET_L)) { + const innerType = this.parseTypeReference(); + this.expectToken(_tokenKind.TokenKind.BRACKET_R); + type = this.node(start, { + kind: _kinds.Kind.LIST_TYPE, + type: innerType, + }); + } else { + type = this.parseNamedType(); + } - fromStream.once('close', () => { - if (fromStream.complete) { - if (toStream.readable) { - toStream.once('end', () => { - toStream.emit('close'); - }); - } else { - toStream.emit('close'); - } - } else { - toStream.emit('close'); - } - }); + if (this.expectOptionalToken(_tokenKind.TokenKind.BANG)) { + return this.node(start, { + kind: _kinds.Kind.NON_NULL_TYPE, + type, + }); + } - return toStream; -}; + return type; + } + /** + * NamedType : Name + */ + parseNamedType() { + return this.node(this._lexer.token, { + kind: _kinds.Kind.NAMED_TYPE, + name: this.parseName(), + }); + } // Implements the parsing rules in the Type Definition section. -/***/ }), + peekDescription() { + return ( + this.peek(_tokenKind.TokenKind.STRING) || + this.peek(_tokenKind.TokenKind.BLOCK_STRING) + ); + } + /** + * Description : StringValue + */ -/***/ 88580: -/***/ ((module) => { + parseDescription() { + if (this.peekDescription()) { + return this.parseStringLiteral(); + } + } + /** + * ``` + * SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ } + * ``` + */ -"use strict"; + parseSchemaDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('schema'); + const directives = this.parseConstDirectives(); + const operationTypes = this.many( + _tokenKind.TokenKind.BRACE_L, + this.parseOperationTypeDefinition, + _tokenKind.TokenKind.BRACE_R, + ); + return this.node(start, { + kind: _kinds.Kind.SCHEMA_DEFINITION, + description, + directives, + operationTypes, + }); + } + /** + * OperationTypeDefinition : OperationType : NamedType + */ + parseOperationTypeDefinition() { + const start = this._lexer.token; + const operation = this.parseOperationType(); + this.expectToken(_tokenKind.TokenKind.COLON); + const type = this.parseNamedType(); + return this.node(start, { + kind: _kinds.Kind.OPERATION_TYPE_DEFINITION, + operation, + type, + }); + } + /** + * ScalarTypeDefinition : Description? scalar Name Directives[Const]? + */ -// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs -const DATA_URL_DEFAULT_MIME_TYPE = 'text/plain'; -const DATA_URL_DEFAULT_CHARSET = 'us-ascii'; + parseScalarTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('scalar'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + return this.node(start, { + kind: _kinds.Kind.SCALAR_TYPE_DEFINITION, + description, + name, + directives, + }); + } + /** + * ObjectTypeDefinition : + * Description? + * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition? + */ -const testParameter = (name, filters) => { - return filters.some(filter => filter instanceof RegExp ? filter.test(name) : filter === name); -}; + parseObjectTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('type'); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseConstDirectives(); + const fields = this.parseFieldsDefinition(); + return this.node(start, { + kind: _kinds.Kind.OBJECT_TYPE_DEFINITION, + description, + name, + interfaces, + directives, + fields, + }); + } + /** + * ImplementsInterfaces : + * - implements `&`? NamedType + * - ImplementsInterfaces & NamedType + */ -const normalizeDataURL = (urlString, {stripHash}) => { - const match = /^data:(?[^,]*?),(?[^#]*?)(?:#(?.*))?$/.exec(urlString); + parseImplementsInterfaces() { + return this.expectOptionalKeyword('implements') + ? this.delimitedMany(_tokenKind.TokenKind.AMP, this.parseNamedType) + : []; + } + /** + * ``` + * FieldsDefinition : { FieldDefinition+ } + * ``` + */ - if (!match) { - throw new Error(`Invalid URL: ${urlString}`); - } + parseFieldsDefinition() { + return this.optionalMany( + _tokenKind.TokenKind.BRACE_L, + this.parseFieldDefinition, + _tokenKind.TokenKind.BRACE_R, + ); + } + /** + * FieldDefinition : + * - Description? Name ArgumentsDefinition? : Type Directives[Const]? + */ - let {type, data, hash} = match.groups; - const mediaType = type.split(';'); - hash = stripHash ? '' : hash; + parseFieldDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + const name = this.parseName(); + const args = this.parseArgumentDefs(); + this.expectToken(_tokenKind.TokenKind.COLON); + const type = this.parseTypeReference(); + const directives = this.parseConstDirectives(); + return this.node(start, { + kind: _kinds.Kind.FIELD_DEFINITION, + description, + name, + arguments: args, + type, + directives, + }); + } + /** + * ArgumentsDefinition : ( InputValueDefinition+ ) + */ - let isBase64 = false; - if (mediaType[mediaType.length - 1] === 'base64') { - mediaType.pop(); - isBase64 = true; - } + parseArgumentDefs() { + return this.optionalMany( + _tokenKind.TokenKind.PAREN_L, + this.parseInputValueDef, + _tokenKind.TokenKind.PAREN_R, + ); + } + /** + * InputValueDefinition : + * - Description? Name : Type DefaultValue? Directives[Const]? + */ - // Lowercase MIME type - const mimeType = (mediaType.shift() || '').toLowerCase(); - const attributes = mediaType - .map(attribute => { - let [key, value = ''] = attribute.split('=').map(string => string.trim()); + parseInputValueDef() { + const start = this._lexer.token; + const description = this.parseDescription(); + const name = this.parseName(); + this.expectToken(_tokenKind.TokenKind.COLON); + const type = this.parseTypeReference(); + let defaultValue; - // Lowercase `charset` - if (key === 'charset') { - value = value.toLowerCase(); + if (this.expectOptionalToken(_tokenKind.TokenKind.EQUALS)) { + defaultValue = this.parseConstValueLiteral(); + } - if (value === DATA_URL_DEFAULT_CHARSET) { - return ''; - } - } + const directives = this.parseConstDirectives(); + return this.node(start, { + kind: _kinds.Kind.INPUT_VALUE_DEFINITION, + description, + name, + type, + defaultValue, + directives, + }); + } + /** + * InterfaceTypeDefinition : + * - Description? interface Name Directives[Const]? FieldsDefinition? + */ - return `${key}${value ? `=${value}` : ''}`; - }) - .filter(Boolean); + parseInterfaceTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('interface'); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseConstDirectives(); + const fields = this.parseFieldsDefinition(); + return this.node(start, { + kind: _kinds.Kind.INTERFACE_TYPE_DEFINITION, + description, + name, + interfaces, + directives, + fields, + }); + } + /** + * UnionTypeDefinition : + * - Description? union Name Directives[Const]? UnionMemberTypes? + */ + + parseUnionTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('union'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const types = this.parseUnionMemberTypes(); + return this.node(start, { + kind: _kinds.Kind.UNION_TYPE_DEFINITION, + description, + name, + directives, + types, + }); + } + /** + * UnionMemberTypes : + * - = `|`? NamedType + * - UnionMemberTypes | NamedType + */ - const normalizedMediaType = [ - ...attributes - ]; + parseUnionMemberTypes() { + return this.expectOptionalToken(_tokenKind.TokenKind.EQUALS) + ? this.delimitedMany(_tokenKind.TokenKind.PIPE, this.parseNamedType) + : []; + } + /** + * EnumTypeDefinition : + * - Description? enum Name Directives[Const]? EnumValuesDefinition? + */ - if (isBase64) { - normalizedMediaType.push('base64'); - } + parseEnumTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('enum'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const values = this.parseEnumValuesDefinition(); + return this.node(start, { + kind: _kinds.Kind.ENUM_TYPE_DEFINITION, + description, + name, + directives, + values, + }); + } + /** + * ``` + * EnumValuesDefinition : { EnumValueDefinition+ } + * ``` + */ - if (normalizedMediaType.length !== 0 || (mimeType && mimeType !== DATA_URL_DEFAULT_MIME_TYPE)) { - normalizedMediaType.unshift(mimeType); - } + parseEnumValuesDefinition() { + return this.optionalMany( + _tokenKind.TokenKind.BRACE_L, + this.parseEnumValueDefinition, + _tokenKind.TokenKind.BRACE_R, + ); + } + /** + * EnumValueDefinition : Description? EnumValue Directives[Const]? + */ - return `data:${normalizedMediaType.join(';')},${isBase64 ? data.trim() : data}${hash ? `#${hash}` : ''}`; -}; + parseEnumValueDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + const name = this.parseEnumValueName(); + const directives = this.parseConstDirectives(); + return this.node(start, { + kind: _kinds.Kind.ENUM_VALUE_DEFINITION, + description, + name, + directives, + }); + } + /** + * EnumValue : Name but not `true`, `false` or `null` + */ -const normalizeUrl = (urlString, options) => { - options = { - defaultProtocol: 'http:', - normalizeProtocol: true, - forceHttp: false, - forceHttps: false, - stripAuthentication: true, - stripHash: false, - stripTextFragment: true, - stripWWW: true, - removeQueryParameters: [/^utm_\w+/i], - removeTrailingSlash: true, - removeSingleSlash: true, - removeDirectoryIndex: false, - sortQueryParameters: true, - ...options - }; + parseEnumValueName() { + if ( + this._lexer.token.value === 'true' || + this._lexer.token.value === 'false' || + this._lexer.token.value === 'null' + ) { + throw (0, _syntaxError.syntaxError)( + this._lexer.source, + this._lexer.token.start, + `${getTokenDesc( + this._lexer.token, + )} is reserved and cannot be used for an enum value.`, + ); + } - urlString = urlString.trim(); + return this.parseName(); + } + /** + * InputObjectTypeDefinition : + * - Description? input Name Directives[Const]? InputFieldsDefinition? + */ - // Data URL - if (/^data:/i.test(urlString)) { - return normalizeDataURL(urlString, options); - } + parseInputObjectTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('input'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const fields = this.parseInputFieldsDefinition(); + return this.node(start, { + kind: _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION, + description, + name, + directives, + fields, + }); + } + /** + * ``` + * InputFieldsDefinition : { InputValueDefinition+ } + * ``` + */ - if (/^view-source:/i.test(urlString)) { - throw new Error('`view-source:` is not supported as it is a non-standard protocol'); - } + parseInputFieldsDefinition() { + return this.optionalMany( + _tokenKind.TokenKind.BRACE_L, + this.parseInputValueDef, + _tokenKind.TokenKind.BRACE_R, + ); + } + /** + * TypeSystemExtension : + * - SchemaExtension + * - TypeExtension + * + * TypeExtension : + * - ScalarTypeExtension + * - ObjectTypeExtension + * - InterfaceTypeExtension + * - UnionTypeExtension + * - EnumTypeExtension + * - InputObjectTypeDefinition + */ - const hasRelativeProtocol = urlString.startsWith('//'); - const isRelativeUrl = !hasRelativeProtocol && /^\.*\//.test(urlString); + parseTypeSystemExtension() { + const keywordToken = this._lexer.lookahead(); - // Prepend protocol - if (!isRelativeUrl) { - urlString = urlString.replace(/^(?!(?:\w+:)?\/\/)|^\/\//, options.defaultProtocol); - } + if (keywordToken.kind === _tokenKind.TokenKind.NAME) { + switch (keywordToken.value) { + case 'schema': + return this.parseSchemaExtension(); - const urlObj = new URL(urlString); + case 'scalar': + return this.parseScalarTypeExtension(); - if (options.forceHttp && options.forceHttps) { - throw new Error('The `forceHttp` and `forceHttps` options cannot be used together'); - } + case 'type': + return this.parseObjectTypeExtension(); - if (options.forceHttp && urlObj.protocol === 'https:') { - urlObj.protocol = 'http:'; - } + case 'interface': + return this.parseInterfaceTypeExtension(); - if (options.forceHttps && urlObj.protocol === 'http:') { - urlObj.protocol = 'https:'; - } + case 'union': + return this.parseUnionTypeExtension(); - // Remove auth - if (options.stripAuthentication) { - urlObj.username = ''; - urlObj.password = ''; - } + case 'enum': + return this.parseEnumTypeExtension(); - // Remove hash - if (options.stripHash) { - urlObj.hash = ''; - } else if (options.stripTextFragment) { - urlObj.hash = urlObj.hash.replace(/#?:~:text.*?$/i, ''); - } + case 'input': + return this.parseInputObjectTypeExtension(); + } + } - // Remove duplicate slashes if not preceded by a protocol - if (urlObj.pathname) { - urlObj.pathname = urlObj.pathname.replace(/(? 0) { - let pathComponents = urlObj.pathname.split('/'); - const lastComponent = pathComponents[pathComponents.length - 1]; + return this.node(start, { + kind: _kinds.Kind.SCHEMA_EXTENSION, + directives, + operationTypes, + }); + } + /** + * ScalarTypeExtension : + * - extend scalar Name Directives[Const] + */ - if (testParameter(lastComponent, options.removeDirectoryIndex)) { - pathComponents = pathComponents.slice(0, pathComponents.length - 1); - urlObj.pathname = pathComponents.slice(1).join('/') + '/'; - } - } + parseScalarTypeExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('scalar'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); - if (urlObj.hostname) { - // Remove trailing dot - urlObj.hostname = urlObj.hostname.replace(/\.$/, ''); + if (directives.length === 0) { + throw this.unexpected(); + } - // Remove `www.` - if (options.stripWWW && /^www\.(?!www\.)(?:[a-z\-\d]{1,63})\.(?:[a-z.\-\d]{2,63})$/.test(urlObj.hostname)) { - // Each label should be max 63 at length (min: 1). - // Source: https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names - // Each TLD should be up to 63 characters long (min: 2). - // It is technically possible to have a single character TLD, but none currently exist. - urlObj.hostname = urlObj.hostname.replace(/^www\./, ''); - } - } + return this.node(start, { + kind: _kinds.Kind.SCALAR_TYPE_EXTENSION, + name, + directives, + }); + } + /** + * ObjectTypeExtension : + * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition + * - extend type Name ImplementsInterfaces? Directives[Const] + * - extend type Name ImplementsInterfaces + */ - // Remove query unwanted parameters - if (Array.isArray(options.removeQueryParameters)) { - for (const key of [...urlObj.searchParams.keys()]) { - if (testParameter(key, options.removeQueryParameters)) { - urlObj.searchParams.delete(key); - } - } - } + parseObjectTypeExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('type'); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseConstDirectives(); + const fields = this.parseFieldsDefinition(); - if (options.removeQueryParameters === true) { - urlObj.search = ''; - } + if ( + interfaces.length === 0 && + directives.length === 0 && + fields.length === 0 + ) { + throw this.unexpected(); + } - // Sort query parameters - if (options.sortQueryParameters) { - urlObj.searchParams.sort(); - } + return this.node(start, { + kind: _kinds.Kind.OBJECT_TYPE_EXTENSION, + name, + interfaces, + directives, + fields, + }); + } + /** + * InterfaceTypeExtension : + * - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition + * - extend interface Name ImplementsInterfaces? Directives[Const] + * - extend interface Name ImplementsInterfaces + */ - if (options.removeTrailingSlash) { - urlObj.pathname = urlObj.pathname.replace(/\/$/, ''); - } + parseInterfaceTypeExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('interface'); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseConstDirectives(); + const fields = this.parseFieldsDefinition(); - const oldUrlString = urlString; + if ( + interfaces.length === 0 && + directives.length === 0 && + fields.length === 0 + ) { + throw this.unexpected(); + } - // Take advantage of many of the Node `url` normalizations - urlString = urlObj.toString(); + return this.node(start, { + kind: _kinds.Kind.INTERFACE_TYPE_EXTENSION, + name, + interfaces, + directives, + fields, + }); + } + /** + * UnionTypeExtension : + * - extend union Name Directives[Const]? UnionMemberTypes + * - extend union Name Directives[Const] + */ - if (!options.removeSingleSlash && urlObj.pathname === '/' && !oldUrlString.endsWith('/') && urlObj.hash === '') { - urlString = urlString.replace(/\/$/, ''); - } + parseUnionTypeExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('union'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const types = this.parseUnionMemberTypes(); - // Remove ending `/` unless removeSingleSlash is false - if ((options.removeTrailingSlash || urlObj.pathname === '/') && urlObj.hash === '' && options.removeSingleSlash) { - urlString = urlString.replace(/\/$/, ''); - } + if (directives.length === 0 && types.length === 0) { + throw this.unexpected(); + } - // Restore relative protocol, if applicable - if (hasRelativeProtocol && !options.normalizeProtocol) { - urlString = urlString.replace(/^http:\/\//, '//'); - } + return this.node(start, { + kind: _kinds.Kind.UNION_TYPE_EXTENSION, + name, + directives, + types, + }); + } + /** + * EnumTypeExtension : + * - extend enum Name Directives[Const]? EnumValuesDefinition + * - extend enum Name Directives[Const] + */ - // Remove http/https - if (options.stripProtocol) { - urlString = urlString.replace(/^(?:https?:)?\/\//, ''); - } + parseEnumTypeExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('enum'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const values = this.parseEnumValuesDefinition(); - return urlString; -}; + if (directives.length === 0 && values.length === 0) { + throw this.unexpected(); + } -module.exports = normalizeUrl; + return this.node(start, { + kind: _kinds.Kind.ENUM_TYPE_EXTENSION, + name, + directives, + values, + }); + } + /** + * InputObjectTypeExtension : + * - extend input Name Directives[Const]? InputFieldsDefinition + * - extend input Name Directives[Const] + */ + parseInputObjectTypeExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('input'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const fields = this.parseInputFieldsDefinition(); -/***/ }), + if (directives.length === 0 && fields.length === 0) { + throw this.unexpected(); + } -/***/ 4797: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return this.node(start, { + kind: _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION, + name, + directives, + fields, + }); + } + /** + * ``` + * DirectiveDefinition : + * - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations + * ``` + */ -"use strict"; + parseDirectiveDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('directive'); + this.expectToken(_tokenKind.TokenKind.AT); + const name = this.parseName(); + const args = this.parseArgumentDefs(); + const repeatable = this.expectOptionalKeyword('repeatable'); + this.expectKeyword('on'); + const locations = this.parseDirectiveLocations(); + return this.node(start, { + kind: _kinds.Kind.DIRECTIVE_DEFINITION, + description, + name, + arguments: args, + repeatable, + locations, + }); + } + /** + * DirectiveLocations : + * - `|`? DirectiveLocation + * - DirectiveLocations | DirectiveLocation + */ + parseDirectiveLocations() { + return this.delimitedMany( + _tokenKind.TokenKind.PIPE, + this.parseDirectiveLocation, + ); + } + /* + * DirectiveLocation : + * - ExecutableDirectiveLocation + * - TypeSystemDirectiveLocation + * + * ExecutableDirectiveLocation : one of + * `QUERY` + * `MUTATION` + * `SUBSCRIPTION` + * `FIELD` + * `FRAGMENT_DEFINITION` + * `FRAGMENT_SPREAD` + * `INLINE_FRAGMENT` + * + * TypeSystemDirectiveLocation : one of + * `SCHEMA` + * `SCALAR` + * `OBJECT` + * `FIELD_DEFINITION` + * `ARGUMENT_DEFINITION` + * `INTERFACE` + * `UNION` + * `ENUM` + * `ENUM_VALUE` + * `INPUT_OBJECT` + * `INPUT_FIELD_DEFINITION` + */ -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.GraphQLError = void 0; -exports.formatError = formatError; -exports.printError = printError; + parseDirectiveLocation() { + const start = this._lexer.token; + const name = this.parseName(); -var _isObjectLike = __nccwpck_require__(95865); + if ( + Object.prototype.hasOwnProperty.call( + _directiveLocation.DirectiveLocation, + name.value, + ) + ) { + return name; + } -var _location = __nccwpck_require__(61922); + throw this.unexpected(start); + } // Core parsing utility functions -var _printLocation = __nccwpck_require__(35250); + /** + * Returns a node that, if configured to do so, sets a "loc" field as a + * location object, used to identify the place in the source that created a + * given parsed object. + */ -function toNormalizedOptions(args) { - const firstArg = args[0]; + node(startToken, node) { + if (this._options.noLocation !== true) { + node.loc = new _ast.Location( + startToken, + this._lexer.lastToken, + this._lexer.source, + ); + } - if (firstArg == null || 'kind' in firstArg || 'length' in firstArg) { - return { - nodes: firstArg, - source: args[1], - positions: args[2], - path: args[3], - originalError: args[4], - extensions: args[5], - }; + return node; } - - return firstArg; -} -/** - * A GraphQLError describes an Error found during the parse, validate, or - * execute phases of performing a GraphQL operation. In addition to a message - * and stack trace, it also includes information about the locations in a - * GraphQL document and/or execution result that correspond to the Error. - */ - -class GraphQLError extends Error { /** - * An array of `{ line, column }` locations within the source GraphQL document - * which correspond to this error. - * - * Errors during validation often contain multiple locations, for example to - * point out two things with the same name. Errors during execution include a - * single location, the field which produced the error. - * - * Enumerable, and appears in the result of JSON.stringify(). + * Determines if the next token is of a given kind */ + peek(kind) { + return this._lexer.token.kind === kind; + } /** - * An array describing the JSON-path into the execution response which - * corresponds to this error. Only included for errors during execution. - * - * Enumerable, and appears in the result of JSON.stringify(). + * If the next token is of the given kind, return that token after advancing the lexer. + * Otherwise, do not change the parser state and throw an error. */ - /** - * An array of GraphQL AST Nodes corresponding to this error. - */ + expectToken(kind) { + const token = this._lexer.token; + + if (token.kind === kind) { + this.advanceLexer(); + return token; + } + throw (0, _syntaxError.syntaxError)( + this._lexer.source, + token.start, + `Expected ${getTokenKindDesc(kind)}, found ${getTokenDesc(token)}.`, + ); + } /** - * The source GraphQL document for the first location of this error. - * - * Note that if this Error represents more than one node, the source may not - * represent nodes after the first node. + * If the next token is of the given kind, return "true" after advancing the lexer. + * Otherwise, do not change the parser state and return "false". */ + expectOptionalToken(kind) { + const token = this._lexer.token; + + if (token.kind === kind) { + this.advanceLexer(); + return true; + } + + return false; + } /** - * An array of character offsets within the source GraphQL document - * which correspond to this error. + * If the next token is a given keyword, advance the lexer. + * Otherwise, do not change the parser state and throw an error. */ + expectKeyword(value) { + const token = this._lexer.token; + + if (token.kind === _tokenKind.TokenKind.NAME && token.value === value) { + this.advanceLexer(); + } else { + throw (0, _syntaxError.syntaxError)( + this._lexer.source, + token.start, + `Expected "${value}", found ${getTokenDesc(token)}.`, + ); + } + } /** - * The original error thrown from a field resolver during execution. + * If the next token is a given keyword, return "true" after advancing the lexer. + * Otherwise, do not change the parser state and return "false". */ + expectOptionalKeyword(value) { + const token = this._lexer.token; + + if (token.kind === _tokenKind.TokenKind.NAME && token.value === value) { + this.advanceLexer(); + return true; + } + + return false; + } /** - * Extension fields to add to the formatted error. + * Helper function for creating an error when an unexpected lexed token is encountered. */ + unexpected(atToken) { + const token = + atToken !== null && atToken !== void 0 ? atToken : this._lexer.token; + return (0, _syntaxError.syntaxError)( + this._lexer.source, + token.start, + `Unexpected ${getTokenDesc(token)}.`, + ); + } /** - * @deprecated Please use the `GraphQLErrorOptions` constructor overload instead. + * Returns a possibly empty list of parse nodes, determined by the parseFn. + * This list begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. */ - constructor(message, ...rawArgs) { - var _this$nodes, _nodeLocations$, _ref; - const { nodes, source, positions, path, originalError, extensions } = - toNormalizedOptions(rawArgs); - super(message); - this.name = 'GraphQLError'; - this.path = path !== null && path !== void 0 ? path : undefined; - this.originalError = - originalError !== null && originalError !== void 0 - ? originalError - : undefined; // Compute list of blame nodes. + any(openKind, parseFn, closeKind) { + this.expectToken(openKind); + const nodes = []; - this.nodes = undefinedIfEmpty( - Array.isArray(nodes) ? nodes : nodes ? [nodes] : undefined, - ); - const nodeLocations = undefinedIfEmpty( - (_this$nodes = this.nodes) === null || _this$nodes === void 0 - ? void 0 - : _this$nodes.map((node) => node.loc).filter((loc) => loc != null), - ); // Compute locations in the source for the given nodes/positions. + while (!this.expectOptionalToken(closeKind)) { + nodes.push(parseFn.call(this)); + } - this.source = - source !== null && source !== void 0 - ? source - : nodeLocations === null || nodeLocations === void 0 - ? void 0 - : (_nodeLocations$ = nodeLocations[0]) === null || - _nodeLocations$ === void 0 - ? void 0 - : _nodeLocations$.source; - this.positions = - positions !== null && positions !== void 0 - ? positions - : nodeLocations === null || nodeLocations === void 0 - ? void 0 - : nodeLocations.map((loc) => loc.start); - this.locations = - positions && source - ? positions.map((pos) => (0, _location.getLocation)(source, pos)) - : nodeLocations === null || nodeLocations === void 0 - ? void 0 - : nodeLocations.map((loc) => - (0, _location.getLocation)(loc.source, loc.start), - ); - const originalExtensions = (0, _isObjectLike.isObjectLike)( - originalError === null || originalError === void 0 - ? void 0 - : originalError.extensions, - ) - ? originalError === null || originalError === void 0 - ? void 0 - : originalError.extensions - : undefined; - this.extensions = - (_ref = - extensions !== null && extensions !== void 0 - ? extensions - : originalExtensions) !== null && _ref !== void 0 - ? _ref - : Object.create(null); // Only properties prescribed by the spec should be enumerable. - // Keep the rest as non-enumerable. + return nodes; + } + /** + * Returns a list of parse nodes, determined by the parseFn. + * It can be empty only if open token is missing otherwise it will always return non-empty list + * that begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. + */ - Object.defineProperties(this, { - message: { - writable: true, - enumerable: true, - }, - name: { - enumerable: false, - }, - nodes: { - enumerable: false, - }, - source: { - enumerable: false, - }, - positions: { - enumerable: false, - }, - originalError: { - enumerable: false, - }, - }); // Include (non-enumerable) stack trace. + optionalMany(openKind, parseFn, closeKind) { + if (this.expectOptionalToken(openKind)) { + const nodes = []; - /* c8 ignore start */ - // FIXME: https://github.com/graphql/graphql-js/issues/2317 + do { + nodes.push(parseFn.call(this)); + } while (!this.expectOptionalToken(closeKind)); - if ( - originalError !== null && - originalError !== void 0 && - originalError.stack - ) { - Object.defineProperty(this, 'stack', { - value: originalError.stack, - writable: true, - configurable: true, - }); - } else if (Error.captureStackTrace) { - Error.captureStackTrace(this, GraphQLError); - } else { - Object.defineProperty(this, 'stack', { - value: Error().stack, - writable: true, - configurable: true, - }); + return nodes; } - /* c8 ignore stop */ - } - get [Symbol.toStringTag]() { - return 'GraphQLError'; + return []; } + /** + * Returns a non-empty list of parse nodes, determined by the parseFn. + * This list begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. + */ - toString() { - let output = this.message; + many(openKind, parseFn, closeKind) { + this.expectToken(openKind); + const nodes = []; - if (this.nodes) { - for (const node of this.nodes) { - if (node.loc) { - output += '\n\n' + (0, _printLocation.printLocation)(node.loc); - } - } - } else if (this.source && this.locations) { - for (const location of this.locations) { - output += - '\n\n' + - (0, _printLocation.printSourceLocation)(this.source, location); - } - } + do { + nodes.push(parseFn.call(this)); + } while (!this.expectOptionalToken(closeKind)); - return output; + return nodes; } + /** + * Returns a non-empty list of parse nodes, determined by the parseFn. + * This list may begin with a lex token of delimiterKind followed by items separated by lex tokens of tokenKind. + * Advances the parser to the next lex token after last item in the list. + */ - toJSON() { - const formattedError = { - message: this.message, - }; + delimitedMany(delimiterKind, parseFn) { + this.expectOptionalToken(delimiterKind); + const nodes = []; - if (this.locations != null) { - formattedError.locations = this.locations; - } + do { + nodes.push(parseFn.call(this)); + } while (this.expectOptionalToken(delimiterKind)); - if (this.path != null) { - formattedError.path = this.path; - } + return nodes; + } - if (this.extensions != null && Object.keys(this.extensions).length > 0) { - formattedError.extensions = this.extensions; - } + advanceLexer() { + const { maxTokens } = this._options; - return formattedError; - } -} + const token = this._lexer.advance(); -exports.GraphQLError = GraphQLError; + if (token.kind !== _tokenKind.TokenKind.EOF) { + ++this._tokenCounter; -function undefinedIfEmpty(array) { - return array === undefined || array.length === 0 ? undefined : array; + if (maxTokens !== undefined && this._tokenCounter > maxTokens) { + throw (0, _syntaxError.syntaxError)( + this._lexer.source, + token.start, + `Document contains more that ${maxTokens} tokens. Parsing aborted.`, + ); + } + } + } } /** - * See: https://spec.graphql.org/draft/#sec-Errors + * A helper function to describe a token as a string for debugging. */ -/** - * Prints a GraphQLError to a string, representing useful location information - * about the error's position in the source. - * - * @deprecated Please use `error.toString` instead. Will be removed in v17 - */ -function printError(error) { - return error.toString(); +exports.Parser = Parser; + +function getTokenDesc(token) { + const value = token.value; + return getTokenKindDesc(token.kind) + (value != null ? ` "${value}"` : ''); } /** - * Given a GraphQLError, format it according to the rules described by the - * Response Format, Errors section of the GraphQL Specification. - * - * @deprecated Please use `error.toJSON` instead. Will be removed in v17 + * A helper function to describe a token kind as a string for debugging. */ -function formatError(error) { - return error.toJSON(); +function getTokenKindDesc(kind) { + return (0, _lexer.isPunctuatorTokenKind)(kind) ? `"${kind}"` : kind; } /***/ }), -/***/ 50578: +/***/ 20535: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -275914,47 +274914,115 @@ function formatError(error) { Object.defineProperty(exports, "__esModule", ({ value: true, })); -Object.defineProperty(exports, "GraphQLError", ({ - enumerable: true, - get: function () { - return _GraphQLError.GraphQLError; - }, -})); -Object.defineProperty(exports, "formatError", ({ - enumerable: true, - get: function () { - return _GraphQLError.formatError; - }, -})); -Object.defineProperty(exports, "locatedError", ({ - enumerable: true, - get: function () { - return _locatedError.locatedError; - }, -})); -Object.defineProperty(exports, "printError", ({ - enumerable: true, - get: function () { - return _GraphQLError.printError; - }, -})); -Object.defineProperty(exports, "syntaxError", ({ - enumerable: true, - get: function () { - return _syntaxError.syntaxError; - }, -})); +exports.isConstValueNode = isConstValueNode; +exports.isDefinitionNode = isDefinitionNode; +exports.isExecutableDefinitionNode = isExecutableDefinitionNode; +exports.isSelectionNode = isSelectionNode; +exports.isTypeDefinitionNode = isTypeDefinitionNode; +exports.isTypeExtensionNode = isTypeExtensionNode; +exports.isTypeNode = isTypeNode; +exports.isTypeSystemDefinitionNode = isTypeSystemDefinitionNode; +exports.isTypeSystemExtensionNode = isTypeSystemExtensionNode; +exports.isValueNode = isValueNode; -var _GraphQLError = __nccwpck_require__(4797); +var _kinds = __nccwpck_require__(11927); -var _syntaxError = __nccwpck_require__(52295); +function isDefinitionNode(node) { + return ( + isExecutableDefinitionNode(node) || + isTypeSystemDefinitionNode(node) || + isTypeSystemExtensionNode(node) + ); +} -var _locatedError = __nccwpck_require__(16842); +function isExecutableDefinitionNode(node) { + return ( + node.kind === _kinds.Kind.OPERATION_DEFINITION || + node.kind === _kinds.Kind.FRAGMENT_DEFINITION + ); +} + +function isSelectionNode(node) { + return ( + node.kind === _kinds.Kind.FIELD || + node.kind === _kinds.Kind.FRAGMENT_SPREAD || + node.kind === _kinds.Kind.INLINE_FRAGMENT + ); +} + +function isValueNode(node) { + return ( + node.kind === _kinds.Kind.VARIABLE || + node.kind === _kinds.Kind.INT || + node.kind === _kinds.Kind.FLOAT || + node.kind === _kinds.Kind.STRING || + node.kind === _kinds.Kind.BOOLEAN || + node.kind === _kinds.Kind.NULL || + node.kind === _kinds.Kind.ENUM || + node.kind === _kinds.Kind.LIST || + node.kind === _kinds.Kind.OBJECT + ); +} + +function isConstValueNode(node) { + return ( + isValueNode(node) && + (node.kind === _kinds.Kind.LIST + ? node.values.some(isConstValueNode) + : node.kind === _kinds.Kind.OBJECT + ? node.fields.some((field) => isConstValueNode(field.value)) + : node.kind !== _kinds.Kind.VARIABLE) + ); +} + +function isTypeNode(node) { + return ( + node.kind === _kinds.Kind.NAMED_TYPE || + node.kind === _kinds.Kind.LIST_TYPE || + node.kind === _kinds.Kind.NON_NULL_TYPE + ); +} + +function isTypeSystemDefinitionNode(node) { + return ( + node.kind === _kinds.Kind.SCHEMA_DEFINITION || + isTypeDefinitionNode(node) || + node.kind === _kinds.Kind.DIRECTIVE_DEFINITION + ); +} + +function isTypeDefinitionNode(node) { + return ( + node.kind === _kinds.Kind.SCALAR_TYPE_DEFINITION || + node.kind === _kinds.Kind.OBJECT_TYPE_DEFINITION || + node.kind === _kinds.Kind.INTERFACE_TYPE_DEFINITION || + node.kind === _kinds.Kind.UNION_TYPE_DEFINITION || + node.kind === _kinds.Kind.ENUM_TYPE_DEFINITION || + node.kind === _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION + ); +} + +function isTypeSystemExtensionNode(node) { + return ( + node.kind === _kinds.Kind.SCHEMA_EXTENSION || isTypeExtensionNode(node) + ); +} + +function isTypeExtensionNode(node) { + return ( + node.kind === _kinds.Kind.SCALAR_TYPE_EXTENSION || + node.kind === _kinds.Kind.OBJECT_TYPE_EXTENSION || + node.kind === _kinds.Kind.INTERFACE_TYPE_EXTENSION || + node.kind === _kinds.Kind.UNION_TYPE_EXTENSION || + node.kind === _kinds.Kind.ENUM_TYPE_EXTENSION || + node.kind === _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION + ); +} /***/ }), -/***/ 16842: +/***/ 35250: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -275963,47 +275031,81 @@ var _locatedError = __nccwpck_require__(16842); Object.defineProperty(exports, "__esModule", ({ value: true, })); -exports.locatedError = locatedError; - -var _toError = __nccwpck_require__(15472); +exports.printLocation = printLocation; +exports.printSourceLocation = printSourceLocation; -var _GraphQLError = __nccwpck_require__(4797); +var _location = __nccwpck_require__(61922); /** - * Given an arbitrary value, presumably thrown while attempting to execute a - * GraphQL operation, produce a new GraphQLError aware of the location in the - * document responsible for the original Error. + * Render a helpful description of the location in the GraphQL Source document. + */ +function printLocation(location) { + return printSourceLocation( + location.source, + (0, _location.getLocation)(location.source, location.start), + ); +} +/** + * Render a helpful description of the location in the GraphQL Source document. */ -function locatedError(rawOriginalError, nodes, path) { - var _nodes; - const originalError = (0, _toError.toError)(rawOriginalError); // Note: this uses a brand-check to support GraphQL errors originating from other contexts. +function printSourceLocation(source, sourceLocation) { + const firstLineColumnOffset = source.locationOffset.column - 1; + const body = ''.padStart(firstLineColumnOffset) + source.body; + const lineIndex = sourceLocation.line - 1; + const lineOffset = source.locationOffset.line - 1; + const lineNum = sourceLocation.line + lineOffset; + const columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0; + const columnNum = sourceLocation.column + columnOffset; + const locationStr = `${source.name}:${lineNum}:${columnNum}\n`; + const lines = body.split(/\r\n|[\n\r]/g); + const locationLine = lines[lineIndex]; // Special case for minified documents - if (isLocatedGraphQLError(originalError)) { - return originalError; + if (locationLine.length > 120) { + const subLineIndex = Math.floor(columnNum / 80); + const subLineColumnNum = columnNum % 80; + const subLines = []; + + for (let i = 0; i < locationLine.length; i += 80) { + subLines.push(locationLine.slice(i, i + 80)); + } + + return ( + locationStr + + printPrefixedLines([ + [`${lineNum} |`, subLines[0]], + ...subLines.slice(1, subLineIndex + 1).map((subLine) => ['|', subLine]), + ['|', '^'.padStart(subLineColumnNum)], + ['|', subLines[subLineIndex + 1]], + ]) + ); } - return new _GraphQLError.GraphQLError(originalError.message, { - nodes: - (_nodes = originalError.nodes) !== null && _nodes !== void 0 - ? _nodes - : nodes, - source: originalError.source, - positions: originalError.positions, - path, - originalError, - }); + return ( + locationStr + + printPrefixedLines([ + // Lines specified like this: ["prefix", "string"], + [`${lineNum - 1} |`, lines[lineIndex - 1]], + [`${lineNum} |`, locationLine], + ['|', '^'.padStart(columnNum)], + [`${lineNum + 1} |`, lines[lineIndex + 1]], + ]) + ); } -function isLocatedGraphQLError(error) { - return Array.isArray(error.path); +function printPrefixedLines(lines) { + const existingLines = lines.filter(([_, line]) => line !== undefined); + const padLen = Math.max(...existingLines.map(([prefix]) => prefix.length)); + return existingLines + .map(([prefix, line]) => prefix.padStart(padLen) + (line ? ' ' + line : '')) + .join('\n'); } /***/ }), -/***/ 52295: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 86011: +/***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -276011,25 +275113,189 @@ function isLocatedGraphQLError(error) { Object.defineProperty(exports, "__esModule", ({ value: true, })); -exports.syntaxError = syntaxError; - -var _GraphQLError = __nccwpck_require__(4797); +exports.printString = printString; /** - * Produces a GraphQLError representing a syntax error, containing useful - * descriptive information about the syntax error's position in the source. + * Prints a string as a GraphQL StringValue literal. Replaces control characters + * and excluded characters (" U+0022 and \\ U+005C) with escape sequences. */ -function syntaxError(source, position, description) { - return new _GraphQLError.GraphQLError(`Syntax Error: ${description}`, { - source, - positions: [position], - }); -} +function printString(str) { + return `"${str.replace(escapedRegExp, escapedReplacer)}"`; +} // eslint-disable-next-line no-control-regex + +const escapedRegExp = /[\x00-\x1f\x22\x5c\x7f-\x9f]/g; + +function escapedReplacer(str) { + return escapeSequences[str.charCodeAt(0)]; +} // prettier-ignore + +const escapeSequences = [ + '\\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', + '', + '', + '\\"', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', // 2F + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', // 3F + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', // 4F + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '\\\\', + '', + '', + '', // 5F + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', // 6F + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '\\u007F', + '\\u0080', + '\\u0081', + '\\u0082', + '\\u0083', + '\\u0084', + '\\u0085', + '\\u0086', + '\\u0087', + '\\u0088', + '\\u0089', + '\\u008A', + '\\u008B', + '\\u008C', + '\\u008D', + '\\u008E', + '\\u008F', + '\\u0090', + '\\u0091', + '\\u0092', + '\\u0093', + '\\u0094', + '\\u0095', + '\\u0096', + '\\u0097', + '\\u0098', + '\\u0099', + '\\u009A', + '\\u009B', + '\\u009C', + '\\u009D', + '\\u009E', + '\\u009F', +]; /***/ }), -/***/ 49942: +/***/ 68203: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -276038,236 +275304,431 @@ function syntaxError(source, position, description) { Object.defineProperty(exports, "__esModule", ({ value: true, })); -exports.collectFields = collectFields; -exports.collectSubfields = collectSubfields; - -var _kinds = __nccwpck_require__(11927); - -var _definition = __nccwpck_require__(32150); +exports.print = print; -var _directives = __nccwpck_require__(83614); +var _blockString = __nccwpck_require__(52671); -var _typeFromAST = __nccwpck_require__(27664); +var _printString = __nccwpck_require__(86011); -var _values = __nccwpck_require__(94834); +var _visitor = __nccwpck_require__(5678); /** - * Given a selectionSet, collects all of the fields and returns them. - * - * CollectFields requires the "runtime type" of an object. For a field that - * returns an Interface or Union type, the "runtime type" will be the actual - * object type returned by that field. - * - * @internal + * Converts an AST into a string, using one set of reasonable + * formatting rules. */ -function collectFields( - schema, - fragments, - variableValues, - runtimeType, - selectionSet, -) { - const fields = new Map(); - collectFieldsImpl( - schema, - fragments, - variableValues, - runtimeType, - selectionSet, - fields, - new Set(), - ); - return fields; +function print(ast) { + return (0, _visitor.visit)(ast, printDocASTReducer); } + +const MAX_LINE_LENGTH = 80; +const printDocASTReducer = { + Name: { + leave: (node) => node.value, + }, + Variable: { + leave: (node) => '$' + node.name, + }, + // Document + Document: { + leave: (node) => join(node.definitions, '\n\n'), + }, + OperationDefinition: { + leave(node) { + const varDefs = wrap('(', join(node.variableDefinitions, ', '), ')'); + const prefix = join( + [ + node.operation, + join([node.name, varDefs]), + join(node.directives, ' '), + ], + ' ', + ); // Anonymous queries with no directives or variable definitions can use + // the query short form. + + return (prefix === 'query' ? '' : prefix + ' ') + node.selectionSet; + }, + }, + VariableDefinition: { + leave: ({ variable, type, defaultValue, directives }) => + variable + + ': ' + + type + + wrap(' = ', defaultValue) + + wrap(' ', join(directives, ' ')), + }, + SelectionSet: { + leave: ({ selections }) => block(selections), + }, + Field: { + leave({ alias, name, arguments: args, directives, selectionSet }) { + const prefix = wrap('', alias, ': ') + name; + let argsLine = prefix + wrap('(', join(args, ', '), ')'); + + if (argsLine.length > MAX_LINE_LENGTH) { + argsLine = prefix + wrap('(\n', indent(join(args, '\n')), '\n)'); + } + + return join([argsLine, join(directives, ' '), selectionSet], ' '); + }, + }, + Argument: { + leave: ({ name, value }) => name + ': ' + value, + }, + // Fragments + FragmentSpread: { + leave: ({ name, directives }) => + '...' + name + wrap(' ', join(directives, ' ')), + }, + InlineFragment: { + leave: ({ typeCondition, directives, selectionSet }) => + join( + [ + '...', + wrap('on ', typeCondition), + join(directives, ' '), + selectionSet, + ], + ' ', + ), + }, + FragmentDefinition: { + leave: ( + { name, typeCondition, variableDefinitions, directives, selectionSet }, // Note: fragment variable definitions are experimental and may be changed + ) => + // or removed in the future. + `fragment ${name}${wrap('(', join(variableDefinitions, ', '), ')')} ` + + `on ${typeCondition} ${wrap('', join(directives, ' '), ' ')}` + + selectionSet, + }, + // Value + IntValue: { + leave: ({ value }) => value, + }, + FloatValue: { + leave: ({ value }) => value, + }, + StringValue: { + leave: ({ value, block: isBlockString }) => + isBlockString + ? (0, _blockString.printBlockString)(value) + : (0, _printString.printString)(value), + }, + BooleanValue: { + leave: ({ value }) => (value ? 'true' : 'false'), + }, + NullValue: { + leave: () => 'null', + }, + EnumValue: { + leave: ({ value }) => value, + }, + ListValue: { + leave: ({ values }) => '[' + join(values, ', ') + ']', + }, + ObjectValue: { + leave: ({ fields }) => '{' + join(fields, ', ') + '}', + }, + ObjectField: { + leave: ({ name, value }) => name + ': ' + value, + }, + // Directive + Directive: { + leave: ({ name, arguments: args }) => + '@' + name + wrap('(', join(args, ', '), ')'), + }, + // Type + NamedType: { + leave: ({ name }) => name, + }, + ListType: { + leave: ({ type }) => '[' + type + ']', + }, + NonNullType: { + leave: ({ type }) => type + '!', + }, + // Type System Definitions + SchemaDefinition: { + leave: ({ description, directives, operationTypes }) => + wrap('', description, '\n') + + join(['schema', join(directives, ' '), block(operationTypes)], ' '), + }, + OperationTypeDefinition: { + leave: ({ operation, type }) => operation + ': ' + type, + }, + ScalarTypeDefinition: { + leave: ({ description, name, directives }) => + wrap('', description, '\n') + + join(['scalar', name, join(directives, ' ')], ' '), + }, + ObjectTypeDefinition: { + leave: ({ description, name, interfaces, directives, fields }) => + wrap('', description, '\n') + + join( + [ + 'type', + name, + wrap('implements ', join(interfaces, ' & ')), + join(directives, ' '), + block(fields), + ], + ' ', + ), + }, + FieldDefinition: { + leave: ({ description, name, arguments: args, type, directives }) => + wrap('', description, '\n') + + name + + (hasMultilineItems(args) + ? wrap('(\n', indent(join(args, '\n')), '\n)') + : wrap('(', join(args, ', '), ')')) + + ': ' + + type + + wrap(' ', join(directives, ' ')), + }, + InputValueDefinition: { + leave: ({ description, name, type, defaultValue, directives }) => + wrap('', description, '\n') + + join( + [name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')], + ' ', + ), + }, + InterfaceTypeDefinition: { + leave: ({ description, name, interfaces, directives, fields }) => + wrap('', description, '\n') + + join( + [ + 'interface', + name, + wrap('implements ', join(interfaces, ' & ')), + join(directives, ' '), + block(fields), + ], + ' ', + ), + }, + UnionTypeDefinition: { + leave: ({ description, name, directives, types }) => + wrap('', description, '\n') + + join( + ['union', name, join(directives, ' '), wrap('= ', join(types, ' | '))], + ' ', + ), + }, + EnumTypeDefinition: { + leave: ({ description, name, directives, values }) => + wrap('', description, '\n') + + join(['enum', name, join(directives, ' '), block(values)], ' '), + }, + EnumValueDefinition: { + leave: ({ description, name, directives }) => + wrap('', description, '\n') + join([name, join(directives, ' ')], ' '), + }, + InputObjectTypeDefinition: { + leave: ({ description, name, directives, fields }) => + wrap('', description, '\n') + + join(['input', name, join(directives, ' '), block(fields)], ' '), + }, + DirectiveDefinition: { + leave: ({ description, name, arguments: args, repeatable, locations }) => + wrap('', description, '\n') + + 'directive @' + + name + + (hasMultilineItems(args) + ? wrap('(\n', indent(join(args, '\n')), '\n)') + : wrap('(', join(args, ', '), ')')) + + (repeatable ? ' repeatable' : '') + + ' on ' + + join(locations, ' | '), + }, + SchemaExtension: { + leave: ({ directives, operationTypes }) => + join( + ['extend schema', join(directives, ' '), block(operationTypes)], + ' ', + ), + }, + ScalarTypeExtension: { + leave: ({ name, directives }) => + join(['extend scalar', name, join(directives, ' ')], ' '), + }, + ObjectTypeExtension: { + leave: ({ name, interfaces, directives, fields }) => + join( + [ + 'extend type', + name, + wrap('implements ', join(interfaces, ' & ')), + join(directives, ' '), + block(fields), + ], + ' ', + ), + }, + InterfaceTypeExtension: { + leave: ({ name, interfaces, directives, fields }) => + join( + [ + 'extend interface', + name, + wrap('implements ', join(interfaces, ' & ')), + join(directives, ' '), + block(fields), + ], + ' ', + ), + }, + UnionTypeExtension: { + leave: ({ name, directives, types }) => + join( + [ + 'extend union', + name, + join(directives, ' '), + wrap('= ', join(types, ' | ')), + ], + ' ', + ), + }, + EnumTypeExtension: { + leave: ({ name, directives, values }) => + join(['extend enum', name, join(directives, ' '), block(values)], ' '), + }, + InputObjectTypeExtension: { + leave: ({ name, directives, fields }) => + join(['extend input', name, join(directives, ' '), block(fields)], ' '), + }, +}; /** - * Given an array of field nodes, collects all of the subfields of the passed - * in fields, and returns them at the end. - * - * CollectSubFields requires the "return type" of an object. For a field that - * returns an Interface or Union type, the "return type" will be the actual - * object type returned by that field. - * - * @internal + * Given maybeArray, print an empty string if it is null or empty, otherwise + * print all items together separated by separator if provided */ -function collectSubfields( - schema, - fragments, - variableValues, - returnType, - fieldNodes, -) { - const subFieldNodes = new Map(); - const visitedFragmentNames = new Set(); - - for (const node of fieldNodes) { - if (node.selectionSet) { - collectFieldsImpl( - schema, - fragments, - variableValues, - returnType, - node.selectionSet, - subFieldNodes, - visitedFragmentNames, - ); - } - } +function join(maybeArray, separator = '') { + var _maybeArray$filter$jo; - return subFieldNodes; + return (_maybeArray$filter$jo = + maybeArray === null || maybeArray === void 0 + ? void 0 + : maybeArray.filter((x) => x).join(separator)) !== null && + _maybeArray$filter$jo !== void 0 + ? _maybeArray$filter$jo + : ''; } +/** + * Given array, print each item on its own line, wrapped in an indented `{ }` block. + */ -function collectFieldsImpl( - schema, - fragments, - variableValues, - runtimeType, - selectionSet, - fields, - visitedFragmentNames, -) { - for (const selection of selectionSet.selections) { - switch (selection.kind) { - case _kinds.Kind.FIELD: { - if (!shouldIncludeNode(variableValues, selection)) { - continue; - } +function block(array) { + return wrap('{\n', indent(join(array, '\n')), '\n}'); +} +/** + * If maybeString is not null or empty, then wrap with start and end, otherwise print an empty string. + */ - const name = getFieldEntryKey(selection); - const fieldList = fields.get(name); +function wrap(start, maybeString, end = '') { + return maybeString != null && maybeString !== '' + ? start + maybeString + end + : ''; +} - if (fieldList !== undefined) { - fieldList.push(selection); - } else { - fields.set(name, [selection]); - } +function indent(str) { + return wrap(' ', str.replace(/\n/g, '\n ')); +} - break; - } +function hasMultilineItems(maybeArray) { + var _maybeArray$some; - case _kinds.Kind.INLINE_FRAGMENT: { - if ( - !shouldIncludeNode(variableValues, selection) || - !doesFragmentConditionMatch(schema, selection, runtimeType) - ) { - continue; - } + // FIXME: https://github.com/graphql/graphql-js/issues/2203 - collectFieldsImpl( - schema, - fragments, - variableValues, - runtimeType, - selection.selectionSet, - fields, - visitedFragmentNames, - ); - break; - } + /* c8 ignore next */ + return (_maybeArray$some = + maybeArray === null || maybeArray === void 0 + ? void 0 + : maybeArray.some((str) => str.includes('\n'))) !== null && + _maybeArray$some !== void 0 + ? _maybeArray$some + : false; +} - case _kinds.Kind.FRAGMENT_SPREAD: { - const fragName = selection.name.value; - if ( - visitedFragmentNames.has(fragName) || - !shouldIncludeNode(variableValues, selection) - ) { - continue; - } +/***/ }), - visitedFragmentNames.add(fragName); - const fragment = fragments[fragName]; +/***/ 65521: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if ( - !fragment || - !doesFragmentConditionMatch(schema, fragment, runtimeType) - ) { - continue; - } +"use strict"; - collectFieldsImpl( - schema, - fragments, - variableValues, - runtimeType, - fragment.selectionSet, - fields, - visitedFragmentNames, - ); - break; - } - } - } -} -/** - * Determines if a field should be included based on the `@include` and `@skip` - * directives, where `@skip` has higher precedence than `@include`. - */ -function shouldIncludeNode(variableValues, node) { - const skip = (0, _values.getDirectiveValues)( - _directives.GraphQLSkipDirective, - node, - variableValues, - ); +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.Source = void 0; +exports.isSource = isSource; - if ((skip === null || skip === void 0 ? void 0 : skip.if) === true) { - return false; - } +var _devAssert = __nccwpck_require__(46514); - const include = (0, _values.getDirectiveValues)( - _directives.GraphQLIncludeDirective, - node, - variableValues, - ); +var _inspect = __nccwpck_require__(10102); - if ( - (include === null || include === void 0 ? void 0 : include.if) === false - ) { - return false; - } +var _instanceOf = __nccwpck_require__(93481); - return true; -} /** - * Determines if a fragment is applicable to the given type. + * A representation of source input to GraphQL. The `name` and `locationOffset` parameters are + * optional, but they are useful for clients who store GraphQL documents in source files. + * For example, if the GraphQL input starts at line 40 in a file named `Foo.graphql`, it might + * be useful for `name` to be `"Foo.graphql"` and location to be `{ line: 40, column: 1 }`. + * The `line` and `column` properties in `locationOffset` are 1-indexed. */ - -function doesFragmentConditionMatch(schema, fragment, type) { - const typeConditionNode = fragment.typeCondition; - - if (!typeConditionNode) { - return true; - } - - const conditionalType = (0, _typeFromAST.typeFromAST)( - schema, - typeConditionNode, - ); - - if (conditionalType === type) { - return true; +class Source { + constructor( + body, + name = 'GraphQL request', + locationOffset = { + line: 1, + column: 1, + }, + ) { + typeof body === 'string' || + (0, _devAssert.devAssert)( + false, + `Body must be a string. Received: ${(0, _inspect.inspect)(body)}.`, + ); + this.body = body; + this.name = name; + this.locationOffset = locationOffset; + this.locationOffset.line > 0 || + (0, _devAssert.devAssert)( + false, + 'line in locationOffset is 1-indexed and must be positive.', + ); + this.locationOffset.column > 0 || + (0, _devAssert.devAssert)( + false, + 'column in locationOffset is 1-indexed and must be positive.', + ); } - if ((0, _definition.isAbstractType)(conditionalType)) { - return schema.isSubType(conditionalType, type); + get [Symbol.toStringTag]() { + return 'Source'; } - - return false; } /** - * Implements the logic to compute the key of a given field's entry + * Test if the given value is a Source object. + * + * @internal */ -function getFieldEntryKey(node) { - return node.alias ? node.alias.value : node.name.value; +exports.Source = Source; + +function isSource(source) { + return (0, _instanceOf.instanceOf)(source, Source); } /***/ }), -/***/ 83677: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 91565: +/***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -276275,1768 +275736,1868 @@ function getFieldEntryKey(node) { Object.defineProperty(exports, "__esModule", ({ value: true, })); -exports.assertValidExecutionArguments = assertValidExecutionArguments; -exports.buildExecutionContext = buildExecutionContext; -exports.buildResolveInfo = buildResolveInfo; -exports.defaultTypeResolver = exports.defaultFieldResolver = void 0; -exports.execute = execute; -exports.executeSync = executeSync; -exports.getFieldDef = getFieldDef; - -var _devAssert = __nccwpck_require__(46514); - -var _inspect = __nccwpck_require__(10102); +exports.TokenKind = void 0; -var _invariant = __nccwpck_require__(28847); +/** + * An exported enum describing the different kinds of tokens that the + * lexer emits. + */ +var TokenKind; +exports.TokenKind = TokenKind; -var _isIterableObject = __nccwpck_require__(81258); +(function (TokenKind) { + TokenKind['SOF'] = ''; + TokenKind['EOF'] = ''; + TokenKind['BANG'] = '!'; + TokenKind['DOLLAR'] = '$'; + TokenKind['AMP'] = '&'; + TokenKind['PAREN_L'] = '('; + TokenKind['PAREN_R'] = ')'; + TokenKind['SPREAD'] = '...'; + TokenKind['COLON'] = ':'; + TokenKind['EQUALS'] = '='; + TokenKind['AT'] = '@'; + TokenKind['BRACKET_L'] = '['; + TokenKind['BRACKET_R'] = ']'; + TokenKind['BRACE_L'] = '{'; + TokenKind['PIPE'] = '|'; + TokenKind['BRACE_R'] = '}'; + TokenKind['NAME'] = 'Name'; + TokenKind['INT'] = 'Int'; + TokenKind['FLOAT'] = 'Float'; + TokenKind['STRING'] = 'String'; + TokenKind['BLOCK_STRING'] = 'BlockString'; + TokenKind['COMMENT'] = 'Comment'; +})(TokenKind || (exports.TokenKind = TokenKind = {})); +/** + * The enum type representing the token kinds values. + * + * @deprecated Please use `TokenKind`. Will be remove in v17. + */ -var _isObjectLike = __nccwpck_require__(95865); -var _isPromise = __nccwpck_require__(93910); +/***/ }), -var _memoize = __nccwpck_require__(64217); +/***/ 5678: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var _Path = __nccwpck_require__(11262); +"use strict"; -var _promiseForObject = __nccwpck_require__(46804); -var _promiseReduce = __nccwpck_require__(63925); +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.BREAK = void 0; +exports.getEnterLeaveForKind = getEnterLeaveForKind; +exports.getVisitFn = getVisitFn; +exports.visit = visit; +exports.visitInParallel = visitInParallel; -var _GraphQLError = __nccwpck_require__(4797); +var _devAssert = __nccwpck_require__(46514); -var _locatedError = __nccwpck_require__(16842); +var _inspect = __nccwpck_require__(10102); var _ast = __nccwpck_require__(45494); var _kinds = __nccwpck_require__(11927); -var _definition = __nccwpck_require__(32150); - -var _introspection = __nccwpck_require__(28344); - -var _validate = __nccwpck_require__(22430); - -var _collectFields = __nccwpck_require__(49942); - -var _values = __nccwpck_require__(94834); - -/** - * A memoized collection of relevant subfields with regard to the return - * type. Memoizing ensures the subfields are not repeatedly calculated, which - * saves overhead when resolving lists of values. - */ -const collectSubfields = (0, _memoize.memoize3)( - (exeContext, returnType, fieldNodes) => - (0, _collectFields.collectSubfields)( - exeContext.schema, - exeContext.fragments, - exeContext.variableValues, - returnType, - fieldNodes, - ), -); +const BREAK = Object.freeze({}); /** - * Terminology + * visit() will walk through an AST using a depth-first traversal, calling + * the visitor's enter function at each node in the traversal, and calling the + * leave function after visiting that node and all of its child nodes. * - * "Definitions" are the generic name for top-level statements in the document. - * Examples of this include: - * 1) Operations (such as a query) - * 2) Fragments + * By returning different values from the enter and leave functions, the + * behavior of the visitor can be altered, including skipping over a sub-tree of + * the AST (by returning false), editing the AST by returning a value or null + * to remove the value, or to stop the whole traversal by returning BREAK. * - * "Operations" are a generic name for requests in the document. - * Examples of this include: - * 1) query, - * 2) mutation + * When using visit() to edit an AST, the original AST will not be modified, and + * a new version of the AST with the changes applied will be returned from the + * visit function. * - * "Selections" are the definitions that can appear legally and at - * single level of the query. These include: - * 1) field references e.g `a` - * 2) fragment "spreads" e.g. `...c` - * 3) inline fragment "spreads" e.g. `...on Type { a }` - */ - -/** - * Data that must be available at all points during query execution. + * ```ts + * const editedAST = visit(ast, { + * enter(node, key, parent, path, ancestors) { + * // @return + * // undefined: no action + * // false: skip visiting this node + * // visitor.BREAK: stop visiting altogether + * // null: delete this node + * // any value: replace this node with the returned value + * }, + * leave(node, key, parent, path, ancestors) { + * // @return + * // undefined: no action + * // false: no action + * // visitor.BREAK: stop visiting altogether + * // null: delete this node + * // any value: replace this node with the returned value + * } + * }); + * ``` * - * Namely, schema of the type system that is currently executing, - * and the fragments defined in the query document - */ - -/** - * Implements the "Executing requests" section of the GraphQL specification. + * Alternatively to providing enter() and leave() functions, a visitor can + * instead provide functions named the same as the kinds of AST nodes, or + * enter/leave visitors at a named key, leading to three permutations of the + * visitor API: + * + * 1) Named visitors triggered when entering a node of a specific kind. + * + * ```ts + * visit(ast, { + * Kind(node) { + * // enter the "Kind" node + * } + * }) + * ``` + * + * 2) Named visitors that trigger upon entering and leaving a node of a specific kind. + * + * ```ts + * visit(ast, { + * Kind: { + * enter(node) { + * // enter the "Kind" node + * } + * leave(node) { + * // leave the "Kind" node + * } + * } + * }) + * ``` * - * Returns either a synchronous ExecutionResult (if all encountered resolvers - * are synchronous), or a Promise of an ExecutionResult that will eventually be - * resolved and never rejected. + * 3) Generic visitors that trigger upon entering and leaving any node. * - * If the arguments to this function do not result in a legal execution context, - * a GraphQLError will be thrown immediately explaining the invalid input. + * ```ts + * visit(ast, { + * enter(node) { + * // enter any node + * }, + * leave(node) { + * // leave any node + * } + * }) + * ``` */ -function execute(args) { - // Temporary for v15 to v16 migration. Remove in v17 - arguments.length < 2 || - (0, _devAssert.devAssert)( - false, - 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.', - ); - const { schema, document, variableValues, rootValue } = args; // If arguments are missing or incorrect, throw an error. - assertValidExecutionArguments(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments, - // a "Response" with only errors is returned. +exports.BREAK = BREAK; - const exeContext = buildExecutionContext(args); // Return early errors if execution context failed. +function visit(root, visitor, visitorKeys = _ast.QueryDocumentKeys) { + const enterLeaveMap = new Map(); - if (!('schema' in exeContext)) { - return { - errors: exeContext, - }; - } // Return a Promise that will eventually resolve to the data described by - // The "Response" section of the GraphQL specification. - // - // If errors are encountered while executing a GraphQL field, only that - // field and its descendants will be omitted, and sibling fields will still - // be executed. An execution which encounters errors will still result in a - // resolved Promise. - // - // Errors from sub-fields of a NonNull type may propagate to the top level, - // at which point we still log the error and null the parent field, which - // in this case is the entire response. + for (const kind of Object.values(_kinds.Kind)) { + enterLeaveMap.set(kind, getEnterLeaveForKind(visitor, kind)); + } + /* eslint-disable no-undef-init */ - try { - const { operation } = exeContext; - const result = executeOperation(exeContext, operation, rootValue); + let stack = undefined; + let inArray = Array.isArray(root); + let keys = [root]; + let index = -1; + let edits = []; + let node = root; + let key = undefined; + let parent = undefined; + const path = []; + const ancestors = []; + /* eslint-enable no-undef-init */ - if ((0, _isPromise.isPromise)(result)) { - return result.then( - (data) => buildResponse(data, exeContext.errors), - (error) => { - exeContext.errors.push(error); - return buildResponse(null, exeContext.errors); - }, - ); - } + do { + index++; + const isLeaving = index === keys.length; + const isEdited = isLeaving && edits.length !== 0; - return buildResponse(result, exeContext.errors); - } catch (error) { - exeContext.errors.push(error); - return buildResponse(null, exeContext.errors); - } -} -/** - * Also implements the "Executing requests" section of the GraphQL specification. - * However, it guarantees to complete synchronously (or throw an error) assuming - * that all field resolvers are also synchronous. - */ + if (isLeaving) { + key = ancestors.length === 0 ? undefined : path[path.length - 1]; + node = parent; + parent = ancestors.pop(); -function executeSync(args) { - const result = execute(args); // Assert that the execution was synchronous. + if (isEdited) { + if (inArray) { + node = node.slice(); + let editOffset = 0; - if ((0, _isPromise.isPromise)(result)) { - throw new Error('GraphQL execution failed to complete synchronously.'); - } + for (const [editKey, editValue] of edits) { + const arrayKey = editKey - editOffset; - return result; -} -/** - * Given a completed execution context and data, build the `{ errors, data }` - * response defined by the "Response" section of the GraphQL specification. - */ + if (editValue === null) { + node.splice(arrayKey, 1); + editOffset++; + } else { + node[arrayKey] = editValue; + } + } + } else { + node = { ...node }; -function buildResponse(data, errors) { - return errors.length === 0 - ? { - data, + for (const [editKey, editValue] of edits) { + node[editKey] = editValue; + } + } } - : { - errors, - data, - }; -} -/** - * Essential assertions before executing to provide developer feedback for - * improper use of the GraphQL library. - * - * @internal - */ - -function assertValidExecutionArguments(schema, document, rawVariableValues) { - document || (0, _devAssert.devAssert)(false, 'Must provide document.'); // If the schema used for execution is invalid, throw an error. - (0, _validate.assertValidSchema)(schema); // Variables, if provided, must be an object. + index = stack.index; + keys = stack.keys; + edits = stack.edits; + inArray = stack.inArray; + stack = stack.prev; + } else if (parent) { + key = inArray ? index : keys[index]; + node = parent[key]; - rawVariableValues == null || - (0, _isObjectLike.isObjectLike)(rawVariableValues) || - (0, _devAssert.devAssert)( - false, - 'Variables must be provided as an Object where each property is a variable value. Perhaps look to see if an unparsed JSON string was provided.', - ); -} -/** - * Constructs a ExecutionContext object from the arguments passed to - * execute, which we will pass throughout the other execution methods. - * - * Throws a GraphQLError if a valid execution context cannot be created. - * - * @internal - */ + if (node === null || node === undefined) { + continue; + } -function buildExecutionContext(args) { - var _definition$name, _operation$variableDe, _options$maxCoercionE; + path.push(key); + } - const { - schema, - document, - rootValue, - contextValue, - variableValues: rawVariableValues, - operationName, - fieldResolver, - typeResolver, - subscribeFieldResolver, - options, - } = args; - let operation; - const fragments = Object.create(null); + let result; - for (const definition of document.definitions) { - switch (definition.kind) { - case _kinds.Kind.OPERATION_DEFINITION: - if (operationName == null) { - if (operation !== undefined) { - return [ - new _GraphQLError.GraphQLError( - 'Must provide operation name if query contains multiple operations.', - ), - ]; - } + if (!Array.isArray(node)) { + var _enterLeaveMap$get, _enterLeaveMap$get2; - operation = definition; - } else if ( - ((_definition$name = definition.name) === null || - _definition$name === void 0 - ? void 0 - : _definition$name.value) === operationName - ) { - operation = definition; - } + (0, _ast.isNode)(node) || + (0, _devAssert.devAssert)( + false, + `Invalid AST Node: ${(0, _inspect.inspect)(node)}.`, + ); + const visitFn = isLeaving + ? (_enterLeaveMap$get = enterLeaveMap.get(node.kind)) === null || + _enterLeaveMap$get === void 0 + ? void 0 + : _enterLeaveMap$get.leave + : (_enterLeaveMap$get2 = enterLeaveMap.get(node.kind)) === null || + _enterLeaveMap$get2 === void 0 + ? void 0 + : _enterLeaveMap$get2.enter; + result = + visitFn === null || visitFn === void 0 + ? void 0 + : visitFn.call(visitor, node, key, parent, path, ancestors); + if (result === BREAK) { break; + } - case _kinds.Kind.FRAGMENT_DEFINITION: - fragments[definition.name.value] = definition; - break; + if (result === false) { + if (!isLeaving) { + path.pop(); + continue; + } + } else if (result !== undefined) { + edits.push([key, result]); - default: // ignore non-executable definitions + if (!isLeaving) { + if ((0, _ast.isNode)(result)) { + node = result; + } else { + path.pop(); + continue; + } + } + } } - } - if (!operation) { - if (operationName != null) { - return [ - new _GraphQLError.GraphQLError( - `Unknown operation named "${operationName}".`, - ), - ]; + if (result === undefined && isEdited) { + edits.push([key, node]); } - return [new _GraphQLError.GraphQLError('Must provide an operation.')]; - } // FIXME: https://github.com/graphql/graphql-js/issues/2203 + if (isLeaving) { + path.pop(); + } else { + var _node$kind; - /* c8 ignore next */ + stack = { + inArray, + index, + keys, + edits, + prev: stack, + }; + inArray = Array.isArray(node); + keys = inArray + ? node + : (_node$kind = visitorKeys[node.kind]) !== null && + _node$kind !== void 0 + ? _node$kind + : []; + index = -1; + edits = []; - const variableDefinitions = - (_operation$variableDe = operation.variableDefinitions) !== null && - _operation$variableDe !== void 0 - ? _operation$variableDe - : []; - const coercedVariableValues = (0, _values.getVariableValues)( - schema, - variableDefinitions, - rawVariableValues !== null && rawVariableValues !== void 0 - ? rawVariableValues - : {}, - { - maxErrors: - (_options$maxCoercionE = - options === null || options === void 0 - ? void 0 - : options.maxCoercionErrors) !== null && - _options$maxCoercionE !== void 0 - ? _options$maxCoercionE - : 50, - }, - ); + if (parent) { + ancestors.push(parent); + } - if (coercedVariableValues.errors) { - return coercedVariableValues.errors; + parent = node; + } + } while (stack !== undefined); + + if (edits.length !== 0) { + // New root + return edits[edits.length - 1][1]; } - return { - schema, - fragments, - rootValue, - contextValue, - operation, - variableValues: coercedVariableValues.coerced, - fieldResolver: - fieldResolver !== null && fieldResolver !== void 0 - ? fieldResolver - : defaultFieldResolver, - typeResolver: - typeResolver !== null && typeResolver !== void 0 - ? typeResolver - : defaultTypeResolver, - subscribeFieldResolver: - subscribeFieldResolver !== null && subscribeFieldResolver !== void 0 - ? subscribeFieldResolver - : defaultFieldResolver, - errors: [], - }; + return root; } /** - * Implements the "Executing operations" section of the spec. + * Creates a new visitor instance which delegates to many visitors to run in + * parallel. Each visitor will be visited for each node before moving on. + * + * If a prior visitor edits a node, no following visitors will see that node. */ -function executeOperation(exeContext, operation, rootValue) { - const rootType = exeContext.schema.getRootType(operation.operation); +function visitInParallel(visitors) { + const skipping = new Array(visitors.length).fill(null); + const mergedVisitor = Object.create(null); - if (rootType == null) { - throw new _GraphQLError.GraphQLError( - `Schema is not configured to execute ${operation.operation} operation.`, - { - nodes: operation, + for (const kind of Object.values(_kinds.Kind)) { + let hasVisitor = false; + const enterList = new Array(visitors.length).fill(undefined); + const leaveList = new Array(visitors.length).fill(undefined); + + for (let i = 0; i < visitors.length; ++i) { + const { enter, leave } = getEnterLeaveForKind(visitors[i], kind); + hasVisitor || (hasVisitor = enter != null || leave != null); + enterList[i] = enter; + leaveList[i] = leave; + } + + if (!hasVisitor) { + continue; + } + + const mergedEnterLeave = { + enter(...args) { + const node = args[0]; + + for (let i = 0; i < visitors.length; i++) { + if (skipping[i] === null) { + var _enterList$i; + + const result = + (_enterList$i = enterList[i]) === null || _enterList$i === void 0 + ? void 0 + : _enterList$i.apply(visitors[i], args); + + if (result === false) { + skipping[i] = node; + } else if (result === BREAK) { + skipping[i] = BREAK; + } else if (result !== undefined) { + return result; + } + } + } }, - ); - } - const rootFields = (0, _collectFields.collectFields)( - exeContext.schema, - exeContext.fragments, - exeContext.variableValues, - rootType, - operation.selectionSet, - ); - const path = undefined; + leave(...args) { + const node = args[0]; - switch (operation.operation) { - case _ast.OperationTypeNode.QUERY: - return executeFields(exeContext, rootType, rootValue, path, rootFields); + for (let i = 0; i < visitors.length; i++) { + if (skipping[i] === null) { + var _leaveList$i; - case _ast.OperationTypeNode.MUTATION: - return executeFieldsSerially( - exeContext, - rootType, - rootValue, - path, - rootFields, - ); + const result = + (_leaveList$i = leaveList[i]) === null || _leaveList$i === void 0 + ? void 0 + : _leaveList$i.apply(visitors[i], args); - case _ast.OperationTypeNode.SUBSCRIPTION: - // TODO: deprecate `subscribe` and move all logic here - // Temporary solution until we finish merging execute and subscribe together - return executeFields(exeContext, rootType, rootValue, path, rootFields); + if (result === BREAK) { + skipping[i] = BREAK; + } else if (result !== undefined && result !== false) { + return result; + } + } else if (skipping[i] === node) { + skipping[i] = null; + } + } + }, + }; + mergedVisitor[kind] = mergedEnterLeave; } + + return mergedVisitor; } /** - * Implements the "Executing selection sets" section of the spec - * for fields that must be executed serially. + * Given a visitor instance and a node kind, return EnterLeaveVisitor for that kind. */ -function executeFieldsSerially( - exeContext, - parentType, - sourceValue, - path, - fields, -) { - return (0, _promiseReduce.promiseReduce)( - fields.entries(), - (results, [responseName, fieldNodes]) => { - const fieldPath = (0, _Path.addPath)(path, responseName, parentType.name); - const result = executeField( - exeContext, - parentType, - sourceValue, - fieldNodes, - fieldPath, - ); - - if (result === undefined) { - return results; - } +function getEnterLeaveForKind(visitor, kind) { + const kindVisitor = visitor[kind]; - if ((0, _isPromise.isPromise)(result)) { - return result.then((resolvedResult) => { - results[responseName] = resolvedResult; - return results; - }); - } + if (typeof kindVisitor === 'object') { + // { Kind: { enter() {}, leave() {} } } + return kindVisitor; + } else if (typeof kindVisitor === 'function') { + // { Kind() {} } + return { + enter: kindVisitor, + leave: undefined, + }; + } // { enter() {}, leave() {} } - results[responseName] = result; - return results; - }, - Object.create(null), - ); + return { + enter: visitor.enter, + leave: visitor.leave, + }; } /** - * Implements the "Executing selection sets" section of the spec - * for fields that may be executed in parallel. + * Given a visitor instance, if it is leaving or not, and a node kind, return + * the function the visitor runtime should call. + * + * @deprecated Please use `getEnterLeaveForKind` instead. Will be removed in v17 */ -function executeFields(exeContext, parentType, sourceValue, path, fields) { - const results = Object.create(null); - let containsPromise = false; +/* c8 ignore next 8 */ - try { - for (const [responseName, fieldNodes] of fields.entries()) { - const fieldPath = (0, _Path.addPath)(path, responseName, parentType.name); - const result = executeField( - exeContext, - parentType, - sourceValue, - fieldNodes, - fieldPath, - ); +function getVisitFn(visitor, kind, isLeaving) { + const { enter, leave } = getEnterLeaveForKind(visitor, kind); + return isLeaving ? leave : enter; +} - if (result !== undefined) { - results[responseName] = result; - if ((0, _isPromise.isPromise)(result)) { - containsPromise = true; - } - } - } - } catch (error) { - if (containsPromise) { - // Ensure that any promises returned by other fields are handled, as they may also reject. - return (0, _promiseForObject.promiseForObject)(results).finally(() => { - throw error; - }); - } +/***/ }), - throw error; - } // If there are no promises, we can just return the object +/***/ 74947: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (!containsPromise) { - return results; - } // Otherwise, results is a map from field name to the result of resolving that - // field, which is possibly a promise. Return a promise that will return this - // same map, but with any promises replaced with the values they resolved to. +"use strict"; - return (0, _promiseForObject.promiseForObject)(results); -} -/** - * Implements the "Executing fields" section of the spec - * In particular, this function figures out the value that the field returns by - * calling its resolve function, then calls completeValue to complete promises, - * serialize scalars, or execute the sub-selection-set for objects. - */ -function executeField(exeContext, parentType, source, fieldNodes, path) { - var _fieldDef$resolve; +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.assertEnumValueName = assertEnumValueName; +exports.assertName = assertName; - const fieldDef = getFieldDef(exeContext.schema, parentType, fieldNodes[0]); +var _devAssert = __nccwpck_require__(46514); - if (!fieldDef) { - return; - } +var _GraphQLError = __nccwpck_require__(4797); - const returnType = fieldDef.type; - const resolveFn = - (_fieldDef$resolve = fieldDef.resolve) !== null && - _fieldDef$resolve !== void 0 - ? _fieldDef$resolve - : exeContext.fieldResolver; - const info = buildResolveInfo( - exeContext, - fieldDef, - fieldNodes, - parentType, - path, - ); // Get the resolve function, regardless of if its result is normal or abrupt (error). +var _characterClasses = __nccwpck_require__(7234); - try { - // Build a JS object of arguments from the field.arguments AST, using the - // variables scope to fulfill any variable references. - // TODO: find a way to memoize, in case this field is within a List type. - const args = (0, _values.getArgumentValues)( - fieldDef, - fieldNodes[0], - exeContext.variableValues, - ); // The resolve function's optional third argument is a context value that - // is provided to every resolve function within an execution. It is commonly - // used to represent an authenticated user, or request-specific caches. +/** + * Upholds the spec rules about naming. + */ +function assertName(name) { + name != null || (0, _devAssert.devAssert)(false, 'Must provide name.'); + typeof name === 'string' || + (0, _devAssert.devAssert)(false, 'Expected name to be a string.'); - const contextValue = exeContext.contextValue; - const result = resolveFn(source, args, contextValue, info); - let completed; + if (name.length === 0) { + throw new _GraphQLError.GraphQLError( + 'Expected name to be a non-empty string.', + ); + } - if ((0, _isPromise.isPromise)(result)) { - completed = result.then((resolved) => - completeValue(exeContext, returnType, fieldNodes, info, path, resolved), - ); - } else { - completed = completeValue( - exeContext, - returnType, - fieldNodes, - info, - path, - result, + for (let i = 1; i < name.length; ++i) { + if (!(0, _characterClasses.isNameContinue)(name.charCodeAt(i))) { + throw new _GraphQLError.GraphQLError( + `Names must only contain [_a-zA-Z0-9] but "${name}" does not.`, ); } + } - if ((0, _isPromise.isPromise)(completed)) { - // Note: we don't rely on a `catch` method, but we do expect "thenable" - // to take a second callback for the error case. - return completed.then(undefined, (rawError) => { - const error = (0, _locatedError.locatedError)( - rawError, - fieldNodes, - (0, _Path.pathToArray)(path), - ); - return handleFieldError(error, returnType, exeContext); - }); - } - - return completed; - } catch (rawError) { - const error = (0, _locatedError.locatedError)( - rawError, - fieldNodes, - (0, _Path.pathToArray)(path), + if (!(0, _characterClasses.isNameStart)(name.charCodeAt(0))) { + throw new _GraphQLError.GraphQLError( + `Names must start with [_a-zA-Z] but "${name}" does not.`, ); - return handleFieldError(error, returnType, exeContext); } + + return name; } /** + * Upholds the spec rules about naming enum values. + * * @internal */ -function buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path) { - // The resolve function's optional fourth argument is a collection of - // information about the current execution state. - return { - fieldName: fieldDef.name, - fieldNodes, - returnType: fieldDef.type, - parentType, - path, - schema: exeContext.schema, - fragments: exeContext.fragments, - rootValue: exeContext.rootValue, - operation: exeContext.operation, - variableValues: exeContext.variableValues, - }; +function assertEnumValueName(name) { + if (name === 'true' || name === 'false' || name === 'null') { + throw new _GraphQLError.GraphQLError( + `Enum values cannot be named: ${name}`, + ); + } + + return assertName(name); } -function handleFieldError(error, returnType, exeContext) { - // If the field type is non-nullable, then it is resolved without any - // protection from errors, however it still properly locates the error. - if ((0, _definition.isNonNullType)(returnType)) { - throw error; - } // Otherwise, error protection is applied, logging the error and resolving - // a null value for this field if one is encountered. - exeContext.errors.push(error); - return null; -} -/** - * Implements the instructions for completeValue as defined in the - * "Value Completion" section of the spec. - * - * If the field type is Non-Null, then this recursively completes the value - * for the inner type. It throws a field error if that completion returns null, - * as per the "Nullability" section of the spec. - * - * If the field type is a List, then this recursively completes the value - * for the inner type on each item in the list. - * - * If the field type is a Scalar or Enum, ensures the completed value is a legal - * value of the type by calling the `serialize` method of GraphQL type - * definition. - * - * If the field is an abstract type, determine the runtime type of the value - * and then complete based on that type - * - * Otherwise, the field type expects a sub-selection set, and will complete the - * value by executing all sub-selections. - */ +/***/ }), -function completeValue(exeContext, returnType, fieldNodes, info, path, result) { - // If result is an Error, throw a located error. - if (result instanceof Error) { - throw result; - } // If field type is NonNull, complete for inner type, and throw field error - // if result is null. +/***/ 32150: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if ((0, _definition.isNonNullType)(returnType)) { - const completed = completeValue( - exeContext, - returnType.ofType, - fieldNodes, - info, - path, - result, - ); +"use strict"; - if (completed === null) { - throw new Error( - `Cannot return null for non-nullable field ${info.parentType.name}.${info.fieldName}.`, - ); - } - return completed; - } // If result value is null or undefined then return null. +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.GraphQLUnionType = + exports.GraphQLScalarType = + exports.GraphQLObjectType = + exports.GraphQLNonNull = + exports.GraphQLList = + exports.GraphQLInterfaceType = + exports.GraphQLInputObjectType = + exports.GraphQLEnumType = + void 0; +exports.argsToArgsConfig = argsToArgsConfig; +exports.assertAbstractType = assertAbstractType; +exports.assertCompositeType = assertCompositeType; +exports.assertEnumType = assertEnumType; +exports.assertInputObjectType = assertInputObjectType; +exports.assertInputType = assertInputType; +exports.assertInterfaceType = assertInterfaceType; +exports.assertLeafType = assertLeafType; +exports.assertListType = assertListType; +exports.assertNamedType = assertNamedType; +exports.assertNonNullType = assertNonNullType; +exports.assertNullableType = assertNullableType; +exports.assertObjectType = assertObjectType; +exports.assertOutputType = assertOutputType; +exports.assertScalarType = assertScalarType; +exports.assertType = assertType; +exports.assertUnionType = assertUnionType; +exports.assertWrappingType = assertWrappingType; +exports.defineArguments = defineArguments; +exports.getNamedType = getNamedType; +exports.getNullableType = getNullableType; +exports.isAbstractType = isAbstractType; +exports.isCompositeType = isCompositeType; +exports.isEnumType = isEnumType; +exports.isInputObjectType = isInputObjectType; +exports.isInputType = isInputType; +exports.isInterfaceType = isInterfaceType; +exports.isLeafType = isLeafType; +exports.isListType = isListType; +exports.isNamedType = isNamedType; +exports.isNonNullType = isNonNullType; +exports.isNullableType = isNullableType; +exports.isObjectType = isObjectType; +exports.isOutputType = isOutputType; +exports.isRequiredArgument = isRequiredArgument; +exports.isRequiredInputField = isRequiredInputField; +exports.isScalarType = isScalarType; +exports.isType = isType; +exports.isUnionType = isUnionType; +exports.isWrappingType = isWrappingType; +exports.resolveObjMapThunk = resolveObjMapThunk; +exports.resolveReadonlyArrayThunk = resolveReadonlyArrayThunk; - if (result == null) { - return null; - } // If field type is List, complete each item in the list with the inner type +var _devAssert = __nccwpck_require__(46514); - if ((0, _definition.isListType)(returnType)) { - return completeListValue( - exeContext, - returnType, - fieldNodes, - info, - path, - result, - ); - } // If field type is a leaf type, Scalar or Enum, serialize to a valid value, - // returning null if serialization is not possible. +var _didYouMean = __nccwpck_require__(42878); - if ((0, _definition.isLeafType)(returnType)) { - return completeLeafValue(returnType, result); - } // If field type is an abstract type, Interface or Union, determine the - // runtime Object type and complete for that type. +var _identityFunc = __nccwpck_require__(51188); - if ((0, _definition.isAbstractType)(returnType)) { - return completeAbstractValue( - exeContext, - returnType, - fieldNodes, - info, - path, - result, - ); - } // If field type is Object, execute and complete all sub-selections. +var _inspect = __nccwpck_require__(10102); - if ((0, _definition.isObjectType)(returnType)) { - return completeObjectValue( - exeContext, - returnType, - fieldNodes, - info, - path, - result, - ); - } - /* c8 ignore next 6 */ - // Not reachable, all possible output types have been considered. +var _instanceOf = __nccwpck_require__(93481); - false || - (0, _invariant.invariant)( - false, - 'Cannot complete value of unexpected output type: ' + - (0, _inspect.inspect)(returnType), - ); -} -/** - * Complete a list value by completing each item in the list with the - * inner type - */ +var _isObjectLike = __nccwpck_require__(95865); -function completeListValue( - exeContext, - returnType, - fieldNodes, - info, - path, - result, -) { - if (!(0, _isIterableObject.isIterableObject)(result)) { - throw new _GraphQLError.GraphQLError( - `Expected Iterable, but did not find one for field "${info.parentType.name}.${info.fieldName}".`, - ); - } // This is specified as a simple map, however we're optimizing the path - // where the list contains no Promises by avoiding creating another Promise. +var _keyMap = __nccwpck_require__(10711); - const itemType = returnType.ofType; - let containsPromise = false; - const completedResults = Array.from(result, (item, index) => { - // No need to modify the info object containing the path, - // since from here on it is not ever accessed by resolver functions. - const itemPath = (0, _Path.addPath)(path, index, undefined); +var _keyValMap = __nccwpck_require__(49268); - try { - let completedItem; +var _mapValue = __nccwpck_require__(32223); - if ((0, _isPromise.isPromise)(item)) { - completedItem = item.then((resolved) => - completeValue( - exeContext, - itemType, - fieldNodes, - info, - itemPath, - resolved, - ), - ); - } else { - completedItem = completeValue( - exeContext, - itemType, - fieldNodes, - info, - itemPath, - item, - ); - } +var _suggestionList = __nccwpck_require__(57704); - if ((0, _isPromise.isPromise)(completedItem)) { - containsPromise = true; // Note: we don't rely on a `catch` method, but we do expect "thenable" - // to take a second callback for the error case. +var _toObjMap = __nccwpck_require__(74728); - return completedItem.then(undefined, (rawError) => { - const error = (0, _locatedError.locatedError)( - rawError, - fieldNodes, - (0, _Path.pathToArray)(itemPath), - ); - return handleFieldError(error, itemType, exeContext); - }); - } +var _GraphQLError = __nccwpck_require__(4797); - return completedItem; - } catch (rawError) { - const error = (0, _locatedError.locatedError)( - rawError, - fieldNodes, - (0, _Path.pathToArray)(itemPath), - ); - return handleFieldError(error, itemType, exeContext); - } - }); - return containsPromise ? Promise.all(completedResults) : completedResults; -} -/** - * Complete a Scalar or Enum by serializing to a valid value, returning - * null if serialization is not possible. - */ +var _kinds = __nccwpck_require__(11927); -function completeLeafValue(returnType, result) { - const serializedResult = returnType.serialize(result); +var _printer = __nccwpck_require__(68203); - if (serializedResult == null) { +var _valueFromASTUntyped = __nccwpck_require__(86699); + +var _assertName = __nccwpck_require__(74947); + +function isType(type) { + return ( + isScalarType(type) || + isObjectType(type) || + isInterfaceType(type) || + isUnionType(type) || + isEnumType(type) || + isInputObjectType(type) || + isListType(type) || + isNonNullType(type) + ); +} + +function assertType(type) { + if (!isType(type)) { throw new Error( - `Expected \`${(0, _inspect.inspect)(returnType)}.serialize(${(0, - _inspect.inspect)(result)})\` to ` + - `return non-nullable value, returned: ${(0, _inspect.inspect)( - serializedResult, - )}`, + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL type.`, ); } - return serializedResult; + return type; } /** - * Complete a value of an abstract type by determining the runtime object type - * of that value, then complete the value for that type. + * There are predicates for each kind of GraphQL type. */ -function completeAbstractValue( - exeContext, - returnType, - fieldNodes, - info, - path, - result, -) { - var _returnType$resolveTy; - - const resolveTypeFn = - (_returnType$resolveTy = returnType.resolveType) !== null && - _returnType$resolveTy !== void 0 - ? _returnType$resolveTy - : exeContext.typeResolver; - const contextValue = exeContext.contextValue; - const runtimeType = resolveTypeFn(result, contextValue, info, returnType); - - if ((0, _isPromise.isPromise)(runtimeType)) { - return runtimeType.then((resolvedRuntimeType) => - completeObjectValue( - exeContext, - ensureValidRuntimeType( - resolvedRuntimeType, - exeContext, - returnType, - fieldNodes, - info, - result, - ), - fieldNodes, - info, - path, - result, - ), - ); - } - - return completeObjectValue( - exeContext, - ensureValidRuntimeType( - runtimeType, - exeContext, - returnType, - fieldNodes, - info, - result, - ), - fieldNodes, - info, - path, - result, - ); +function isScalarType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLScalarType); } -function ensureValidRuntimeType( - runtimeTypeName, - exeContext, - returnType, - fieldNodes, - info, - result, -) { - if (runtimeTypeName == null) { - throw new _GraphQLError.GraphQLError( - `Abstract type "${returnType.name}" must resolve to an Object type at runtime for field "${info.parentType.name}.${info.fieldName}". Either the "${returnType.name}" type should provide a "resolveType" function or each possible type should provide an "isTypeOf" function.`, - fieldNodes, - ); - } // releases before 16.0.0 supported returning `GraphQLObjectType` from `resolveType` - // TODO: remove in 17.0.0 release - - if ((0, _definition.isObjectType)(runtimeTypeName)) { - throw new _GraphQLError.GraphQLError( - 'Support for returning GraphQLObjectType from resolveType was removed in graphql-js@16.0.0 please return type name instead.', +function assertScalarType(type) { + if (!isScalarType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Scalar type.`, ); } - if (typeof runtimeTypeName !== 'string') { - throw new _GraphQLError.GraphQLError( - `Abstract type "${returnType.name}" must resolve to an Object type at runtime for field "${info.parentType.name}.${info.fieldName}" with ` + - `value ${(0, _inspect.inspect)(result)}, received "${(0, - _inspect.inspect)(runtimeTypeName)}".`, - ); - } + return type; +} - const runtimeType = exeContext.schema.getType(runtimeTypeName); +function isObjectType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLObjectType); +} - if (runtimeType == null) { - throw new _GraphQLError.GraphQLError( - `Abstract type "${returnType.name}" was resolved to a type "${runtimeTypeName}" that does not exist inside the schema.`, - { - nodes: fieldNodes, - }, +function assertObjectType(type) { + if (!isObjectType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Object type.`, ); } - if (!(0, _definition.isObjectType)(runtimeType)) { - throw new _GraphQLError.GraphQLError( - `Abstract type "${returnType.name}" was resolved to a non-object type "${runtimeTypeName}".`, - { - nodes: fieldNodes, - }, + return type; +} + +function isInterfaceType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLInterfaceType); +} + +function assertInterfaceType(type) { + if (!isInterfaceType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Interface type.`, ); } - if (!exeContext.schema.isSubType(returnType, runtimeType)) { - throw new _GraphQLError.GraphQLError( - `Runtime Object type "${runtimeType.name}" is not a possible type for "${returnType.name}".`, - { - nodes: fieldNodes, - }, + return type; +} + +function isUnionType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLUnionType); +} + +function assertUnionType(type) { + if (!isUnionType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Union type.`, ); } - return runtimeType; + return type; } -/** - * Complete an Object value by executing all sub-selections. - */ -function completeObjectValue( - exeContext, - returnType, - fieldNodes, - info, - path, - result, -) { - // Collect sub-fields to execute to complete this value. - const subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes); // If there is an isTypeOf predicate function, call it with the - // current result. If isTypeOf returns false, then raise an error rather - // than continuing execution. +function isEnumType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLEnumType); +} - if (returnType.isTypeOf) { - const isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info); +function assertEnumType(type) { + if (!isEnumType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Enum type.`, + ); + } - if ((0, _isPromise.isPromise)(isTypeOf)) { - return isTypeOf.then((resolvedIsTypeOf) => { - if (!resolvedIsTypeOf) { - throw invalidReturnTypeError(returnType, result, fieldNodes); - } + return type; +} - return executeFields( - exeContext, - returnType, - result, - path, - subFieldNodes, - ); - }); - } +function isInputObjectType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLInputObjectType); +} - if (!isTypeOf) { - throw invalidReturnTypeError(returnType, result, fieldNodes); - } +function assertInputObjectType(type) { + if (!isInputObjectType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)( + type, + )} to be a GraphQL Input Object type.`, + ); } - return executeFields(exeContext, returnType, result, path, subFieldNodes); + return type; } -function invalidReturnTypeError(returnType, result, fieldNodes) { - return new _GraphQLError.GraphQLError( - `Expected value of type "${returnType.name}" but got: ${(0, - _inspect.inspect)(result)}.`, - { - nodes: fieldNodes, - }, - ); +function isListType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLList); } -/** - * If a resolveType function is not given, then a default resolve behavior is - * used which attempts two strategies: - * - * First, See if the provided value has a `__typename` field defined, if so, use - * that value as name of the resolved type. - * - * Otherwise, test each possible type for the abstract type by calling - * isTypeOf for the object being coerced, returning the first type that matches. - */ - -const defaultTypeResolver = function (value, contextValue, info, abstractType) { - // First, look for `__typename`. - if ( - (0, _isObjectLike.isObjectLike)(value) && - typeof value.__typename === 'string' - ) { - return value.__typename; - } // Otherwise, test each possible type. - const possibleTypes = info.schema.getPossibleTypes(abstractType); - const promisedIsTypeOfResults = []; +function assertListType(type) { + if (!isListType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL List type.`, + ); + } - for (let i = 0; i < possibleTypes.length; i++) { - const type = possibleTypes[i]; + return type; +} - if (type.isTypeOf) { - const isTypeOfResult = type.isTypeOf(value, contextValue, info); +function isNonNullType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLNonNull); +} - if ((0, _isPromise.isPromise)(isTypeOfResult)) { - promisedIsTypeOfResults[i] = isTypeOfResult; - } else if (isTypeOfResult) { - return type.name; - } - } +function assertNonNullType(type) { + if (!isNonNullType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Non-Null type.`, + ); } - if (promisedIsTypeOfResults.length) { - return Promise.all(promisedIsTypeOfResults).then((isTypeOfResults) => { - for (let i = 0; i < isTypeOfResults.length; i++) { - if (isTypeOfResults[i]) { - return possibleTypes[i].name; - } - } - }); - } -}; + return type; +} /** - * If a resolve function is not given, then a default resolve behavior is used - * which takes the property of the source object of the same name as the field - * and returns it as the result, or if it's a function, returns the result - * of calling that function while passing along args and context value. + * These types may be used as input types for arguments and directives. */ -exports.defaultTypeResolver = defaultTypeResolver; - -const defaultFieldResolver = function (source, args, contextValue, info) { - // ensure source is a value for which property access is acceptable. - if ((0, _isObjectLike.isObjectLike)(source) || typeof source === 'function') { - const property = source[info.fieldName]; - - if (typeof property === 'function') { - return source[info.fieldName](args, contextValue, info); - } +function isInputType(type) { + return ( + isScalarType(type) || + isEnumType(type) || + isInputObjectType(type) || + (isWrappingType(type) && isInputType(type.ofType)) + ); +} - return property; +function assertInputType(type) { + if (!isInputType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL input type.`, + ); } -}; + + return type; +} /** - * This method looks up the field on the given type definition. - * It has special casing for the three introspection fields, - * __schema, __type and __typename. __typename is special because - * it can always be queried as a field, even in situations where no - * other fields are allowed, like on a Union. __schema and __type - * could get automatically added to the query type, but that would - * require mutating type definitions, which would cause issues. - * - * @internal + * These types may be used as output types as the result of fields. */ -exports.defaultFieldResolver = defaultFieldResolver; - -function getFieldDef(schema, parentType, fieldNode) { - const fieldName = fieldNode.name.value; +function isOutputType(type) { + return ( + isScalarType(type) || + isObjectType(type) || + isInterfaceType(type) || + isUnionType(type) || + isEnumType(type) || + (isWrappingType(type) && isOutputType(type.ofType)) + ); +} - if ( - fieldName === _introspection.SchemaMetaFieldDef.name && - schema.getQueryType() === parentType - ) { - return _introspection.SchemaMetaFieldDef; - } else if ( - fieldName === _introspection.TypeMetaFieldDef.name && - schema.getQueryType() === parentType - ) { - return _introspection.TypeMetaFieldDef; - } else if (fieldName === _introspection.TypeNameMetaFieldDef.name) { - return _introspection.TypeNameMetaFieldDef; +function assertOutputType(type) { + if (!isOutputType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL output type.`, + ); } - return parentType.getFields()[fieldName]; + return type; } +/** + * These types may describe types which may be leaf values. + */ +function isLeafType(type) { + return isScalarType(type) || isEnumType(type); +} -/***/ }), - -/***/ 13176: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -Object.defineProperty(exports, "createSourceEventStream", ({ - enumerable: true, - get: function () { - return _subscribe.createSourceEventStream; - }, -})); -Object.defineProperty(exports, "defaultFieldResolver", ({ - enumerable: true, - get: function () { - return _execute.defaultFieldResolver; - }, -})); -Object.defineProperty(exports, "defaultTypeResolver", ({ - enumerable: true, - get: function () { - return _execute.defaultTypeResolver; - }, -})); -Object.defineProperty(exports, "execute", ({ - enumerable: true, - get: function () { - return _execute.execute; - }, -})); -Object.defineProperty(exports, "executeSync", ({ - enumerable: true, - get: function () { - return _execute.executeSync; - }, -})); -Object.defineProperty(exports, "getArgumentValues", ({ - enumerable: true, - get: function () { - return _values.getArgumentValues; - }, -})); -Object.defineProperty(exports, "getDirectiveValues", ({ - enumerable: true, - get: function () { - return _values.getDirectiveValues; - }, -})); -Object.defineProperty(exports, "getVariableValues", ({ - enumerable: true, - get: function () { - return _values.getVariableValues; - }, -})); -Object.defineProperty(exports, "responsePathAsArray", ({ - enumerable: true, - get: function () { - return _Path.pathToArray; - }, -})); -Object.defineProperty(exports, "subscribe", ({ - enumerable: true, - get: function () { - return _subscribe.subscribe; - }, -})); +function assertLeafType(type) { + if (!isLeafType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL leaf type.`, + ); + } -var _Path = __nccwpck_require__(11262); + return type; +} +/** + * These types may describe the parent context of a selection set. + */ -var _execute = __nccwpck_require__(83677); +function isCompositeType(type) { + return isObjectType(type) || isInterfaceType(type) || isUnionType(type); +} -var _subscribe = __nccwpck_require__(77847); +function assertCompositeType(type) { + if (!isCompositeType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL composite type.`, + ); + } -var _values = __nccwpck_require__(94834); + return type; +} +/** + * These types may describe the parent context of a selection set. + */ +function isAbstractType(type) { + return isInterfaceType(type) || isUnionType(type); +} -/***/ }), +function assertAbstractType(type) { + if (!isAbstractType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL abstract type.`, + ); + } -/***/ 86063: -/***/ ((__unused_webpack_module, exports) => { + return type; +} +/** + * List Type Wrapper + * + * A list is a wrapping type which points to another type. + * Lists are often created within the context of defining the fields of + * an object type. + * + * Example: + * + * ```ts + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * parents: { type: new GraphQLList(PersonType) }, + * children: { type: new GraphQLList(PersonType) }, + * }) + * }) + * ``` + */ -"use strict"; +class GraphQLList { + constructor(ofType) { + isType(ofType) || + (0, _devAssert.devAssert)( + false, + `Expected ${(0, _inspect.inspect)(ofType)} to be a GraphQL type.`, + ); + this.ofType = ofType; + } + get [Symbol.toStringTag]() { + return 'GraphQLList'; + } -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.mapAsyncIterator = mapAsyncIterator; + toString() { + return '[' + String(this.ofType) + ']'; + } + toJSON() { + return this.toString(); + } +} /** - * Given an AsyncIterable and a callback function, return an AsyncIterator - * which produces values mapped via calling the callback function. + * Non-Null Type Wrapper + * + * A non-null is a wrapping type which points to another type. + * Non-null types enforce that their values are never null and can ensure + * an error is raised if this ever occurs during a request. It is useful for + * fields which you can make a strong guarantee on non-nullability, for example + * usually the id field of a database row will never be null. + * + * Example: + * + * ```ts + * const RowType = new GraphQLObjectType({ + * name: 'Row', + * fields: () => ({ + * id: { type: new GraphQLNonNull(GraphQLString) }, + * }) + * }) + * ``` + * Note: the enforcement of non-nullability occurs within the executor. */ -function mapAsyncIterator(iterable, callback) { - const iterator = iterable[Symbol.asyncIterator](); - async function mapResult(result) { - if (result.done) { - return result; - } - - try { - return { - value: await callback(result.value), - done: false, - }; - } catch (error) { - /* c8 ignore start */ - // FIXME: add test case - if (typeof iterator.return === 'function') { - try { - await iterator.return(); - } catch (_e) { - /* ignore error */ - } - } +exports.GraphQLList = GraphQLList; - throw error; - /* c8 ignore stop */ - } +class GraphQLNonNull { + constructor(ofType) { + isNullableType(ofType) || + (0, _devAssert.devAssert)( + false, + `Expected ${(0, _inspect.inspect)( + ofType, + )} to be a GraphQL nullable type.`, + ); + this.ofType = ofType; } - return { - async next() { - return mapResult(await iterator.next()); - }, - - async return() { - // If iterator.return() does not exist, then type R must be undefined. - return typeof iterator.return === 'function' - ? mapResult(await iterator.return()) - : { - value: undefined, - done: true, - }; - }, - - async throw(error) { - if (typeof iterator.throw === 'function') { - return mapResult(await iterator.throw(error)); - } + get [Symbol.toStringTag]() { + return 'GraphQLNonNull'; + } - throw error; - }, + toString() { + return String(this.ofType) + '!'; + } - [Symbol.asyncIterator]() { - return this; - }, - }; + toJSON() { + return this.toString(); + } } +/** + * These types wrap and modify other types + */ +exports.GraphQLNonNull = GraphQLNonNull; -/***/ }), +function isWrappingType(type) { + return isListType(type) || isNonNullType(type); +} -/***/ 77847: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function assertWrappingType(type) { + if (!isWrappingType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL wrapping type.`, + ); + } -"use strict"; + return type; +} +/** + * These types can all accept null as a value. + */ +function isNullableType(type) { + return isType(type) && !isNonNullType(type); +} -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.createSourceEventStream = createSourceEventStream; -exports.subscribe = subscribe; +function assertNullableType(type) { + if (!isNullableType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL nullable type.`, + ); + } -var _devAssert = __nccwpck_require__(46514); + return type; +} -var _inspect = __nccwpck_require__(10102); +function getNullableType(type) { + if (type) { + return isNonNullType(type) ? type.ofType : type; + } +} +/** + * These named types do not include modifiers like List or NonNull. + */ -var _isAsyncIterable = __nccwpck_require__(20626); +function isNamedType(type) { + return ( + isScalarType(type) || + isObjectType(type) || + isInterfaceType(type) || + isUnionType(type) || + isEnumType(type) || + isInputObjectType(type) + ); +} -var _Path = __nccwpck_require__(11262); +function assertNamedType(type) { + if (!isNamedType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL named type.`, + ); + } -var _GraphQLError = __nccwpck_require__(4797); + return type; +} -var _locatedError = __nccwpck_require__(16842); +function getNamedType(type) { + if (type) { + let unwrappedType = type; -var _collectFields = __nccwpck_require__(49942); + while (isWrappingType(unwrappedType)) { + unwrappedType = unwrappedType.ofType; + } -var _execute = __nccwpck_require__(83677); + return unwrappedType; + } +} +/** + * Used while defining GraphQL types to allow for circular references in + * otherwise immutable type definitions. + */ -var _mapAsyncIterator = __nccwpck_require__(86063); +function resolveReadonlyArrayThunk(thunk) { + return typeof thunk === 'function' ? thunk() : thunk; +} -var _values = __nccwpck_require__(94834); +function resolveObjMapThunk(thunk) { + return typeof thunk === 'function' ? thunk() : thunk; +} +/** + * Custom extensions + * + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ /** - * Implements the "Subscribe" algorithm described in the GraphQL specification. + * Scalar Type Definition * - * Returns a Promise which resolves to either an AsyncIterator (if successful) - * or an ExecutionResult (error). The promise will be rejected if the schema or - * other arguments to this function are invalid, or if the resolved event stream - * is not an async iterable. + * The leaf values of any request and input values to arguments are + * Scalars (or Enums) and are defined with a name and a series of functions + * used to parse input from ast or variables and to ensure validity. * - * If the client-provided arguments to this function do not result in a - * compliant subscription, a GraphQL Response (ExecutionResult) with - * descriptive errors and no data will be returned. + * If a type's serialize function returns `null` or does not return a value + * (i.e. it returns `undefined`) then an error will be raised and a `null` + * value will be returned in the response. It is always better to validate * - * If the source stream could not be created due to faulty subscription - * resolver logic or underlying systems, the promise will resolve to a single - * ExecutionResult containing `errors` and no `data`. + * Example: * - * If the operation succeeded, the promise resolves to an AsyncIterator, which - * yields a stream of ExecutionResults representing the response stream. + * ```ts + * const OddType = new GraphQLScalarType({ + * name: 'Odd', + * serialize(value) { + * if (!Number.isFinite(value)) { + * throw new Error( + * `Scalar "Odd" cannot represent "${value}" since it is not a finite number.`, + * ); + * } * - * Accepts either an object with named arguments, or individual arguments. + * if (value % 2 === 0) { + * throw new Error(`Scalar "Odd" cannot represent "${value}" since it is even.`); + * } + * return value; + * } + * }); + * ``` */ -async function subscribe(args) { - // Temporary for v15 to v16 migration. Remove in v17 - arguments.length < 2 || - (0, _devAssert.devAssert)( - false, - 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.', - ); - const resultOrStream = await createSourceEventStream(args); +class GraphQLScalarType { + constructor(config) { + var _config$parseValue, + _config$serialize, + _config$parseLiteral, + _config$extensionASTN; - if (!(0, _isAsyncIterable.isAsyncIterable)(resultOrStream)) { - return resultOrStream; - } // For each payload yielded from a subscription, map it over the normal - // GraphQL `execute` function, with `payload` as the rootValue. - // This implements the "MapSourceToResponseEvent" algorithm described in - // the GraphQL specification. The `execute` function provides the - // "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the - // "ExecuteQuery" algorithm, for which `execute` is also used. + const parseValue = + (_config$parseValue = config.parseValue) !== null && + _config$parseValue !== void 0 + ? _config$parseValue + : _identityFunc.identityFunc; + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.specifiedByURL = config.specifiedByURL; + this.serialize = + (_config$serialize = config.serialize) !== null && + _config$serialize !== void 0 + ? _config$serialize + : _identityFunc.identityFunc; + this.parseValue = parseValue; + this.parseLiteral = + (_config$parseLiteral = config.parseLiteral) !== null && + _config$parseLiteral !== void 0 + ? _config$parseLiteral + : (node, variables) => + parseValue( + (0, _valueFromASTUntyped.valueFromASTUntyped)(node, variables), + ); + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = + (_config$extensionASTN = config.extensionASTNodes) !== null && + _config$extensionASTN !== void 0 + ? _config$extensionASTN + : []; + config.specifiedByURL == null || + typeof config.specifiedByURL === 'string' || + (0, _devAssert.devAssert)( + false, + `${this.name} must provide "specifiedByURL" as a string, ` + + `but got: ${(0, _inspect.inspect)(config.specifiedByURL)}.`, + ); + config.serialize == null || + typeof config.serialize === 'function' || + (0, _devAssert.devAssert)( + false, + `${this.name} must provide "serialize" function. If this custom Scalar is also used as an input type, ensure "parseValue" and "parseLiteral" functions are also provided.`, + ); - const mapSourceToResponse = (payload) => - (0, _execute.execute)({ ...args, rootValue: payload }); // Map every source value to a ExecutionResult value as described above. + if (config.parseLiteral) { + (typeof config.parseValue === 'function' && + typeof config.parseLiteral === 'function') || + (0, _devAssert.devAssert)( + false, + `${this.name} must provide both "parseValue" and "parseLiteral" functions.`, + ); + } + } - return (0, _mapAsyncIterator.mapAsyncIterator)( - resultOrStream, - mapSourceToResponse, - ); -} + get [Symbol.toStringTag]() { + return 'GraphQLScalarType'; + } -function toNormalizedArgs(args) { - const firstArg = args[0]; + toConfig() { + return { + name: this.name, + description: this.description, + specifiedByURL: this.specifiedByURL, + serialize: this.serialize, + parseValue: this.parseValue, + parseLiteral: this.parseLiteral, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + }; + } - if (firstArg && 'document' in firstArg) { - return firstArg; + toString() { + return this.name; } - return { - schema: firstArg, - // FIXME: when underlying TS bug fixed, see https://github.com/microsoft/TypeScript/issues/31613 - document: args[1], - rootValue: args[2], - contextValue: args[3], - variableValues: args[4], - operationName: args[5], - subscribeFieldResolver: args[6], - }; + toJSON() { + return this.toString(); + } } + +exports.GraphQLScalarType = GraphQLScalarType; + /** - * Implements the "CreateSourceEventStream" algorithm described in the - * GraphQL specification, resolving the subscription source event stream. + * Object Type Definition * - * Returns a Promise which resolves to either an AsyncIterable (if successful) - * or an ExecutionResult (error). The promise will be rejected if the schema or - * other arguments to this function are invalid, or if the resolved event stream - * is not an async iterable. + * Almost all of the GraphQL types you define will be object types. Object types + * have a name, but most importantly describe their fields. * - * If the client-provided arguments to this function do not result in a - * compliant subscription, a GraphQL Response (ExecutionResult) with - * descriptive errors and no data will be returned. + * Example: * - * If the the source stream could not be created due to faulty subscription - * resolver logic or underlying systems, the promise will resolve to a single - * ExecutionResult containing `errors` and no `data`. + * ```ts + * const AddressType = new GraphQLObjectType({ + * name: 'Address', + * fields: { + * street: { type: GraphQLString }, + * number: { type: GraphQLInt }, + * formatted: { + * type: GraphQLString, + * resolve(obj) { + * return obj.number + ' ' + obj.street + * } + * } + * } + * }); + * ``` * - * If the operation succeeded, the promise resolves to the AsyncIterable for the - * event stream returned by the resolver. + * When two types need to refer to each other, or a type needs to refer to + * itself in a field, you can use a function expression (aka a closure or a + * thunk) to supply the fields lazily. * - * A Source Event Stream represents a sequence of events, each of which triggers - * a GraphQL execution for that event. + * Example: * - * This may be useful when hosting the stateful subscription service in a - * different process or machine than the stateless GraphQL execution engine, - * or otherwise separating these two steps. For more on this, see the - * "Supporting Subscriptions at Scale" information in the GraphQL specification. + * ```ts + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * name: { type: GraphQLString }, + * bestFriend: { type: PersonType }, + * }) + * }); + * ``` */ +class GraphQLObjectType { + constructor(config) { + var _config$extensionASTN2; -async function createSourceEventStream(...rawArgs) { - const args = toNormalizedArgs(rawArgs); - const { schema, document, variableValues } = args; // If arguments are missing or incorrectly typed, this is an internal - // developer mistake which should throw an early error. + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.isTypeOf = config.isTypeOf; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = + (_config$extensionASTN2 = config.extensionASTNodes) !== null && + _config$extensionASTN2 !== void 0 + ? _config$extensionASTN2 + : []; - (0, _execute.assertValidExecutionArguments)(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments, - // a "Response" with only errors is returned. + this._fields = () => defineFieldMap(config); - const exeContext = (0, _execute.buildExecutionContext)(args); // Return early errors if execution context failed. + this._interfaces = () => defineInterfaces(config); - if (!('schema' in exeContext)) { - return { - errors: exeContext, - }; + config.isTypeOf == null || + typeof config.isTypeOf === 'function' || + (0, _devAssert.devAssert)( + false, + `${this.name} must provide "isTypeOf" as a function, ` + + `but got: ${(0, _inspect.inspect)(config.isTypeOf)}.`, + ); } - try { - const eventStream = await executeSubscription(exeContext); // Assert field returned an event stream, otherwise yield an error. + get [Symbol.toStringTag]() { + return 'GraphQLObjectType'; + } - if (!(0, _isAsyncIterable.isAsyncIterable)(eventStream)) { - throw new Error( - 'Subscription field must return Async Iterable. ' + - `Received: ${(0, _inspect.inspect)(eventStream)}.`, - ); + getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); } - return eventStream; - } catch (error) { - // If it GraphQLError, report it as an ExecutionResult, containing only errors and no data. - // Otherwise treat the error as a system-class error and re-throw it. - if (error instanceof _GraphQLError.GraphQLError) { - return { - errors: [error], - }; + return this._fields; + } + + getInterfaces() { + if (typeof this._interfaces === 'function') { + this._interfaces = this._interfaces(); } - throw error; + return this._interfaces; } -} -async function executeSubscription(exeContext) { - const { schema, fragments, operation, variableValues, rootValue } = - exeContext; - const rootType = schema.getSubscriptionType(); + toConfig() { + return { + name: this.name, + description: this.description, + interfaces: this.getInterfaces(), + fields: fieldsToFieldsConfig(this.getFields()), + isTypeOf: this.isTypeOf, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + }; + } - if (rootType == null) { - throw new _GraphQLError.GraphQLError( - 'Schema is not configured to execute subscription operation.', - { - nodes: operation, - }, - ); + toString() { + return this.name; } - const rootFields = (0, _collectFields.collectFields)( - schema, - fragments, - variableValues, - rootType, - operation.selectionSet, + toJSON() { + return this.toString(); + } +} + +exports.GraphQLObjectType = GraphQLObjectType; + +function defineInterfaces(config) { + var _config$interfaces; + + const interfaces = resolveReadonlyArrayThunk( + (_config$interfaces = config.interfaces) !== null && + _config$interfaces !== void 0 + ? _config$interfaces + : [], ); - const [responseName, fieldNodes] = [...rootFields.entries()][0]; - const fieldDef = (0, _execute.getFieldDef)(schema, rootType, fieldNodes[0]); + Array.isArray(interfaces) || + (0, _devAssert.devAssert)( + false, + `${config.name} interfaces must be an Array or a function which returns an Array.`, + ); + return interfaces; +} - if (!fieldDef) { - const fieldName = fieldNodes[0].name.value; - throw new _GraphQLError.GraphQLError( - `The subscription field "${fieldName}" is not defined.`, - { - nodes: fieldNodes, - }, +function defineFieldMap(config) { + const fieldMap = resolveObjMapThunk(config.fields); + isPlainObj(fieldMap) || + (0, _devAssert.devAssert)( + false, + `${config.name} fields must be an object with field names as keys or a function which returns such an object.`, ); - } + return (0, _mapValue.mapValue)(fieldMap, (fieldConfig, fieldName) => { + var _fieldConfig$args; + + isPlainObj(fieldConfig) || + (0, _devAssert.devAssert)( + false, + `${config.name}.${fieldName} field config must be an object.`, + ); + fieldConfig.resolve == null || + typeof fieldConfig.resolve === 'function' || + (0, _devAssert.devAssert)( + false, + `${config.name}.${fieldName} field resolver must be a function if ` + + `provided, but got: ${(0, _inspect.inspect)(fieldConfig.resolve)}.`, + ); + const argsConfig = + (_fieldConfig$args = fieldConfig.args) !== null && + _fieldConfig$args !== void 0 + ? _fieldConfig$args + : {}; + isPlainObj(argsConfig) || + (0, _devAssert.devAssert)( + false, + `${config.name}.${fieldName} args must be an object with argument names as keys.`, + ); + return { + name: (0, _assertName.assertName)(fieldName), + description: fieldConfig.description, + type: fieldConfig.type, + args: defineArguments(argsConfig), + resolve: fieldConfig.resolve, + subscribe: fieldConfig.subscribe, + deprecationReason: fieldConfig.deprecationReason, + extensions: (0, _toObjMap.toObjMap)(fieldConfig.extensions), + astNode: fieldConfig.astNode, + }; + }); +} + +function defineArguments(config) { + return Object.entries(config).map(([argName, argConfig]) => ({ + name: (0, _assertName.assertName)(argName), + description: argConfig.description, + type: argConfig.type, + defaultValue: argConfig.defaultValue, + deprecationReason: argConfig.deprecationReason, + extensions: (0, _toObjMap.toObjMap)(argConfig.extensions), + astNode: argConfig.astNode, + })); +} + +function isPlainObj(obj) { + return (0, _isObjectLike.isObjectLike)(obj) && !Array.isArray(obj); +} + +function fieldsToFieldsConfig(fields) { + return (0, _mapValue.mapValue)(fields, (field) => ({ + description: field.description, + type: field.type, + args: argsToArgsConfig(field.args), + resolve: field.resolve, + subscribe: field.subscribe, + deprecationReason: field.deprecationReason, + extensions: field.extensions, + astNode: field.astNode, + })); +} +/** + * @internal + */ - const path = (0, _Path.addPath)(undefined, responseName, rootType.name); - const info = (0, _execute.buildResolveInfo)( - exeContext, - fieldDef, - fieldNodes, - rootType, - path, +function argsToArgsConfig(args) { + return (0, _keyValMap.keyValMap)( + args, + (arg) => arg.name, + (arg) => ({ + description: arg.description, + type: arg.type, + defaultValue: arg.defaultValue, + deprecationReason: arg.deprecationReason, + extensions: arg.extensions, + astNode: arg.astNode, + }), ); +} - try { - var _fieldDef$subscribe; +function isRequiredArgument(arg) { + return isNonNullType(arg.type) && arg.defaultValue === undefined; +} - // Implements the "ResolveFieldEventStream" algorithm from GraphQL specification. - // It differs from "ResolveFieldValue" due to providing a different `resolveFn`. - // Build a JS object of arguments from the field.arguments AST, using the - // variables scope to fulfill any variable references. - const args = (0, _values.getArgumentValues)( - fieldDef, - fieldNodes[0], - variableValues, - ); // The resolve function's optional third argument is a context value that - // is provided to every resolve function within an execution. It is commonly - // used to represent an authenticated user, or request-specific caches. +/** + * Interface Type Definition + * + * When a field can return one of a heterogeneous set of types, a Interface type + * is used to describe what types are possible, what fields are in common across + * all types, as well as a function to determine which type is actually used + * when the field is resolved. + * + * Example: + * + * ```ts + * const EntityType = new GraphQLInterfaceType({ + * name: 'Entity', + * fields: { + * name: { type: GraphQLString } + * } + * }); + * ``` + */ +class GraphQLInterfaceType { + constructor(config) { + var _config$extensionASTN3; - const contextValue = exeContext.contextValue; // Call the `subscribe()` resolver or the default resolver to produce an - // AsyncIterable yielding raw payloads. + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.resolveType = config.resolveType; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = + (_config$extensionASTN3 = config.extensionASTNodes) !== null && + _config$extensionASTN3 !== void 0 + ? _config$extensionASTN3 + : []; + this._fields = defineFieldMap.bind(undefined, config); + this._interfaces = defineInterfaces.bind(undefined, config); + config.resolveType == null || + typeof config.resolveType === 'function' || + (0, _devAssert.devAssert)( + false, + `${this.name} must provide "resolveType" as a function, ` + + `but got: ${(0, _inspect.inspect)(config.resolveType)}.`, + ); + } - const resolveFn = - (_fieldDef$subscribe = fieldDef.subscribe) !== null && - _fieldDef$subscribe !== void 0 - ? _fieldDef$subscribe - : exeContext.subscribeFieldResolver; - const eventStream = await resolveFn(rootValue, args, contextValue, info); + get [Symbol.toStringTag]() { + return 'GraphQLInterfaceType'; + } - if (eventStream instanceof Error) { - throw eventStream; + getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); } - return eventStream; - } catch (error) { - throw (0, _locatedError.locatedError)( - error, - fieldNodes, - (0, _Path.pathToArray)(path), - ); + return this._fields; } -} + getInterfaces() { + if (typeof this._interfaces === 'function') { + this._interfaces = this._interfaces(); + } -/***/ }), + return this._interfaces; + } -/***/ 94834: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + toConfig() { + return { + name: this.name, + description: this.description, + interfaces: this.getInterfaces(), + fields: fieldsToFieldsConfig(this.getFields()), + resolveType: this.resolveType, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + }; + } -"use strict"; + toString() { + return this.name; + } + toJSON() { + return this.toString(); + } +} -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.getArgumentValues = getArgumentValues; -exports.getDirectiveValues = getDirectiveValues; -exports.getVariableValues = getVariableValues; +exports.GraphQLInterfaceType = GraphQLInterfaceType; -var _inspect = __nccwpck_require__(10102); +/** + * Union Type Definition + * + * When a field can return one of a heterogeneous set of types, a Union type + * is used to describe what types are possible as well as providing a function + * to determine which type is actually used when the field is resolved. + * + * Example: + * + * ```ts + * const PetType = new GraphQLUnionType({ + * name: 'Pet', + * types: [ DogType, CatType ], + * resolveType(value) { + * if (value instanceof Dog) { + * return DogType; + * } + * if (value instanceof Cat) { + * return CatType; + * } + * } + * }); + * ``` + */ +class GraphQLUnionType { + constructor(config) { + var _config$extensionASTN4; -var _keyMap = __nccwpck_require__(10711); + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.resolveType = config.resolveType; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = + (_config$extensionASTN4 = config.extensionASTNodes) !== null && + _config$extensionASTN4 !== void 0 + ? _config$extensionASTN4 + : []; + this._types = defineTypes.bind(undefined, config); + config.resolveType == null || + typeof config.resolveType === 'function' || + (0, _devAssert.devAssert)( + false, + `${this.name} must provide "resolveType" as a function, ` + + `but got: ${(0, _inspect.inspect)(config.resolveType)}.`, + ); + } -var _printPathArray = __nccwpck_require__(94281); + get [Symbol.toStringTag]() { + return 'GraphQLUnionType'; + } -var _GraphQLError = __nccwpck_require__(4797); + getTypes() { + if (typeof this._types === 'function') { + this._types = this._types(); + } -var _kinds = __nccwpck_require__(11927); + return this._types; + } -var _printer = __nccwpck_require__(68203); + toConfig() { + return { + name: this.name, + description: this.description, + types: this.getTypes(), + resolveType: this.resolveType, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + }; + } -var _definition = __nccwpck_require__(32150); + toString() { + return this.name; + } -var _coerceInputValue = __nccwpck_require__(39603); + toJSON() { + return this.toString(); + } +} -var _typeFromAST = __nccwpck_require__(27664); +exports.GraphQLUnionType = GraphQLUnionType; -var _valueFromAST = __nccwpck_require__(83181); +function defineTypes(config) { + const types = resolveReadonlyArrayThunk(config.types); + Array.isArray(types) || + (0, _devAssert.devAssert)( + false, + `Must provide Array of types or a function which returns such an array for Union ${config.name}.`, + ); + return types; +} /** - * Prepares an object map of variableValues of the correct type based on the - * provided variable definitions and arbitrary input. If the input cannot be - * parsed to match the variable definitions, a GraphQLError will be thrown. + * Enum Type Definition * - * Note: The returned value is a plain Object with a prototype, since it is - * exposed to user code. Care should be taken to not pull values from the - * Object prototype. + * Some leaf values of requests and input values are Enums. GraphQL serializes + * Enum values as strings, however internally Enums can be represented by any + * kind of type, often integers. + * + * Example: + * + * ```ts + * const RGBType = new GraphQLEnumType({ + * name: 'RGB', + * values: { + * RED: { value: 0 }, + * GREEN: { value: 1 }, + * BLUE: { value: 2 } + * } + * }); + * ``` + * + * Note: If a value is not provided in a definition, the name of the enum value + * will be used as its internal value. */ -function getVariableValues(schema, varDefNodes, inputs, options) { - const errors = []; - const maxErrors = - options === null || options === void 0 ? void 0 : options.maxErrors; - - try { - const coerced = coerceVariableValues( - schema, - varDefNodes, - inputs, - (error) => { - if (maxErrors != null && errors.length >= maxErrors) { - throw new _GraphQLError.GraphQLError( - 'Too many errors processing variables, error limit reached. Execution aborted.', - ); - } - - errors.push(error); - }, - ); +class GraphQLEnumType { + /* */ + constructor(config) { + var _config$extensionASTN5; - if (errors.length === 0) { - return { - coerced, - }; - } - } catch (error) { - errors.push(error); + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = + (_config$extensionASTN5 = config.extensionASTNodes) !== null && + _config$extensionASTN5 !== void 0 + ? _config$extensionASTN5 + : []; + this._values = + typeof config.values === 'function' + ? config.values + : defineEnumValues(this.name, config.values); + this._valueLookup = null; + this._nameLookup = null; } - return { - errors, - }; -} + get [Symbol.toStringTag]() { + return 'GraphQLEnumType'; + } -function coerceVariableValues(schema, varDefNodes, inputs, onError) { - const coercedValues = {}; + getValues() { + if (typeof this._values === 'function') { + this._values = defineEnumValues(this.name, this._values()); + } - for (const varDefNode of varDefNodes) { - const varName = varDefNode.variable.name.value; - const varType = (0, _typeFromAST.typeFromAST)(schema, varDefNode.type); + return this._values; + } - if (!(0, _definition.isInputType)(varType)) { - // Must use input types for variables. This should be caught during - // validation, however is checked again here for safety. - const varTypeStr = (0, _printer.print)(varDefNode.type); - onError( - new _GraphQLError.GraphQLError( - `Variable "$${varName}" expected value of type "${varTypeStr}" which cannot be used as an input type.`, - { - nodes: varDefNode.type, - }, - ), + getValue(name) { + if (this._nameLookup === null) { + this._nameLookup = (0, _keyMap.keyMap)( + this.getValues(), + (value) => value.name, ); - continue; } - if (!hasOwnProperty(inputs, varName)) { - if (varDefNode.defaultValue) { - coercedValues[varName] = (0, _valueFromAST.valueFromAST)( - varDefNode.defaultValue, - varType, - ); - } else if ((0, _definition.isNonNullType)(varType)) { - const varTypeStr = (0, _inspect.inspect)(varType); - onError( - new _GraphQLError.GraphQLError( - `Variable "$${varName}" of required type "${varTypeStr}" was not provided.`, - { - nodes: varDefNode, - }, - ), - ); - } + return this._nameLookup[name]; + } - continue; + serialize(outputValue) { + if (this._valueLookup === null) { + this._valueLookup = new Map( + this.getValues().map((enumValue) => [enumValue.value, enumValue]), + ); } - const value = inputs[varName]; + const enumValue = this._valueLookup.get(outputValue); - if (value === null && (0, _definition.isNonNullType)(varType)) { - const varTypeStr = (0, _inspect.inspect)(varType); - onError( - new _GraphQLError.GraphQLError( - `Variable "$${varName}" of non-null type "${varTypeStr}" must not be null.`, - { - nodes: varDefNode, - }, - ), + if (enumValue === undefined) { + throw new _GraphQLError.GraphQLError( + `Enum "${this.name}" cannot represent value: ${(0, _inspect.inspect)( + outputValue, + )}`, ); - continue; } - coercedValues[varName] = (0, _coerceInputValue.coerceInputValue)( - value, - varType, - (path, invalidValue, error) => { - let prefix = - `Variable "$${varName}" got invalid value ` + - (0, _inspect.inspect)(invalidValue); - - if (path.length > 0) { - prefix += ` at "${varName}${(0, _printPathArray.printPathArray)( - path, - )}"`; - } - - onError( - new _GraphQLError.GraphQLError(prefix + '; ' + error.message, { - nodes: varDefNode, - originalError: error, - }), - ); - }, - ); + return enumValue.name; } - return coercedValues; -} -/** - * Prepares an object map of argument values given a list of argument - * definitions and list of argument AST nodes. - * - * Note: The returned value is a plain Object with a prototype, since it is - * exposed to user code. Care should be taken to not pull values from the - * Object prototype. - */ - -function getArgumentValues(def, node, variableValues) { - var _node$arguments; - - const coercedValues = {}; // FIXME: https://github.com/graphql/graphql-js/issues/2203 - - /* c8 ignore next */ - - const argumentNodes = - (_node$arguments = node.arguments) !== null && _node$arguments !== void 0 - ? _node$arguments - : []; - const argNodeMap = (0, _keyMap.keyMap)( - argumentNodes, - (arg) => arg.name.value, - ); - - for (const argDef of def.args) { - const name = argDef.name; - const argType = argDef.type; - const argumentNode = argNodeMap[name]; - - if (!argumentNode) { - if (argDef.defaultValue !== undefined) { - coercedValues[name] = argDef.defaultValue; - } else if ((0, _definition.isNonNullType)(argType)) { - throw new _GraphQLError.GraphQLError( - `Argument "${name}" of required type "${(0, _inspect.inspect)( - argType, - )}" ` + 'was not provided.', - { - nodes: node, - }, - ); - } - - continue; + parseValue(inputValue) /* T */ + { + if (typeof inputValue !== 'string') { + const valueStr = (0, _inspect.inspect)(inputValue); + throw new _GraphQLError.GraphQLError( + `Enum "${this.name}" cannot represent non-string value: ${valueStr}.` + + didYouMeanEnumValue(this, valueStr), + ); } - const valueNode = argumentNode.value; - let isNull = valueNode.kind === _kinds.Kind.NULL; - - if (valueNode.kind === _kinds.Kind.VARIABLE) { - const variableName = valueNode.name.value; - - if ( - variableValues == null || - !hasOwnProperty(variableValues, variableName) - ) { - if (argDef.defaultValue !== undefined) { - coercedValues[name] = argDef.defaultValue; - } else if ((0, _definition.isNonNullType)(argType)) { - throw new _GraphQLError.GraphQLError( - `Argument "${name}" of required type "${(0, _inspect.inspect)( - argType, - )}" ` + - `was provided the variable "$${variableName}" which was not provided a runtime value.`, - { - nodes: valueNode, - }, - ); - } - - continue; - } + const enumValue = this.getValue(inputValue); - isNull = variableValues[variableName] == null; + if (enumValue == null) { + throw new _GraphQLError.GraphQLError( + `Value "${inputValue}" does not exist in "${this.name}" enum.` + + didYouMeanEnumValue(this, inputValue), + ); } - if (isNull && (0, _definition.isNonNullType)(argType)) { + return enumValue.value; + } + + parseLiteral(valueNode, _variables) /* T */ + { + // Note: variables will be resolved to a value before calling this function. + if (valueNode.kind !== _kinds.Kind.ENUM) { + const valueStr = (0, _printer.print)(valueNode); throw new _GraphQLError.GraphQLError( - `Argument "${name}" of non-null type "${(0, _inspect.inspect)( - argType, - )}" ` + 'must not be null.', + `Enum "${this.name}" cannot represent non-enum value: ${valueStr}.` + + didYouMeanEnumValue(this, valueStr), { nodes: valueNode, }, ); } - const coercedValue = (0, _valueFromAST.valueFromAST)( - valueNode, - argType, - variableValues, - ); + const enumValue = this.getValue(valueNode.value); - if (coercedValue === undefined) { - // Note: ValuesOfCorrectTypeRule validation should catch this before - // execution. This is a runtime check to ensure execution does not - // continue with an invalid argument value. + if (enumValue == null) { + const valueStr = (0, _printer.print)(valueNode); throw new _GraphQLError.GraphQLError( - `Argument "${name}" has invalid value ${(0, _printer.print)( - valueNode, - )}.`, + `Value "${valueStr}" does not exist in "${this.name}" enum.` + + didYouMeanEnumValue(this, valueStr), { nodes: valueNode, }, ); } - coercedValues[name] = coercedValue; + return enumValue.value; } - return coercedValues; + toConfig() { + const values = (0, _keyValMap.keyValMap)( + this.getValues(), + (value) => value.name, + (value) => ({ + description: value.description, + value: value.value, + deprecationReason: value.deprecationReason, + extensions: value.extensions, + astNode: value.astNode, + }), + ); + return { + name: this.name, + description: this.description, + values, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + }; + } + + toString() { + return this.name; + } + + toJSON() { + return this.toString(); + } +} + +exports.GraphQLEnumType = GraphQLEnumType; + +function didYouMeanEnumValue(enumType, unknownValueStr) { + const allNames = enumType.getValues().map((value) => value.name); + const suggestedValues = (0, _suggestionList.suggestionList)( + unknownValueStr, + allNames, + ); + return (0, _didYouMean.didYouMean)('the enum value', suggestedValues); +} + +function defineEnumValues(typeName, valueMap) { + isPlainObj(valueMap) || + (0, _devAssert.devAssert)( + false, + `${typeName} values must be an object with value names as keys.`, + ); + return Object.entries(valueMap).map(([valueName, valueConfig]) => { + isPlainObj(valueConfig) || + (0, _devAssert.devAssert)( + false, + `${typeName}.${valueName} must refer to an object with a "value" key ` + + `representing an internal value but got: ${(0, _inspect.inspect)( + valueConfig, + )}.`, + ); + return { + name: (0, _assertName.assertEnumValueName)(valueName), + description: valueConfig.description, + value: valueConfig.value !== undefined ? valueConfig.value : valueName, + deprecationReason: valueConfig.deprecationReason, + extensions: (0, _toObjMap.toObjMap)(valueConfig.extensions), + astNode: valueConfig.astNode, + }; + }); } + /** - * Prepares an object map of argument values given a directive definition - * and a AST node which may contain directives. Optionally also accepts a map - * of variable values. + * Input Object Type Definition * - * If the directive does not exist on the node, returns undefined. + * An input object defines a structured collection of fields which may be + * supplied to a field argument. * - * Note: The returned value is a plain Object with a prototype, since it is - * exposed to user code. Care should be taken to not pull values from the - * Object prototype. + * Using `NonNull` will ensure that a value must be provided by the query + * + * Example: + * + * ```ts + * const GeoPoint = new GraphQLInputObjectType({ + * name: 'GeoPoint', + * fields: { + * lat: { type: new GraphQLNonNull(GraphQLFloat) }, + * lon: { type: new GraphQLNonNull(GraphQLFloat) }, + * alt: { type: GraphQLFloat, defaultValue: 0 }, + * } + * }); + * ``` */ +class GraphQLInputObjectType { + constructor(config) { + var _config$extensionASTN6, _config$isOneOf; -function getDirectiveValues(directiveDef, node, variableValues) { - var _node$directives; + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = + (_config$extensionASTN6 = config.extensionASTNodes) !== null && + _config$extensionASTN6 !== void 0 + ? _config$extensionASTN6 + : []; + this.isOneOf = + (_config$isOneOf = config.isOneOf) !== null && _config$isOneOf !== void 0 + ? _config$isOneOf + : false; + this._fields = defineInputFieldMap.bind(undefined, config); + } - const directiveNode = - (_node$directives = node.directives) === null || _node$directives === void 0 - ? void 0 - : _node$directives.find( - (directive) => directive.name.value === directiveDef.name, - ); + get [Symbol.toStringTag]() { + return 'GraphQLInputObjectType'; + } - if (directiveNode) { - return getArgumentValues(directiveDef, directiveNode, variableValues); + getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + + return this._fields; + } + + toConfig() { + const fields = (0, _mapValue.mapValue)(this.getFields(), (field) => ({ + description: field.description, + type: field.type, + defaultValue: field.defaultValue, + deprecationReason: field.deprecationReason, + extensions: field.extensions, + astNode: field.astNode, + })); + return { + name: this.name, + description: this.description, + fields, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + isOneOf: this.isOneOf, + }; + } + + toString() { + return this.name; + } + + toJSON() { + return this.toString(); } } -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); +exports.GraphQLInputObjectType = GraphQLInputObjectType; + +function defineInputFieldMap(config) { + const fieldMap = resolveObjMapThunk(config.fields); + isPlainObj(fieldMap) || + (0, _devAssert.devAssert)( + false, + `${config.name} fields must be an object with field names as keys or a function which returns such an object.`, + ); + return (0, _mapValue.mapValue)(fieldMap, (fieldConfig, fieldName) => { + !('resolve' in fieldConfig) || + (0, _devAssert.devAssert)( + false, + `${config.name}.${fieldName} field has a resolve property, but Input Types cannot define resolvers.`, + ); + return { + name: (0, _assertName.assertName)(fieldName), + description: fieldConfig.description, + type: fieldConfig.type, + defaultValue: fieldConfig.defaultValue, + deprecationReason: fieldConfig.deprecationReason, + extensions: (0, _toObjMap.toObjMap)(fieldConfig.extensions), + astNode: fieldConfig.astNode, + }; + }); +} + +function isRequiredInputField(field) { + return isNonNullType(field.type) && field.defaultValue === undefined; } /***/ }), -/***/ 64215: +/***/ 83614: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -278045,1398 +277606,3425 @@ function hasOwnProperty(obj, prop) { Object.defineProperty(exports, "__esModule", ({ value: true, })); -exports.graphql = graphql; -exports.graphqlSync = graphqlSync; +exports.GraphQLSpecifiedByDirective = + exports.GraphQLSkipDirective = + exports.GraphQLOneOfDirective = + exports.GraphQLIncludeDirective = + exports.GraphQLDirective = + exports.GraphQLDeprecatedDirective = + exports.DEFAULT_DEPRECATION_REASON = + void 0; +exports.assertDirective = assertDirective; +exports.isDirective = isDirective; +exports.isSpecifiedDirective = isSpecifiedDirective; +exports.specifiedDirectives = void 0; var _devAssert = __nccwpck_require__(46514); -var _isPromise = __nccwpck_require__(93910); +var _inspect = __nccwpck_require__(10102); -var _parser = __nccwpck_require__(50655); +var _instanceOf = __nccwpck_require__(93481); -var _validate = __nccwpck_require__(22430); +var _isObjectLike = __nccwpck_require__(95865); -var _validate2 = __nccwpck_require__(14193); +var _toObjMap = __nccwpck_require__(74728); -var _execute = __nccwpck_require__(83677); +var _directiveLocation = __nccwpck_require__(71553); -function graphql(args) { - // Always return a Promise for a consistent API. - return new Promise((resolve) => resolve(graphqlImpl(args))); -} -/** - * The graphqlSync function also fulfills GraphQL operations by parsing, - * validating, and executing a GraphQL document along side a GraphQL schema. - * However, it guarantees to complete synchronously (or throw an error) assuming - * that all field resolvers are also synchronous. - */ +var _assertName = __nccwpck_require__(74947); -function graphqlSync(args) { - const result = graphqlImpl(args); // Assert that the execution was synchronous. +var _definition = __nccwpck_require__(32150); - if ((0, _isPromise.isPromise)(result)) { - throw new Error('GraphQL execution failed to complete synchronously.'); - } +var _scalars = __nccwpck_require__(93145); - return result; +/** + * Test if the given value is a GraphQL directive. + */ +function isDirective(directive) { + return (0, _instanceOf.instanceOf)(directive, GraphQLDirective); } -function graphqlImpl(args) { - // Temporary for v15 to v16 migration. Remove in v17 - arguments.length < 2 || - (0, _devAssert.devAssert)( - false, - 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.', +function assertDirective(directive) { + if (!isDirective(directive)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(directive)} to be a GraphQL directive.`, ); - const { - schema, - source, - rootValue, - contextValue, - variableValues, - operationName, - fieldResolver, - typeResolver, - } = args; // Validate Schema - - const schemaValidationErrors = (0, _validate.validateSchema)(schema); + } - if (schemaValidationErrors.length > 0) { - return { - errors: schemaValidationErrors, - }; - } // Parse + return directive; +} +/** + * Custom extensions + * + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ - let document; +/** + * Directives are used by the GraphQL runtime as a way of modifying execution + * behavior. Type system creators will usually not create these directly. + */ +class GraphQLDirective { + constructor(config) { + var _config$isRepeatable, _config$args; - try { - document = (0, _parser.parse)(source); - } catch (syntaxError) { - return { - errors: [syntaxError], - }; - } // Validate + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.locations = config.locations; + this.isRepeatable = + (_config$isRepeatable = config.isRepeatable) !== null && + _config$isRepeatable !== void 0 + ? _config$isRepeatable + : false; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + Array.isArray(config.locations) || + (0, _devAssert.devAssert)( + false, + `@${config.name} locations must be an Array.`, + ); + const args = + (_config$args = config.args) !== null && _config$args !== void 0 + ? _config$args + : {}; + ((0, _isObjectLike.isObjectLike)(args) && !Array.isArray(args)) || + (0, _devAssert.devAssert)( + false, + `@${config.name} args must be an object with argument names as keys.`, + ); + this.args = (0, _definition.defineArguments)(args); + } - const validationErrors = (0, _validate2.validate)(schema, document); + get [Symbol.toStringTag]() { + return 'GraphQLDirective'; + } - if (validationErrors.length > 0) { + toConfig() { return { - errors: validationErrors, + name: this.name, + description: this.description, + locations: this.locations, + args: (0, _definition.argsToArgsConfig)(this.args), + isRepeatable: this.isRepeatable, + extensions: this.extensions, + astNode: this.astNode, }; - } // Execute + } - return (0, _execute.execute)({ - schema, - document, - rootValue, - contextValue, - variableValues, - operationName, - fieldResolver, - typeResolver, - }); -} + toString() { + return '@' + this.name; + } + toJSON() { + return this.toString(); + } +} -/***/ }), +exports.GraphQLDirective = GraphQLDirective; -/***/ 16155: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/** + * Used to conditionally include fields or fragments. + */ +const GraphQLIncludeDirective = new GraphQLDirective({ + name: 'include', + description: + 'Directs the executor to include this field or fragment only when the `if` argument is true.', + locations: [ + _directiveLocation.DirectiveLocation.FIELD, + _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, + _directiveLocation.DirectiveLocation.INLINE_FRAGMENT, + ], + args: { + if: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + description: 'Included when true.', + }, + }, +}); +/** + * Used to conditionally skip (exclude) fields or fragments. + */ -"use strict"; +exports.GraphQLIncludeDirective = GraphQLIncludeDirective; +const GraphQLSkipDirective = new GraphQLDirective({ + name: 'skip', + description: + 'Directs the executor to skip this field or fragment when the `if` argument is true.', + locations: [ + _directiveLocation.DirectiveLocation.FIELD, + _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, + _directiveLocation.DirectiveLocation.INLINE_FRAGMENT, + ], + args: { + if: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + description: 'Skipped when true.', + }, + }, +}); +/** + * Constant string used for default reason for a deprecation. + */ +exports.GraphQLSkipDirective = GraphQLSkipDirective; +const DEFAULT_DEPRECATION_REASON = 'No longer supported'; +/** + * Used to declare element of a GraphQL schema as deprecated. + */ -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -Object.defineProperty(exports, "BREAK", ({ - enumerable: true, - get: function () { - return _index2.BREAK; - }, -})); -Object.defineProperty(exports, "BreakingChangeType", ({ - enumerable: true, - get: function () { - return _index6.BreakingChangeType; - }, -})); -Object.defineProperty(exports, "DEFAULT_DEPRECATION_REASON", ({ - enumerable: true, - get: function () { - return _index.DEFAULT_DEPRECATION_REASON; - }, -})); -Object.defineProperty(exports, "DangerousChangeType", ({ - enumerable: true, - get: function () { - return _index6.DangerousChangeType; - }, -})); -Object.defineProperty(exports, "DirectiveLocation", ({ - enumerable: true, - get: function () { - return _index2.DirectiveLocation; - }, -})); -Object.defineProperty(exports, "ExecutableDefinitionsRule", ({ - enumerable: true, - get: function () { - return _index4.ExecutableDefinitionsRule; +exports.DEFAULT_DEPRECATION_REASON = DEFAULT_DEPRECATION_REASON; +const GraphQLDeprecatedDirective = new GraphQLDirective({ + name: 'deprecated', + description: 'Marks an element of a GraphQL schema as no longer supported.', + locations: [ + _directiveLocation.DirectiveLocation.FIELD_DEFINITION, + _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION, + _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION, + _directiveLocation.DirectiveLocation.ENUM_VALUE, + ], + args: { + reason: { + type: _scalars.GraphQLString, + description: + 'Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted using the Markdown syntax, as specified by [CommonMark](https://commonmark.org/).', + defaultValue: DEFAULT_DEPRECATION_REASON, + }, }, -})); -Object.defineProperty(exports, "FieldsOnCorrectTypeRule", ({ - enumerable: true, - get: function () { - return _index4.FieldsOnCorrectTypeRule; +}); +/** + * Used to provide a URL for specifying the behavior of custom scalar definitions. + */ + +exports.GraphQLDeprecatedDirective = GraphQLDeprecatedDirective; +const GraphQLSpecifiedByDirective = new GraphQLDirective({ + name: 'specifiedBy', + description: 'Exposes a URL that specifies the behavior of this scalar.', + locations: [_directiveLocation.DirectiveLocation.SCALAR], + args: { + url: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + description: 'The URL that specifies the behavior of this scalar.', + }, }, +}); +/** + * Used to indicate an Input Object is a OneOf Input Object. + */ + +exports.GraphQLSpecifiedByDirective = GraphQLSpecifiedByDirective; +const GraphQLOneOfDirective = new GraphQLDirective({ + name: 'oneOf', + description: + 'Indicates exactly one field must be supplied and this field must not be `null`.', + locations: [_directiveLocation.DirectiveLocation.INPUT_OBJECT], + args: {}, +}); +/** + * The full list of specified directives. + */ + +exports.GraphQLOneOfDirective = GraphQLOneOfDirective; +const specifiedDirectives = Object.freeze([ + GraphQLIncludeDirective, + GraphQLSkipDirective, + GraphQLDeprecatedDirective, + GraphQLSpecifiedByDirective, + GraphQLOneOfDirective, +]); +exports.specifiedDirectives = specifiedDirectives; + +function isSpecifiedDirective(directive) { + return specifiedDirectives.some(({ name }) => name === directive.name); +} + + +/***/ }), + +/***/ 63280: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, })); -Object.defineProperty(exports, "FragmentsOnCompositeTypesRule", ({ +Object.defineProperty(exports, "DEFAULT_DEPRECATION_REASON", ({ enumerable: true, get: function () { - return _index4.FragmentsOnCompositeTypesRule; + return _directives.DEFAULT_DEPRECATION_REASON; }, })); Object.defineProperty(exports, "GRAPHQL_MAX_INT", ({ enumerable: true, get: function () { - return _index.GRAPHQL_MAX_INT; + return _scalars.GRAPHQL_MAX_INT; }, })); Object.defineProperty(exports, "GRAPHQL_MIN_INT", ({ enumerable: true, get: function () { - return _index.GRAPHQL_MIN_INT; + return _scalars.GRAPHQL_MIN_INT; }, })); Object.defineProperty(exports, "GraphQLBoolean", ({ enumerable: true, get: function () { - return _index.GraphQLBoolean; + return _scalars.GraphQLBoolean; }, })); Object.defineProperty(exports, "GraphQLDeprecatedDirective", ({ enumerable: true, get: function () { - return _index.GraphQLDeprecatedDirective; + return _directives.GraphQLDeprecatedDirective; }, })); Object.defineProperty(exports, "GraphQLDirective", ({ enumerable: true, get: function () { - return _index.GraphQLDirective; + return _directives.GraphQLDirective; }, })); Object.defineProperty(exports, "GraphQLEnumType", ({ enumerable: true, get: function () { - return _index.GraphQLEnumType; - }, -})); -Object.defineProperty(exports, "GraphQLError", ({ - enumerable: true, - get: function () { - return _index5.GraphQLError; + return _definition.GraphQLEnumType; }, })); Object.defineProperty(exports, "GraphQLFloat", ({ enumerable: true, get: function () { - return _index.GraphQLFloat; + return _scalars.GraphQLFloat; }, })); Object.defineProperty(exports, "GraphQLID", ({ enumerable: true, get: function () { - return _index.GraphQLID; + return _scalars.GraphQLID; }, })); Object.defineProperty(exports, "GraphQLIncludeDirective", ({ enumerable: true, get: function () { - return _index.GraphQLIncludeDirective; + return _directives.GraphQLIncludeDirective; }, })); Object.defineProperty(exports, "GraphQLInputObjectType", ({ enumerable: true, get: function () { - return _index.GraphQLInputObjectType; + return _definition.GraphQLInputObjectType; }, })); Object.defineProperty(exports, "GraphQLInt", ({ enumerable: true, get: function () { - return _index.GraphQLInt; + return _scalars.GraphQLInt; }, })); Object.defineProperty(exports, "GraphQLInterfaceType", ({ enumerable: true, get: function () { - return _index.GraphQLInterfaceType; + return _definition.GraphQLInterfaceType; }, })); Object.defineProperty(exports, "GraphQLList", ({ enumerable: true, get: function () { - return _index.GraphQLList; + return _definition.GraphQLList; }, })); Object.defineProperty(exports, "GraphQLNonNull", ({ enumerable: true, get: function () { - return _index.GraphQLNonNull; + return _definition.GraphQLNonNull; }, })); Object.defineProperty(exports, "GraphQLObjectType", ({ enumerable: true, get: function () { - return _index.GraphQLObjectType; + return _definition.GraphQLObjectType; }, })); Object.defineProperty(exports, "GraphQLOneOfDirective", ({ enumerable: true, get: function () { - return _index.GraphQLOneOfDirective; + return _directives.GraphQLOneOfDirective; }, })); Object.defineProperty(exports, "GraphQLScalarType", ({ enumerable: true, get: function () { - return _index.GraphQLScalarType; + return _definition.GraphQLScalarType; }, })); Object.defineProperty(exports, "GraphQLSchema", ({ enumerable: true, get: function () { - return _index.GraphQLSchema; + return _schema.GraphQLSchema; }, })); Object.defineProperty(exports, "GraphQLSkipDirective", ({ enumerable: true, get: function () { - return _index.GraphQLSkipDirective; + return _directives.GraphQLSkipDirective; }, })); Object.defineProperty(exports, "GraphQLSpecifiedByDirective", ({ enumerable: true, get: function () { - return _index.GraphQLSpecifiedByDirective; + return _directives.GraphQLSpecifiedByDirective; }, })); Object.defineProperty(exports, "GraphQLString", ({ enumerable: true, get: function () { - return _index.GraphQLString; + return _scalars.GraphQLString; }, })); Object.defineProperty(exports, "GraphQLUnionType", ({ enumerable: true, get: function () { - return _index.GraphQLUnionType; - }, -})); -Object.defineProperty(exports, "Kind", ({ - enumerable: true, - get: function () { - return _index2.Kind; - }, -})); -Object.defineProperty(exports, "KnownArgumentNamesRule", ({ - enumerable: true, - get: function () { - return _index4.KnownArgumentNamesRule; - }, -})); -Object.defineProperty(exports, "KnownDirectivesRule", ({ - enumerable: true, - get: function () { - return _index4.KnownDirectivesRule; - }, -})); -Object.defineProperty(exports, "KnownFragmentNamesRule", ({ - enumerable: true, - get: function () { - return _index4.KnownFragmentNamesRule; - }, -})); -Object.defineProperty(exports, "KnownTypeNamesRule", ({ - enumerable: true, - get: function () { - return _index4.KnownTypeNamesRule; - }, -})); -Object.defineProperty(exports, "Lexer", ({ - enumerable: true, - get: function () { - return _index2.Lexer; - }, -})); -Object.defineProperty(exports, "Location", ({ - enumerable: true, - get: function () { - return _index2.Location; - }, -})); -Object.defineProperty(exports, "LoneAnonymousOperationRule", ({ - enumerable: true, - get: function () { - return _index4.LoneAnonymousOperationRule; - }, -})); -Object.defineProperty(exports, "LoneSchemaDefinitionRule", ({ - enumerable: true, - get: function () { - return _index4.LoneSchemaDefinitionRule; - }, -})); -Object.defineProperty(exports, "MaxIntrospectionDepthRule", ({ - enumerable: true, - get: function () { - return _index4.MaxIntrospectionDepthRule; - }, -})); -Object.defineProperty(exports, "NoDeprecatedCustomRule", ({ - enumerable: true, - get: function () { - return _index4.NoDeprecatedCustomRule; - }, -})); -Object.defineProperty(exports, "NoFragmentCyclesRule", ({ - enumerable: true, - get: function () { - return _index4.NoFragmentCyclesRule; - }, -})); -Object.defineProperty(exports, "NoSchemaIntrospectionCustomRule", ({ - enumerable: true, - get: function () { - return _index4.NoSchemaIntrospectionCustomRule; - }, -})); -Object.defineProperty(exports, "NoUndefinedVariablesRule", ({ - enumerable: true, - get: function () { - return _index4.NoUndefinedVariablesRule; - }, -})); -Object.defineProperty(exports, "NoUnusedFragmentsRule", ({ - enumerable: true, - get: function () { - return _index4.NoUnusedFragmentsRule; - }, -})); -Object.defineProperty(exports, "NoUnusedVariablesRule", ({ - enumerable: true, - get: function () { - return _index4.NoUnusedVariablesRule; - }, -})); -Object.defineProperty(exports, "OperationTypeNode", ({ - enumerable: true, - get: function () { - return _index2.OperationTypeNode; - }, -})); -Object.defineProperty(exports, "OverlappingFieldsCanBeMergedRule", ({ - enumerable: true, - get: function () { - return _index4.OverlappingFieldsCanBeMergedRule; - }, -})); -Object.defineProperty(exports, "PossibleFragmentSpreadsRule", ({ - enumerable: true, - get: function () { - return _index4.PossibleFragmentSpreadsRule; - }, -})); -Object.defineProperty(exports, "PossibleTypeExtensionsRule", ({ - enumerable: true, - get: function () { - return _index4.PossibleTypeExtensionsRule; - }, -})); -Object.defineProperty(exports, "ProvidedRequiredArgumentsRule", ({ - enumerable: true, - get: function () { - return _index4.ProvidedRequiredArgumentsRule; - }, -})); -Object.defineProperty(exports, "ScalarLeafsRule", ({ - enumerable: true, - get: function () { - return _index4.ScalarLeafsRule; + return _definition.GraphQLUnionType; }, })); Object.defineProperty(exports, "SchemaMetaFieldDef", ({ enumerable: true, get: function () { - return _index.SchemaMetaFieldDef; - }, -})); -Object.defineProperty(exports, "SingleFieldSubscriptionsRule", ({ - enumerable: true, - get: function () { - return _index4.SingleFieldSubscriptionsRule; - }, -})); -Object.defineProperty(exports, "Source", ({ - enumerable: true, - get: function () { - return _index2.Source; - }, -})); -Object.defineProperty(exports, "Token", ({ - enumerable: true, - get: function () { - return _index2.Token; - }, -})); -Object.defineProperty(exports, "TokenKind", ({ - enumerable: true, - get: function () { - return _index2.TokenKind; - }, -})); -Object.defineProperty(exports, "TypeInfo", ({ - enumerable: true, - get: function () { - return _index6.TypeInfo; + return _introspection.SchemaMetaFieldDef; }, })); Object.defineProperty(exports, "TypeKind", ({ enumerable: true, get: function () { - return _index.TypeKind; + return _introspection.TypeKind; }, })); Object.defineProperty(exports, "TypeMetaFieldDef", ({ enumerable: true, get: function () { - return _index.TypeMetaFieldDef; + return _introspection.TypeMetaFieldDef; }, })); Object.defineProperty(exports, "TypeNameMetaFieldDef", ({ enumerable: true, get: function () { - return _index.TypeNameMetaFieldDef; - }, -})); -Object.defineProperty(exports, "UniqueArgumentDefinitionNamesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueArgumentDefinitionNamesRule; - }, -})); -Object.defineProperty(exports, "UniqueArgumentNamesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueArgumentNamesRule; - }, -})); -Object.defineProperty(exports, "UniqueDirectiveNamesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueDirectiveNamesRule; - }, -})); -Object.defineProperty(exports, "UniqueDirectivesPerLocationRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueDirectivesPerLocationRule; - }, -})); -Object.defineProperty(exports, "UniqueEnumValueNamesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueEnumValueNamesRule; - }, -})); -Object.defineProperty(exports, "UniqueFieldDefinitionNamesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueFieldDefinitionNamesRule; - }, -})); -Object.defineProperty(exports, "UniqueFragmentNamesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueFragmentNamesRule; - }, -})); -Object.defineProperty(exports, "UniqueInputFieldNamesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueInputFieldNamesRule; - }, -})); -Object.defineProperty(exports, "UniqueOperationNamesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueOperationNamesRule; - }, -})); -Object.defineProperty(exports, "UniqueOperationTypesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueOperationTypesRule; - }, -})); -Object.defineProperty(exports, "UniqueTypeNamesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueTypeNamesRule; - }, -})); -Object.defineProperty(exports, "UniqueVariableNamesRule", ({ - enumerable: true, - get: function () { - return _index4.UniqueVariableNamesRule; - }, -})); -Object.defineProperty(exports, "ValidationContext", ({ - enumerable: true, - get: function () { - return _index4.ValidationContext; - }, -})); -Object.defineProperty(exports, "ValuesOfCorrectTypeRule", ({ - enumerable: true, - get: function () { - return _index4.ValuesOfCorrectTypeRule; - }, -})); -Object.defineProperty(exports, "VariablesAreInputTypesRule", ({ - enumerable: true, - get: function () { - return _index4.VariablesAreInputTypesRule; - }, -})); -Object.defineProperty(exports, "VariablesInAllowedPositionRule", ({ - enumerable: true, - get: function () { - return _index4.VariablesInAllowedPositionRule; + return _introspection.TypeNameMetaFieldDef; }, })); Object.defineProperty(exports, "__Directive", ({ enumerable: true, get: function () { - return _index.__Directive; + return _introspection.__Directive; }, })); Object.defineProperty(exports, "__DirectiveLocation", ({ enumerable: true, get: function () { - return _index.__DirectiveLocation; + return _introspection.__DirectiveLocation; }, })); Object.defineProperty(exports, "__EnumValue", ({ enumerable: true, get: function () { - return _index.__EnumValue; + return _introspection.__EnumValue; }, })); Object.defineProperty(exports, "__Field", ({ enumerable: true, get: function () { - return _index.__Field; + return _introspection.__Field; }, })); Object.defineProperty(exports, "__InputValue", ({ enumerable: true, get: function () { - return _index.__InputValue; + return _introspection.__InputValue; }, })); Object.defineProperty(exports, "__Schema", ({ enumerable: true, get: function () { - return _index.__Schema; + return _introspection.__Schema; }, })); Object.defineProperty(exports, "__Type", ({ enumerable: true, get: function () { - return _index.__Type; + return _introspection.__Type; }, })); Object.defineProperty(exports, "__TypeKind", ({ enumerable: true, get: function () { - return _index.__TypeKind; + return _introspection.__TypeKind; }, })); Object.defineProperty(exports, "assertAbstractType", ({ enumerable: true, get: function () { - return _index.assertAbstractType; + return _definition.assertAbstractType; }, })); Object.defineProperty(exports, "assertCompositeType", ({ enumerable: true, get: function () { - return _index.assertCompositeType; + return _definition.assertCompositeType; }, })); Object.defineProperty(exports, "assertDirective", ({ enumerable: true, get: function () { - return _index.assertDirective; + return _directives.assertDirective; }, })); Object.defineProperty(exports, "assertEnumType", ({ enumerable: true, get: function () { - return _index.assertEnumType; + return _definition.assertEnumType; }, })); Object.defineProperty(exports, "assertEnumValueName", ({ enumerable: true, get: function () { - return _index.assertEnumValueName; + return _assertName.assertEnumValueName; }, })); Object.defineProperty(exports, "assertInputObjectType", ({ enumerable: true, get: function () { - return _index.assertInputObjectType; + return _definition.assertInputObjectType; }, })); Object.defineProperty(exports, "assertInputType", ({ enumerable: true, get: function () { - return _index.assertInputType; + return _definition.assertInputType; }, })); Object.defineProperty(exports, "assertInterfaceType", ({ enumerable: true, get: function () { - return _index.assertInterfaceType; + return _definition.assertInterfaceType; }, })); Object.defineProperty(exports, "assertLeafType", ({ enumerable: true, get: function () { - return _index.assertLeafType; + return _definition.assertLeafType; }, })); Object.defineProperty(exports, "assertListType", ({ enumerable: true, get: function () { - return _index.assertListType; + return _definition.assertListType; }, })); Object.defineProperty(exports, "assertName", ({ enumerable: true, get: function () { - return _index.assertName; + return _assertName.assertName; }, })); Object.defineProperty(exports, "assertNamedType", ({ enumerable: true, get: function () { - return _index.assertNamedType; + return _definition.assertNamedType; }, })); Object.defineProperty(exports, "assertNonNullType", ({ enumerable: true, get: function () { - return _index.assertNonNullType; + return _definition.assertNonNullType; }, })); Object.defineProperty(exports, "assertNullableType", ({ enumerable: true, get: function () { - return _index.assertNullableType; + return _definition.assertNullableType; }, })); Object.defineProperty(exports, "assertObjectType", ({ enumerable: true, get: function () { - return _index.assertObjectType; + return _definition.assertObjectType; }, })); Object.defineProperty(exports, "assertOutputType", ({ enumerable: true, get: function () { - return _index.assertOutputType; + return _definition.assertOutputType; }, })); Object.defineProperty(exports, "assertScalarType", ({ enumerable: true, get: function () { - return _index.assertScalarType; + return _definition.assertScalarType; }, })); Object.defineProperty(exports, "assertSchema", ({ enumerable: true, get: function () { - return _index.assertSchema; + return _schema.assertSchema; }, })); Object.defineProperty(exports, "assertType", ({ enumerable: true, get: function () { - return _index.assertType; + return _definition.assertType; }, })); Object.defineProperty(exports, "assertUnionType", ({ enumerable: true, get: function () { - return _index.assertUnionType; - }, -})); -Object.defineProperty(exports, "assertValidName", ({ - enumerable: true, - get: function () { - return _index6.assertValidName; + return _definition.assertUnionType; }, })); Object.defineProperty(exports, "assertValidSchema", ({ enumerable: true, get: function () { - return _index.assertValidSchema; + return _validate.assertValidSchema; }, })); Object.defineProperty(exports, "assertWrappingType", ({ enumerable: true, get: function () { - return _index.assertWrappingType; - }, -})); -Object.defineProperty(exports, "astFromValue", ({ - enumerable: true, - get: function () { - return _index6.astFromValue; - }, -})); -Object.defineProperty(exports, "buildASTSchema", ({ - enumerable: true, - get: function () { - return _index6.buildASTSchema; - }, -})); -Object.defineProperty(exports, "buildClientSchema", ({ - enumerable: true, - get: function () { - return _index6.buildClientSchema; - }, -})); -Object.defineProperty(exports, "buildSchema", ({ - enumerable: true, - get: function () { - return _index6.buildSchema; - }, -})); -Object.defineProperty(exports, "coerceInputValue", ({ - enumerable: true, - get: function () { - return _index6.coerceInputValue; - }, -})); -Object.defineProperty(exports, "concatAST", ({ - enumerable: true, - get: function () { - return _index6.concatAST; - }, -})); -Object.defineProperty(exports, "createSourceEventStream", ({ - enumerable: true, - get: function () { - return _index3.createSourceEventStream; - }, -})); -Object.defineProperty(exports, "defaultFieldResolver", ({ - enumerable: true, - get: function () { - return _index3.defaultFieldResolver; - }, -})); -Object.defineProperty(exports, "defaultTypeResolver", ({ - enumerable: true, - get: function () { - return _index3.defaultTypeResolver; - }, -})); -Object.defineProperty(exports, "doTypesOverlap", ({ - enumerable: true, - get: function () { - return _index6.doTypesOverlap; - }, -})); -Object.defineProperty(exports, "execute", ({ - enumerable: true, - get: function () { - return _index3.execute; - }, -})); -Object.defineProperty(exports, "executeSync", ({ - enumerable: true, - get: function () { - return _index3.executeSync; - }, -})); -Object.defineProperty(exports, "extendSchema", ({ - enumerable: true, - get: function () { - return _index6.extendSchema; - }, -})); -Object.defineProperty(exports, "findBreakingChanges", ({ - enumerable: true, - get: function () { - return _index6.findBreakingChanges; - }, -})); -Object.defineProperty(exports, "findDangerousChanges", ({ - enumerable: true, - get: function () { - return _index6.findDangerousChanges; - }, -})); -Object.defineProperty(exports, "formatError", ({ - enumerable: true, - get: function () { - return _index5.formatError; - }, -})); -Object.defineProperty(exports, "getArgumentValues", ({ - enumerable: true, - get: function () { - return _index3.getArgumentValues; - }, -})); -Object.defineProperty(exports, "getDirectiveValues", ({ - enumerable: true, - get: function () { - return _index3.getDirectiveValues; - }, -})); -Object.defineProperty(exports, "getEnterLeaveForKind", ({ - enumerable: true, - get: function () { - return _index2.getEnterLeaveForKind; - }, -})); -Object.defineProperty(exports, "getIntrospectionQuery", ({ - enumerable: true, - get: function () { - return _index6.getIntrospectionQuery; - }, -})); -Object.defineProperty(exports, "getLocation", ({ - enumerable: true, - get: function () { - return _index2.getLocation; + return _definition.assertWrappingType; }, })); Object.defineProperty(exports, "getNamedType", ({ enumerable: true, get: function () { - return _index.getNamedType; + return _definition.getNamedType; }, })); Object.defineProperty(exports, "getNullableType", ({ enumerable: true, get: function () { - return _index.getNullableType; - }, -})); -Object.defineProperty(exports, "getOperationAST", ({ - enumerable: true, - get: function () { - return _index6.getOperationAST; - }, -})); -Object.defineProperty(exports, "getOperationRootType", ({ - enumerable: true, - get: function () { - return _index6.getOperationRootType; - }, -})); -Object.defineProperty(exports, "getVariableValues", ({ - enumerable: true, - get: function () { - return _index3.getVariableValues; - }, -})); -Object.defineProperty(exports, "getVisitFn", ({ - enumerable: true, - get: function () { - return _index2.getVisitFn; - }, -})); -Object.defineProperty(exports, "graphql", ({ - enumerable: true, - get: function () { - return _graphql.graphql; - }, -})); -Object.defineProperty(exports, "graphqlSync", ({ - enumerable: true, - get: function () { - return _graphql.graphqlSync; - }, -})); -Object.defineProperty(exports, "introspectionFromSchema", ({ - enumerable: true, - get: function () { - return _index6.introspectionFromSchema; + return _definition.getNullableType; }, })); Object.defineProperty(exports, "introspectionTypes", ({ enumerable: true, get: function () { - return _index.introspectionTypes; + return _introspection.introspectionTypes; }, })); Object.defineProperty(exports, "isAbstractType", ({ enumerable: true, get: function () { - return _index.isAbstractType; + return _definition.isAbstractType; }, })); Object.defineProperty(exports, "isCompositeType", ({ enumerable: true, get: function () { - return _index.isCompositeType; - }, -})); -Object.defineProperty(exports, "isConstValueNode", ({ - enumerable: true, - get: function () { - return _index2.isConstValueNode; - }, -})); -Object.defineProperty(exports, "isDefinitionNode", ({ - enumerable: true, - get: function () { - return _index2.isDefinitionNode; + return _definition.isCompositeType; }, })); Object.defineProperty(exports, "isDirective", ({ enumerable: true, get: function () { - return _index.isDirective; + return _directives.isDirective; }, })); Object.defineProperty(exports, "isEnumType", ({ enumerable: true, get: function () { - return _index.isEnumType; - }, -})); -Object.defineProperty(exports, "isEqualType", ({ - enumerable: true, - get: function () { - return _index6.isEqualType; - }, -})); -Object.defineProperty(exports, "isExecutableDefinitionNode", ({ - enumerable: true, - get: function () { - return _index2.isExecutableDefinitionNode; + return _definition.isEnumType; }, })); Object.defineProperty(exports, "isInputObjectType", ({ enumerable: true, get: function () { - return _index.isInputObjectType; + return _definition.isInputObjectType; }, })); Object.defineProperty(exports, "isInputType", ({ enumerable: true, get: function () { - return _index.isInputType; + return _definition.isInputType; }, })); Object.defineProperty(exports, "isInterfaceType", ({ enumerable: true, get: function () { - return _index.isInterfaceType; + return _definition.isInterfaceType; }, })); Object.defineProperty(exports, "isIntrospectionType", ({ enumerable: true, get: function () { - return _index.isIntrospectionType; + return _introspection.isIntrospectionType; }, })); Object.defineProperty(exports, "isLeafType", ({ enumerable: true, get: function () { - return _index.isLeafType; + return _definition.isLeafType; }, })); Object.defineProperty(exports, "isListType", ({ enumerable: true, get: function () { - return _index.isListType; + return _definition.isListType; }, })); Object.defineProperty(exports, "isNamedType", ({ enumerable: true, get: function () { - return _index.isNamedType; + return _definition.isNamedType; }, })); Object.defineProperty(exports, "isNonNullType", ({ enumerable: true, get: function () { - return _index.isNonNullType; + return _definition.isNonNullType; }, })); Object.defineProperty(exports, "isNullableType", ({ enumerable: true, get: function () { - return _index.isNullableType; + return _definition.isNullableType; }, })); Object.defineProperty(exports, "isObjectType", ({ enumerable: true, get: function () { - return _index.isObjectType; + return _definition.isObjectType; }, })); Object.defineProperty(exports, "isOutputType", ({ enumerable: true, get: function () { - return _index.isOutputType; + return _definition.isOutputType; }, })); Object.defineProperty(exports, "isRequiredArgument", ({ enumerable: true, get: function () { - return _index.isRequiredArgument; + return _definition.isRequiredArgument; }, })); Object.defineProperty(exports, "isRequiredInputField", ({ enumerable: true, get: function () { - return _index.isRequiredInputField; + return _definition.isRequiredInputField; }, })); Object.defineProperty(exports, "isScalarType", ({ enumerable: true, get: function () { - return _index.isScalarType; + return _definition.isScalarType; }, })); Object.defineProperty(exports, "isSchema", ({ enumerable: true, get: function () { - return _index.isSchema; - }, -})); -Object.defineProperty(exports, "isSelectionNode", ({ - enumerable: true, - get: function () { - return _index2.isSelectionNode; + return _schema.isSchema; }, })); Object.defineProperty(exports, "isSpecifiedDirective", ({ enumerable: true, get: function () { - return _index.isSpecifiedDirective; + return _directives.isSpecifiedDirective; }, })); Object.defineProperty(exports, "isSpecifiedScalarType", ({ enumerable: true, get: function () { - return _index.isSpecifiedScalarType; + return _scalars.isSpecifiedScalarType; }, })); Object.defineProperty(exports, "isType", ({ enumerable: true, get: function () { - return _index.isType; - }, -})); -Object.defineProperty(exports, "isTypeDefinitionNode", ({ - enumerable: true, - get: function () { - return _index2.isTypeDefinitionNode; - }, -})); -Object.defineProperty(exports, "isTypeExtensionNode", ({ - enumerable: true, - get: function () { - return _index2.isTypeExtensionNode; - }, -})); -Object.defineProperty(exports, "isTypeNode", ({ - enumerable: true, - get: function () { - return _index2.isTypeNode; - }, -})); -Object.defineProperty(exports, "isTypeSubTypeOf", ({ - enumerable: true, - get: function () { - return _index6.isTypeSubTypeOf; - }, -})); -Object.defineProperty(exports, "isTypeSystemDefinitionNode", ({ - enumerable: true, - get: function () { - return _index2.isTypeSystemDefinitionNode; - }, -})); -Object.defineProperty(exports, "isTypeSystemExtensionNode", ({ - enumerable: true, - get: function () { - return _index2.isTypeSystemExtensionNode; + return _definition.isType; }, })); Object.defineProperty(exports, "isUnionType", ({ enumerable: true, get: function () { - return _index.isUnionType; - }, -})); -Object.defineProperty(exports, "isValidNameError", ({ - enumerable: true, - get: function () { - return _index6.isValidNameError; - }, -})); -Object.defineProperty(exports, "isValueNode", ({ - enumerable: true, - get: function () { - return _index2.isValueNode; + return _definition.isUnionType; }, })); Object.defineProperty(exports, "isWrappingType", ({ enumerable: true, get: function () { - return _index.isWrappingType; - }, -})); -Object.defineProperty(exports, "lexicographicSortSchema", ({ - enumerable: true, - get: function () { - return _index6.lexicographicSortSchema; - }, -})); -Object.defineProperty(exports, "locatedError", ({ - enumerable: true, - get: function () { - return _index5.locatedError; - }, -})); -Object.defineProperty(exports, "parse", ({ - enumerable: true, - get: function () { - return _index2.parse; - }, -})); -Object.defineProperty(exports, "parseConstValue", ({ - enumerable: true, - get: function () { - return _index2.parseConstValue; - }, -})); -Object.defineProperty(exports, "parseType", ({ - enumerable: true, - get: function () { - return _index2.parseType; - }, -})); -Object.defineProperty(exports, "parseValue", ({ - enumerable: true, - get: function () { - return _index2.parseValue; - }, -})); -Object.defineProperty(exports, "print", ({ - enumerable: true, - get: function () { - return _index2.print; - }, -})); -Object.defineProperty(exports, "printError", ({ - enumerable: true, - get: function () { - return _index5.printError; + return _definition.isWrappingType; }, })); -Object.defineProperty(exports, "printIntrospectionSchema", ({ +Object.defineProperty(exports, "resolveObjMapThunk", ({ enumerable: true, get: function () { - return _index6.printIntrospectionSchema; + return _definition.resolveObjMapThunk; }, })); -Object.defineProperty(exports, "printLocation", ({ +Object.defineProperty(exports, "resolveReadonlyArrayThunk", ({ enumerable: true, get: function () { - return _index2.printLocation; + return _definition.resolveReadonlyArrayThunk; }, })); -Object.defineProperty(exports, "printSchema", ({ +Object.defineProperty(exports, "specifiedDirectives", ({ enumerable: true, get: function () { - return _index6.printSchema; + return _directives.specifiedDirectives; }, })); -Object.defineProperty(exports, "printSourceLocation", ({ +Object.defineProperty(exports, "specifiedScalarTypes", ({ enumerable: true, get: function () { - return _index2.printSourceLocation; + return _scalars.specifiedScalarTypes; }, })); -Object.defineProperty(exports, "printType", ({ +Object.defineProperty(exports, "validateSchema", ({ enumerable: true, get: function () { - return _index6.printType; + return _validate.validateSchema; }, })); -Object.defineProperty(exports, "recommendedRules", ({ - enumerable: true, - get: function () { - return _index4.recommendedRules; - }, + +var _schema = __nccwpck_require__(8505); + +var _definition = __nccwpck_require__(32150); + +var _directives = __nccwpck_require__(83614); + +var _scalars = __nccwpck_require__(93145); + +var _introspection = __nccwpck_require__(28344); + +var _validate = __nccwpck_require__(22430); + +var _assertName = __nccwpck_require__(74947); + + +/***/ }), + +/***/ 28344: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, })); -Object.defineProperty(exports, "resolveObjMapThunk", ({ - enumerable: true, - get: function () { - return _index.resolveObjMapThunk; +exports.introspectionTypes = + exports.__TypeKind = + exports.__Type = + exports.__Schema = + exports.__InputValue = + exports.__Field = + exports.__EnumValue = + exports.__DirectiveLocation = + exports.__Directive = + exports.TypeNameMetaFieldDef = + exports.TypeMetaFieldDef = + exports.TypeKind = + exports.SchemaMetaFieldDef = + void 0; +exports.isIntrospectionType = isIntrospectionType; + +var _inspect = __nccwpck_require__(10102); + +var _invariant = __nccwpck_require__(28847); + +var _directiveLocation = __nccwpck_require__(71553); + +var _printer = __nccwpck_require__(68203); + +var _astFromValue = __nccwpck_require__(12653); + +var _definition = __nccwpck_require__(32150); + +var _scalars = __nccwpck_require__(93145); + +const __Schema = new _definition.GraphQLObjectType({ + name: '__Schema', + description: + 'A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations.', + fields: () => ({ + description: { + type: _scalars.GraphQLString, + resolve: (schema) => schema.description, + }, + types: { + description: 'A list of all types supported by this server.', + type: new _definition.GraphQLNonNull( + new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type)), + ), + + resolve(schema) { + return Object.values(schema.getTypeMap()); + }, + }, + queryType: { + description: 'The type that query operations will be rooted at.', + type: new _definition.GraphQLNonNull(__Type), + resolve: (schema) => schema.getQueryType(), + }, + mutationType: { + description: + 'If this server supports mutation, the type that mutation operations will be rooted at.', + type: __Type, + resolve: (schema) => schema.getMutationType(), + }, + subscriptionType: { + description: + 'If this server support subscription, the type that subscription operations will be rooted at.', + type: __Type, + resolve: (schema) => schema.getSubscriptionType(), + }, + directives: { + description: 'A list of all directives supported by this server.', + type: new _definition.GraphQLNonNull( + new _definition.GraphQLList( + new _definition.GraphQLNonNull(__Directive), + ), + ), + resolve: (schema) => schema.getDirectives(), + }, + }), +}); + +exports.__Schema = __Schema; + +const __Directive = new _definition.GraphQLObjectType({ + name: '__Directive', + description: + "A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.\n\nIn some cases, you need to provide options to alter GraphQL's execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor.", + fields: () => ({ + name: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + resolve: (directive) => directive.name, + }, + description: { + type: _scalars.GraphQLString, + resolve: (directive) => directive.description, + }, + isRepeatable: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + resolve: (directive) => directive.isRepeatable, + }, + locations: { + type: new _definition.GraphQLNonNull( + new _definition.GraphQLList( + new _definition.GraphQLNonNull(__DirectiveLocation), + ), + ), + resolve: (directive) => directive.locations, + }, + args: { + type: new _definition.GraphQLNonNull( + new _definition.GraphQLList( + new _definition.GraphQLNonNull(__InputValue), + ), + ), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false, + }, + }, + + resolve(field, { includeDeprecated }) { + return includeDeprecated + ? field.args + : field.args.filter((arg) => arg.deprecationReason == null); + }, + }, + }), +}); + +exports.__Directive = __Directive; + +const __DirectiveLocation = new _definition.GraphQLEnumType({ + name: '__DirectiveLocation', + description: + 'A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies.', + values: { + QUERY: { + value: _directiveLocation.DirectiveLocation.QUERY, + description: 'Location adjacent to a query operation.', + }, + MUTATION: { + value: _directiveLocation.DirectiveLocation.MUTATION, + description: 'Location adjacent to a mutation operation.', + }, + SUBSCRIPTION: { + value: _directiveLocation.DirectiveLocation.SUBSCRIPTION, + description: 'Location adjacent to a subscription operation.', + }, + FIELD: { + value: _directiveLocation.DirectiveLocation.FIELD, + description: 'Location adjacent to a field.', + }, + FRAGMENT_DEFINITION: { + value: _directiveLocation.DirectiveLocation.FRAGMENT_DEFINITION, + description: 'Location adjacent to a fragment definition.', + }, + FRAGMENT_SPREAD: { + value: _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, + description: 'Location adjacent to a fragment spread.', + }, + INLINE_FRAGMENT: { + value: _directiveLocation.DirectiveLocation.INLINE_FRAGMENT, + description: 'Location adjacent to an inline fragment.', + }, + VARIABLE_DEFINITION: { + value: _directiveLocation.DirectiveLocation.VARIABLE_DEFINITION, + description: 'Location adjacent to a variable definition.', + }, + SCHEMA: { + value: _directiveLocation.DirectiveLocation.SCHEMA, + description: 'Location adjacent to a schema definition.', + }, + SCALAR: { + value: _directiveLocation.DirectiveLocation.SCALAR, + description: 'Location adjacent to a scalar definition.', + }, + OBJECT: { + value: _directiveLocation.DirectiveLocation.OBJECT, + description: 'Location adjacent to an object type definition.', + }, + FIELD_DEFINITION: { + value: _directiveLocation.DirectiveLocation.FIELD_DEFINITION, + description: 'Location adjacent to a field definition.', + }, + ARGUMENT_DEFINITION: { + value: _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION, + description: 'Location adjacent to an argument definition.', + }, + INTERFACE: { + value: _directiveLocation.DirectiveLocation.INTERFACE, + description: 'Location adjacent to an interface definition.', + }, + UNION: { + value: _directiveLocation.DirectiveLocation.UNION, + description: 'Location adjacent to a union definition.', + }, + ENUM: { + value: _directiveLocation.DirectiveLocation.ENUM, + description: 'Location adjacent to an enum definition.', + }, + ENUM_VALUE: { + value: _directiveLocation.DirectiveLocation.ENUM_VALUE, + description: 'Location adjacent to an enum value definition.', + }, + INPUT_OBJECT: { + value: _directiveLocation.DirectiveLocation.INPUT_OBJECT, + description: 'Location adjacent to an input object type definition.', + }, + INPUT_FIELD_DEFINITION: { + value: _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION, + description: 'Location adjacent to an input object field definition.', + }, }, -})); -Object.defineProperty(exports, "resolveReadonlyArrayThunk", ({ - enumerable: true, - get: function () { - return _index.resolveReadonlyArrayThunk; +}); + +exports.__DirectiveLocation = __DirectiveLocation; + +const __Type = new _definition.GraphQLObjectType({ + name: '__Type', + description: + 'The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in GraphQL as represented by the `__TypeKind` enum.\n\nDepending on the kind of a type, certain fields describe information about that type. Scalar types provide no information beyond a name, description and optional `specifiedByURL`, while Enum types provide their values. Object and Interface types provide the fields they describe. Abstract types, Union and Interface, provide the Object types possible at runtime. List and NonNull types compose other types.', + fields: () => ({ + kind: { + type: new _definition.GraphQLNonNull(__TypeKind), + + resolve(type) { + if ((0, _definition.isScalarType)(type)) { + return TypeKind.SCALAR; + } + + if ((0, _definition.isObjectType)(type)) { + return TypeKind.OBJECT; + } + + if ((0, _definition.isInterfaceType)(type)) { + return TypeKind.INTERFACE; + } + + if ((0, _definition.isUnionType)(type)) { + return TypeKind.UNION; + } + + if ((0, _definition.isEnumType)(type)) { + return TypeKind.ENUM; + } + + if ((0, _definition.isInputObjectType)(type)) { + return TypeKind.INPUT_OBJECT; + } + + if ((0, _definition.isListType)(type)) { + return TypeKind.LIST; + } + + if ((0, _definition.isNonNullType)(type)) { + return TypeKind.NON_NULL; + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered) + + false || + (0, _invariant.invariant)( + false, + `Unexpected type: "${(0, _inspect.inspect)(type)}".`, + ); + }, + }, + name: { + type: _scalars.GraphQLString, + resolve: (type) => ('name' in type ? type.name : undefined), + }, + description: { + type: _scalars.GraphQLString, + resolve: ( + type, // FIXME: add test case + ) => + /* c8 ignore next */ + 'description' in type ? type.description : undefined, + }, + specifiedByURL: { + type: _scalars.GraphQLString, + resolve: (obj) => + 'specifiedByURL' in obj ? obj.specifiedByURL : undefined, + }, + fields: { + type: new _definition.GraphQLList( + new _definition.GraphQLNonNull(__Field), + ), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false, + }, + }, + + resolve(type, { includeDeprecated }) { + if ( + (0, _definition.isObjectType)(type) || + (0, _definition.isInterfaceType)(type) + ) { + const fields = Object.values(type.getFields()); + return includeDeprecated + ? fields + : fields.filter((field) => field.deprecationReason == null); + } + }, + }, + interfaces: { + type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type)), + + resolve(type) { + if ( + (0, _definition.isObjectType)(type) || + (0, _definition.isInterfaceType)(type) + ) { + return type.getInterfaces(); + } + }, + }, + possibleTypes: { + type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type)), + + resolve(type, _args, _context, { schema }) { + if ((0, _definition.isAbstractType)(type)) { + return schema.getPossibleTypes(type); + } + }, + }, + enumValues: { + type: new _definition.GraphQLList( + new _definition.GraphQLNonNull(__EnumValue), + ), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false, + }, + }, + + resolve(type, { includeDeprecated }) { + if ((0, _definition.isEnumType)(type)) { + const values = type.getValues(); + return includeDeprecated + ? values + : values.filter((field) => field.deprecationReason == null); + } + }, + }, + inputFields: { + type: new _definition.GraphQLList( + new _definition.GraphQLNonNull(__InputValue), + ), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false, + }, + }, + + resolve(type, { includeDeprecated }) { + if ((0, _definition.isInputObjectType)(type)) { + const values = Object.values(type.getFields()); + return includeDeprecated + ? values + : values.filter((field) => field.deprecationReason == null); + } + }, + }, + ofType: { + type: __Type, + resolve: (type) => ('ofType' in type ? type.ofType : undefined), + }, + isOneOf: { + type: _scalars.GraphQLBoolean, + resolve: (type) => { + if ((0, _definition.isInputObjectType)(type)) { + return type.isOneOf; + } + }, + }, + }), +}); + +exports.__Type = __Type; + +const __Field = new _definition.GraphQLObjectType({ + name: '__Field', + description: + 'Object and Interface types are described by a list of Fields, each of which has a name, potentially a list of arguments, and a return type.', + fields: () => ({ + name: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + resolve: (field) => field.name, + }, + description: { + type: _scalars.GraphQLString, + resolve: (field) => field.description, + }, + args: { + type: new _definition.GraphQLNonNull( + new _definition.GraphQLList( + new _definition.GraphQLNonNull(__InputValue), + ), + ), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false, + }, + }, + + resolve(field, { includeDeprecated }) { + return includeDeprecated + ? field.args + : field.args.filter((arg) => arg.deprecationReason == null); + }, + }, + type: { + type: new _definition.GraphQLNonNull(__Type), + resolve: (field) => field.type, + }, + isDeprecated: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + resolve: (field) => field.deprecationReason != null, + }, + deprecationReason: { + type: _scalars.GraphQLString, + resolve: (field) => field.deprecationReason, + }, + }), +}); + +exports.__Field = __Field; + +const __InputValue = new _definition.GraphQLObjectType({ + name: '__InputValue', + description: + 'Arguments provided to Fields or Directives and the input fields of an InputObject are represented as Input Values which describe their type and optionally a default value.', + fields: () => ({ + name: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + resolve: (inputValue) => inputValue.name, + }, + description: { + type: _scalars.GraphQLString, + resolve: (inputValue) => inputValue.description, + }, + type: { + type: new _definition.GraphQLNonNull(__Type), + resolve: (inputValue) => inputValue.type, + }, + defaultValue: { + type: _scalars.GraphQLString, + description: + 'A GraphQL-formatted string representing the default value for this input value.', + + resolve(inputValue) { + const { type, defaultValue } = inputValue; + const valueAST = (0, _astFromValue.astFromValue)(defaultValue, type); + return valueAST ? (0, _printer.print)(valueAST) : null; + }, + }, + isDeprecated: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + resolve: (field) => field.deprecationReason != null, + }, + deprecationReason: { + type: _scalars.GraphQLString, + resolve: (obj) => obj.deprecationReason, + }, + }), +}); + +exports.__InputValue = __InputValue; + +const __EnumValue = new _definition.GraphQLObjectType({ + name: '__EnumValue', + description: + 'One possible value for a given Enum. Enum values are unique values, not a placeholder for a string or numeric value. However an Enum value is returned in a JSON response as a string.', + fields: () => ({ + name: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + resolve: (enumValue) => enumValue.name, + }, + description: { + type: _scalars.GraphQLString, + resolve: (enumValue) => enumValue.description, + }, + isDeprecated: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + resolve: (enumValue) => enumValue.deprecationReason != null, + }, + deprecationReason: { + type: _scalars.GraphQLString, + resolve: (enumValue) => enumValue.deprecationReason, + }, + }), +}); + +exports.__EnumValue = __EnumValue; +var TypeKind; +exports.TypeKind = TypeKind; + +(function (TypeKind) { + TypeKind['SCALAR'] = 'SCALAR'; + TypeKind['OBJECT'] = 'OBJECT'; + TypeKind['INTERFACE'] = 'INTERFACE'; + TypeKind['UNION'] = 'UNION'; + TypeKind['ENUM'] = 'ENUM'; + TypeKind['INPUT_OBJECT'] = 'INPUT_OBJECT'; + TypeKind['LIST'] = 'LIST'; + TypeKind['NON_NULL'] = 'NON_NULL'; +})(TypeKind || (exports.TypeKind = TypeKind = {})); + +const __TypeKind = new _definition.GraphQLEnumType({ + name: '__TypeKind', + description: 'An enum describing what kind of type a given `__Type` is.', + values: { + SCALAR: { + value: TypeKind.SCALAR, + description: 'Indicates this type is a scalar.', + }, + OBJECT: { + value: TypeKind.OBJECT, + description: + 'Indicates this type is an object. `fields` and `interfaces` are valid fields.', + }, + INTERFACE: { + value: TypeKind.INTERFACE, + description: + 'Indicates this type is an interface. `fields`, `interfaces`, and `possibleTypes` are valid fields.', + }, + UNION: { + value: TypeKind.UNION, + description: + 'Indicates this type is a union. `possibleTypes` is a valid field.', + }, + ENUM: { + value: TypeKind.ENUM, + description: + 'Indicates this type is an enum. `enumValues` is a valid field.', + }, + INPUT_OBJECT: { + value: TypeKind.INPUT_OBJECT, + description: + 'Indicates this type is an input object. `inputFields` is a valid field.', + }, + LIST: { + value: TypeKind.LIST, + description: 'Indicates this type is a list. `ofType` is a valid field.', + }, + NON_NULL: { + value: TypeKind.NON_NULL, + description: + 'Indicates this type is a non-null. `ofType` is a valid field.', + }, }, +}); +/** + * Note that these are GraphQLField and not GraphQLFieldConfig, + * so the format for args is different. + */ + +exports.__TypeKind = __TypeKind; +const SchemaMetaFieldDef = { + name: '__schema', + type: new _definition.GraphQLNonNull(__Schema), + description: 'Access the current type schema of this server.', + args: [], + resolve: (_source, _args, _context, { schema }) => schema, + deprecationReason: undefined, + extensions: Object.create(null), + astNode: undefined, +}; +exports.SchemaMetaFieldDef = SchemaMetaFieldDef; +const TypeMetaFieldDef = { + name: '__type', + type: __Type, + description: 'Request the type information of a single type.', + args: [ + { + name: 'name', + description: undefined, + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + defaultValue: undefined, + deprecationReason: undefined, + extensions: Object.create(null), + astNode: undefined, + }, + ], + resolve: (_source, { name }, _context, { schema }) => schema.getType(name), + deprecationReason: undefined, + extensions: Object.create(null), + astNode: undefined, +}; +exports.TypeMetaFieldDef = TypeMetaFieldDef; +const TypeNameMetaFieldDef = { + name: '__typename', + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + description: 'The name of the current Object type at runtime.', + args: [], + resolve: (_source, _args, _context, { parentType }) => parentType.name, + deprecationReason: undefined, + extensions: Object.create(null), + astNode: undefined, +}; +exports.TypeNameMetaFieldDef = TypeNameMetaFieldDef; +const introspectionTypes = Object.freeze([ + __Schema, + __Directive, + __DirectiveLocation, + __Type, + __Field, + __InputValue, + __EnumValue, + __TypeKind, +]); +exports.introspectionTypes = introspectionTypes; + +function isIntrospectionType(type) { + return introspectionTypes.some(({ name }) => type.name === name); +} + + +/***/ }), + +/***/ 93145: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, })); -Object.defineProperty(exports, "responsePathAsArray", ({ - enumerable: true, - get: function () { - return _index3.responsePathAsArray; +exports.GraphQLString = + exports.GraphQLInt = + exports.GraphQLID = + exports.GraphQLFloat = + exports.GraphQLBoolean = + exports.GRAPHQL_MIN_INT = + exports.GRAPHQL_MAX_INT = + void 0; +exports.isSpecifiedScalarType = isSpecifiedScalarType; +exports.specifiedScalarTypes = void 0; + +var _inspect = __nccwpck_require__(10102); + +var _isObjectLike = __nccwpck_require__(95865); + +var _GraphQLError = __nccwpck_require__(4797); + +var _kinds = __nccwpck_require__(11927); + +var _printer = __nccwpck_require__(68203); + +var _definition = __nccwpck_require__(32150); + +/** + * Maximum possible Int value as per GraphQL Spec (32-bit signed integer). + * n.b. This differs from JavaScript's numbers that are IEEE 754 doubles safe up-to 2^53 - 1 + * */ +const GRAPHQL_MAX_INT = 2147483647; +/** + * Minimum possible Int value as per GraphQL Spec (32-bit signed integer). + * n.b. This differs from JavaScript's numbers that are IEEE 754 doubles safe starting at -(2^53 - 1) + * */ + +exports.GRAPHQL_MAX_INT = GRAPHQL_MAX_INT; +const GRAPHQL_MIN_INT = -2147483648; +exports.GRAPHQL_MIN_INT = GRAPHQL_MIN_INT; +const GraphQLInt = new _definition.GraphQLScalarType({ + name: 'Int', + description: + 'The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.', + + serialize(outputValue) { + const coercedValue = serializeObject(outputValue); + + if (typeof coercedValue === 'boolean') { + return coercedValue ? 1 : 0; + } + + let num = coercedValue; + + if (typeof coercedValue === 'string' && coercedValue !== '') { + num = Number(coercedValue); + } + + if (typeof num !== 'number' || !Number.isInteger(num)) { + throw new _GraphQLError.GraphQLError( + `Int cannot represent non-integer value: ${(0, _inspect.inspect)( + coercedValue, + )}`, + ); + } + + if (num > GRAPHQL_MAX_INT || num < GRAPHQL_MIN_INT) { + throw new _GraphQLError.GraphQLError( + 'Int cannot represent non 32-bit signed integer value: ' + + (0, _inspect.inspect)(coercedValue), + ); + } + + return num; }, -})); -Object.defineProperty(exports, "separateOperations", ({ - enumerable: true, - get: function () { - return _index6.separateOperations; + + parseValue(inputValue) { + if (typeof inputValue !== 'number' || !Number.isInteger(inputValue)) { + throw new _GraphQLError.GraphQLError( + `Int cannot represent non-integer value: ${(0, _inspect.inspect)( + inputValue, + )}`, + ); + } + + if (inputValue > GRAPHQL_MAX_INT || inputValue < GRAPHQL_MIN_INT) { + throw new _GraphQLError.GraphQLError( + `Int cannot represent non 32-bit signed integer value: ${inputValue}`, + ); + } + + return inputValue; }, -})); -Object.defineProperty(exports, "specifiedDirectives", ({ - enumerable: true, - get: function () { - return _index.specifiedDirectives; + + parseLiteral(valueNode) { + if (valueNode.kind !== _kinds.Kind.INT) { + throw new _GraphQLError.GraphQLError( + `Int cannot represent non-integer value: ${(0, _printer.print)( + valueNode, + )}`, + { + nodes: valueNode, + }, + ); + } + + const num = parseInt(valueNode.value, 10); + + if (num > GRAPHQL_MAX_INT || num < GRAPHQL_MIN_INT) { + throw new _GraphQLError.GraphQLError( + `Int cannot represent non 32-bit signed integer value: ${valueNode.value}`, + { + nodes: valueNode, + }, + ); + } + + return num; }, -})); -Object.defineProperty(exports, "specifiedRules", ({ - enumerable: true, - get: function () { - return _index4.specifiedRules; +}); +exports.GraphQLInt = GraphQLInt; +const GraphQLFloat = new _definition.GraphQLScalarType({ + name: 'Float', + description: + 'The `Float` scalar type represents signed double-precision fractional values as specified by [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point).', + + serialize(outputValue) { + const coercedValue = serializeObject(outputValue); + + if (typeof coercedValue === 'boolean') { + return coercedValue ? 1 : 0; + } + + let num = coercedValue; + + if (typeof coercedValue === 'string' && coercedValue !== '') { + num = Number(coercedValue); + } + + if (typeof num !== 'number' || !Number.isFinite(num)) { + throw new _GraphQLError.GraphQLError( + `Float cannot represent non numeric value: ${(0, _inspect.inspect)( + coercedValue, + )}`, + ); + } + + return num; }, -})); -Object.defineProperty(exports, "specifiedScalarTypes", ({ - enumerable: true, - get: function () { - return _index.specifiedScalarTypes; + + parseValue(inputValue) { + if (typeof inputValue !== 'number' || !Number.isFinite(inputValue)) { + throw new _GraphQLError.GraphQLError( + `Float cannot represent non numeric value: ${(0, _inspect.inspect)( + inputValue, + )}`, + ); + } + + return inputValue; }, -})); -Object.defineProperty(exports, "stripIgnoredCharacters", ({ - enumerable: true, - get: function () { - return _index6.stripIgnoredCharacters; + + parseLiteral(valueNode) { + if ( + valueNode.kind !== _kinds.Kind.FLOAT && + valueNode.kind !== _kinds.Kind.INT + ) { + throw new _GraphQLError.GraphQLError( + `Float cannot represent non numeric value: ${(0, _printer.print)( + valueNode, + )}`, + valueNode, + ); + } + + return parseFloat(valueNode.value); }, -})); -Object.defineProperty(exports, "subscribe", ({ - enumerable: true, - get: function () { - return _index3.subscribe; +}); +exports.GraphQLFloat = GraphQLFloat; +const GraphQLString = new _definition.GraphQLScalarType({ + name: 'String', + description: + 'The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.', + + serialize(outputValue) { + const coercedValue = serializeObject(outputValue); // Serialize string, boolean and number values to a string, but do not + // attempt to coerce object, function, symbol, or other types as strings. + + if (typeof coercedValue === 'string') { + return coercedValue; + } + + if (typeof coercedValue === 'boolean') { + return coercedValue ? 'true' : 'false'; + } + + if (typeof coercedValue === 'number' && Number.isFinite(coercedValue)) { + return coercedValue.toString(); + } + + throw new _GraphQLError.GraphQLError( + `String cannot represent value: ${(0, _inspect.inspect)(outputValue)}`, + ); }, -})); -Object.defineProperty(exports, "syntaxError", ({ - enumerable: true, - get: function () { - return _index5.syntaxError; + + parseValue(inputValue) { + if (typeof inputValue !== 'string') { + throw new _GraphQLError.GraphQLError( + `String cannot represent a non string value: ${(0, _inspect.inspect)( + inputValue, + )}`, + ); + } + + return inputValue; }, -})); -Object.defineProperty(exports, "typeFromAST", ({ - enumerable: true, - get: function () { - return _index6.typeFromAST; + + parseLiteral(valueNode) { + if (valueNode.kind !== _kinds.Kind.STRING) { + throw new _GraphQLError.GraphQLError( + `String cannot represent a non string value: ${(0, _printer.print)( + valueNode, + )}`, + { + nodes: valueNode, + }, + ); + } + + return valueNode.value; }, -})); -Object.defineProperty(exports, "validate", ({ - enumerable: true, - get: function () { - return _index4.validate; +}); +exports.GraphQLString = GraphQLString; +const GraphQLBoolean = new _definition.GraphQLScalarType({ + name: 'Boolean', + description: 'The `Boolean` scalar type represents `true` or `false`.', + + serialize(outputValue) { + const coercedValue = serializeObject(outputValue); + + if (typeof coercedValue === 'boolean') { + return coercedValue; + } + + if (Number.isFinite(coercedValue)) { + return coercedValue !== 0; + } + + throw new _GraphQLError.GraphQLError( + `Boolean cannot represent a non boolean value: ${(0, _inspect.inspect)( + coercedValue, + )}`, + ); }, -})); -Object.defineProperty(exports, "validateSchema", ({ - enumerable: true, - get: function () { - return _index.validateSchema; + + parseValue(inputValue) { + if (typeof inputValue !== 'boolean') { + throw new _GraphQLError.GraphQLError( + `Boolean cannot represent a non boolean value: ${(0, _inspect.inspect)( + inputValue, + )}`, + ); + } + + return inputValue; }, -})); -Object.defineProperty(exports, "valueFromAST", ({ - enumerable: true, - get: function () { - return _index6.valueFromAST; + + parseLiteral(valueNode) { + if (valueNode.kind !== _kinds.Kind.BOOLEAN) { + throw new _GraphQLError.GraphQLError( + `Boolean cannot represent a non boolean value: ${(0, _printer.print)( + valueNode, + )}`, + { + nodes: valueNode, + }, + ); + } + + return valueNode.value; }, -})); -Object.defineProperty(exports, "valueFromASTUntyped", ({ - enumerable: true, - get: function () { - return _index6.valueFromASTUntyped; +}); +exports.GraphQLBoolean = GraphQLBoolean; +const GraphQLID = new _definition.GraphQLScalarType({ + name: 'ID', + description: + 'The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `"4"`) or integer (such as `4`) input value will be accepted as an ID.', + + serialize(outputValue) { + const coercedValue = serializeObject(outputValue); + + if (typeof coercedValue === 'string') { + return coercedValue; + } + + if (Number.isInteger(coercedValue)) { + return String(coercedValue); + } + + throw new _GraphQLError.GraphQLError( + `ID cannot represent value: ${(0, _inspect.inspect)(outputValue)}`, + ); }, -})); -Object.defineProperty(exports, "version", ({ - enumerable: true, - get: function () { - return _version.version; + + parseValue(inputValue) { + if (typeof inputValue === 'string') { + return inputValue; + } + + if (typeof inputValue === 'number' && Number.isInteger(inputValue)) { + return inputValue.toString(); + } + + throw new _GraphQLError.GraphQLError( + `ID cannot represent value: ${(0, _inspect.inspect)(inputValue)}`, + ); }, -})); -Object.defineProperty(exports, "versionInfo", ({ - enumerable: true, - get: function () { - return _version.versionInfo; + + parseLiteral(valueNode) { + if ( + valueNode.kind !== _kinds.Kind.STRING && + valueNode.kind !== _kinds.Kind.INT + ) { + throw new _GraphQLError.GraphQLError( + 'ID cannot represent a non-string and non-integer value: ' + + (0, _printer.print)(valueNode), + { + nodes: valueNode, + }, + ); + } + + return valueNode.value; }, +}); +exports.GraphQLID = GraphQLID; +const specifiedScalarTypes = Object.freeze([ + GraphQLString, + GraphQLInt, + GraphQLFloat, + GraphQLBoolean, + GraphQLID, +]); +exports.specifiedScalarTypes = specifiedScalarTypes; + +function isSpecifiedScalarType(type) { + return specifiedScalarTypes.some(({ name }) => type.name === name); +} // Support serializing objects with custom valueOf() or toJSON() functions - +// a common way to represent a complex value which can be represented as +// a string (ex: MongoDB id objects). + +function serializeObject(outputValue) { + if ((0, _isObjectLike.isObjectLike)(outputValue)) { + if (typeof outputValue.valueOf === 'function') { + const valueOfResult = outputValue.valueOf(); + + if (!(0, _isObjectLike.isObjectLike)(valueOfResult)) { + return valueOfResult; + } + } + + if (typeof outputValue.toJSON === 'function') { + return outputValue.toJSON(); + } + } + + return outputValue; +} + + +/***/ }), + +/***/ 8505: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, })); -Object.defineProperty(exports, "visit", ({ - enumerable: true, - get: function () { - return _index2.visit; - }, +exports.GraphQLSchema = void 0; +exports.assertSchema = assertSchema; +exports.isSchema = isSchema; + +var _devAssert = __nccwpck_require__(46514); + +var _inspect = __nccwpck_require__(10102); + +var _instanceOf = __nccwpck_require__(93481); + +var _isObjectLike = __nccwpck_require__(95865); + +var _toObjMap = __nccwpck_require__(74728); + +var _ast = __nccwpck_require__(45494); + +var _definition = __nccwpck_require__(32150); + +var _directives = __nccwpck_require__(83614); + +var _introspection = __nccwpck_require__(28344); + +/** + * Test if the given value is a GraphQL schema. + */ +function isSchema(schema) { + return (0, _instanceOf.instanceOf)(schema, GraphQLSchema); +} + +function assertSchema(schema) { + if (!isSchema(schema)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(schema)} to be a GraphQL schema.`, + ); + } + + return schema; +} +/** + * Custom extensions + * + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ + +/** + * Schema Definition + * + * A Schema is created by supplying the root types of each type of operation, + * query and mutation (optional). A schema definition is then supplied to the + * validator and executor. + * + * Example: + * + * ```ts + * const MyAppSchema = new GraphQLSchema({ + * query: MyAppQueryRootType, + * mutation: MyAppMutationRootType, + * }) + * ``` + * + * Note: When the schema is constructed, by default only the types that are + * reachable by traversing the root types are included, other types must be + * explicitly referenced. + * + * Example: + * + * ```ts + * const characterInterface = new GraphQLInterfaceType({ + * name: 'Character', + * ... + * }); + * + * const humanType = new GraphQLObjectType({ + * name: 'Human', + * interfaces: [characterInterface], + * ... + * }); + * + * const droidType = new GraphQLObjectType({ + * name: 'Droid', + * interfaces: [characterInterface], + * ... + * }); + * + * const schema = new GraphQLSchema({ + * query: new GraphQLObjectType({ + * name: 'Query', + * fields: { + * hero: { type: characterInterface, ... }, + * } + * }), + * ... + * // Since this schema references only the `Character` interface it's + * // necessary to explicitly list the types that implement it if + * // you want them to be included in the final schema. + * types: [humanType, droidType], + * }) + * ``` + * + * Note: If an array of `directives` are provided to GraphQLSchema, that will be + * the exact list of directives represented and allowed. If `directives` is not + * provided then a default set of the specified directives (e.g. `@include` and + * `@skip`) will be used. If you wish to provide *additional* directives to these + * specified directives, you must explicitly declare them. Example: + * + * ```ts + * const MyAppSchema = new GraphQLSchema({ + * ... + * directives: specifiedDirectives.concat([ myCustomDirective ]), + * }) + * ``` + */ +class GraphQLSchema { + // Used as a cache for validateSchema(). + constructor(config) { + var _config$extensionASTN, _config$directives; + + // If this schema was built from a source known to be valid, then it may be + // marked with assumeValid to avoid an additional type system validation. + this.__validationErrors = config.assumeValid === true ? [] : undefined; // Check for common mistakes during construction to produce early errors. + + (0, _isObjectLike.isObjectLike)(config) || + (0, _devAssert.devAssert)(false, 'Must provide configuration object.'); + !config.types || + Array.isArray(config.types) || + (0, _devAssert.devAssert)( + false, + `"types" must be Array if provided but got: ${(0, _inspect.inspect)( + config.types, + )}.`, + ); + !config.directives || + Array.isArray(config.directives) || + (0, _devAssert.devAssert)( + false, + '"directives" must be Array if provided but got: ' + + `${(0, _inspect.inspect)(config.directives)}.`, + ); + this.description = config.description; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = + (_config$extensionASTN = config.extensionASTNodes) !== null && + _config$extensionASTN !== void 0 + ? _config$extensionASTN + : []; + this._queryType = config.query; + this._mutationType = config.mutation; + this._subscriptionType = config.subscription; // Provide specified directives (e.g. @include and @skip) by default. + + this._directives = + (_config$directives = config.directives) !== null && + _config$directives !== void 0 + ? _config$directives + : _directives.specifiedDirectives; // To preserve order of user-provided types, we add first to add them to + // the set of "collected" types, so `collectReferencedTypes` ignore them. + + const allReferencedTypes = new Set(config.types); + + if (config.types != null) { + for (const type of config.types) { + // When we ready to process this type, we remove it from "collected" types + // and then add it together with all dependent types in the correct position. + allReferencedTypes.delete(type); + collectReferencedTypes(type, allReferencedTypes); + } + } + + if (this._queryType != null) { + collectReferencedTypes(this._queryType, allReferencedTypes); + } + + if (this._mutationType != null) { + collectReferencedTypes(this._mutationType, allReferencedTypes); + } + + if (this._subscriptionType != null) { + collectReferencedTypes(this._subscriptionType, allReferencedTypes); + } + + for (const directive of this._directives) { + // Directives are not validated until validateSchema() is called. + if ((0, _directives.isDirective)(directive)) { + for (const arg of directive.args) { + collectReferencedTypes(arg.type, allReferencedTypes); + } + } + } + + collectReferencedTypes(_introspection.__Schema, allReferencedTypes); // Storing the resulting map for reference by the schema. + + this._typeMap = Object.create(null); + this._subTypeMap = Object.create(null); // Keep track of all implementations by interface name. + + this._implementationsMap = Object.create(null); + + for (const namedType of allReferencedTypes) { + if (namedType == null) { + continue; + } + + const typeName = namedType.name; + typeName || + (0, _devAssert.devAssert)( + false, + 'One of the provided types for building the Schema is missing a name.', + ); + + if (this._typeMap[typeName] !== undefined) { + throw new Error( + `Schema must contain uniquely named types but contains multiple types named "${typeName}".`, + ); + } + + this._typeMap[typeName] = namedType; + + if ((0, _definition.isInterfaceType)(namedType)) { + // Store implementations by interface. + for (const iface of namedType.getInterfaces()) { + if ((0, _definition.isInterfaceType)(iface)) { + let implementations = this._implementationsMap[iface.name]; + + if (implementations === undefined) { + implementations = this._implementationsMap[iface.name] = { + objects: [], + interfaces: [], + }; + } + + implementations.interfaces.push(namedType); + } + } + } else if ((0, _definition.isObjectType)(namedType)) { + // Store implementations by objects. + for (const iface of namedType.getInterfaces()) { + if ((0, _definition.isInterfaceType)(iface)) { + let implementations = this._implementationsMap[iface.name]; + + if (implementations === undefined) { + implementations = this._implementationsMap[iface.name] = { + objects: [], + interfaces: [], + }; + } + + implementations.objects.push(namedType); + } + } + } + } + } + + get [Symbol.toStringTag]() { + return 'GraphQLSchema'; + } + + getQueryType() { + return this._queryType; + } + + getMutationType() { + return this._mutationType; + } + + getSubscriptionType() { + return this._subscriptionType; + } + + getRootType(operation) { + switch (operation) { + case _ast.OperationTypeNode.QUERY: + return this.getQueryType(); + + case _ast.OperationTypeNode.MUTATION: + return this.getMutationType(); + + case _ast.OperationTypeNode.SUBSCRIPTION: + return this.getSubscriptionType(); + } + } + + getTypeMap() { + return this._typeMap; + } + + getType(name) { + return this.getTypeMap()[name]; + } + + getPossibleTypes(abstractType) { + return (0, _definition.isUnionType)(abstractType) + ? abstractType.getTypes() + : this.getImplementations(abstractType).objects; + } + + getImplementations(interfaceType) { + const implementations = this._implementationsMap[interfaceType.name]; + return implementations !== null && implementations !== void 0 + ? implementations + : { + objects: [], + interfaces: [], + }; + } + + isSubType(abstractType, maybeSubType) { + let map = this._subTypeMap[abstractType.name]; + + if (map === undefined) { + map = Object.create(null); + + if ((0, _definition.isUnionType)(abstractType)) { + for (const type of abstractType.getTypes()) { + map[type.name] = true; + } + } else { + const implementations = this.getImplementations(abstractType); + + for (const type of implementations.objects) { + map[type.name] = true; + } + + for (const type of implementations.interfaces) { + map[type.name] = true; + } + } + + this._subTypeMap[abstractType.name] = map; + } + + return map[maybeSubType.name] !== undefined; + } + + getDirectives() { + return this._directives; + } + + getDirective(name) { + return this.getDirectives().find((directive) => directive.name === name); + } + + toConfig() { + return { + description: this.description, + query: this.getQueryType(), + mutation: this.getMutationType(), + subscription: this.getSubscriptionType(), + types: Object.values(this.getTypeMap()), + directives: this.getDirectives(), + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + assumeValid: this.__validationErrors !== undefined, + }; + } +} + +exports.GraphQLSchema = GraphQLSchema; + +function collectReferencedTypes(type, typeSet) { + const namedType = (0, _definition.getNamedType)(type); + + if (!typeSet.has(namedType)) { + typeSet.add(namedType); + + if ((0, _definition.isUnionType)(namedType)) { + for (const memberType of namedType.getTypes()) { + collectReferencedTypes(memberType, typeSet); + } + } else if ( + (0, _definition.isObjectType)(namedType) || + (0, _definition.isInterfaceType)(namedType) + ) { + for (const interfaceType of namedType.getInterfaces()) { + collectReferencedTypes(interfaceType, typeSet); + } + + for (const field of Object.values(namedType.getFields())) { + collectReferencedTypes(field.type, typeSet); + + for (const arg of field.args) { + collectReferencedTypes(arg.type, typeSet); + } + } + } else if ((0, _definition.isInputObjectType)(namedType)) { + for (const field of Object.values(namedType.getFields())) { + collectReferencedTypes(field.type, typeSet); + } + } + } + + return typeSet; +} + + +/***/ }), + +/***/ 22430: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, })); -Object.defineProperty(exports, "visitInParallel", ({ - enumerable: true, - get: function () { - return _index2.visitInParallel; - }, +exports.assertValidSchema = assertValidSchema; +exports.validateSchema = validateSchema; + +var _inspect = __nccwpck_require__(10102); + +var _GraphQLError = __nccwpck_require__(4797); + +var _ast = __nccwpck_require__(45494); + +var _typeComparators = __nccwpck_require__(10333); + +var _definition = __nccwpck_require__(32150); + +var _directives = __nccwpck_require__(83614); + +var _introspection = __nccwpck_require__(28344); + +var _schema = __nccwpck_require__(8505); + +/** + * Implements the "Type Validation" sub-sections of the specification's + * "Type System" section. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the Schema is valid. + */ +function validateSchema(schema) { + // First check to ensure the provided value is in fact a GraphQLSchema. + (0, _schema.assertSchema)(schema); // If this Schema has already been validated, return the previous results. + + if (schema.__validationErrors) { + return schema.__validationErrors; + } // Validate the schema, producing a list of errors. + + const context = new SchemaValidationContext(schema); + validateRootTypes(context); + validateDirectives(context); + validateTypes(context); // Persist the results of validation before returning to ensure validation + // does not run multiple times for this schema. + + const errors = context.getErrors(); + schema.__validationErrors = errors; + return errors; +} +/** + * Utility function which asserts a schema is valid by throwing an error if + * it is invalid. + */ + +function assertValidSchema(schema) { + const errors = validateSchema(schema); + + if (errors.length !== 0) { + throw new Error(errors.map((error) => error.message).join('\n\n')); + } +} + +class SchemaValidationContext { + constructor(schema) { + this._errors = []; + this.schema = schema; + } + + reportError(message, nodes) { + const _nodes = Array.isArray(nodes) ? nodes.filter(Boolean) : nodes; + + this._errors.push( + new _GraphQLError.GraphQLError(message, { + nodes: _nodes, + }), + ); + } + + getErrors() { + return this._errors; + } +} + +function validateRootTypes(context) { + const schema = context.schema; + const queryType = schema.getQueryType(); + + if (!queryType) { + context.reportError('Query root type must be provided.', schema.astNode); + } else if (!(0, _definition.isObjectType)(queryType)) { + var _getOperationTypeNode; + + context.reportError( + `Query root type must be Object type, it cannot be ${(0, + _inspect.inspect)(queryType)}.`, + (_getOperationTypeNode = getOperationTypeNode( + schema, + _ast.OperationTypeNode.QUERY, + )) !== null && _getOperationTypeNode !== void 0 + ? _getOperationTypeNode + : queryType.astNode, + ); + } + + const mutationType = schema.getMutationType(); + + if (mutationType && !(0, _definition.isObjectType)(mutationType)) { + var _getOperationTypeNode2; + + context.reportError( + 'Mutation root type must be Object type if provided, it cannot be ' + + `${(0, _inspect.inspect)(mutationType)}.`, + (_getOperationTypeNode2 = getOperationTypeNode( + schema, + _ast.OperationTypeNode.MUTATION, + )) !== null && _getOperationTypeNode2 !== void 0 + ? _getOperationTypeNode2 + : mutationType.astNode, + ); + } + + const subscriptionType = schema.getSubscriptionType(); + + if (subscriptionType && !(0, _definition.isObjectType)(subscriptionType)) { + var _getOperationTypeNode3; + + context.reportError( + 'Subscription root type must be Object type if provided, it cannot be ' + + `${(0, _inspect.inspect)(subscriptionType)}.`, + (_getOperationTypeNode3 = getOperationTypeNode( + schema, + _ast.OperationTypeNode.SUBSCRIPTION, + )) !== null && _getOperationTypeNode3 !== void 0 + ? _getOperationTypeNode3 + : subscriptionType.astNode, + ); + } +} + +function getOperationTypeNode(schema, operation) { + var _flatMap$find; + + return (_flatMap$find = [schema.astNode, ...schema.extensionASTNodes] + .flatMap( + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + (schemaNode) => { + var _schemaNode$operation; + + return ( + /* c8 ignore next */ + (_schemaNode$operation = + schemaNode === null || schemaNode === void 0 + ? void 0 + : schemaNode.operationTypes) !== null && + _schemaNode$operation !== void 0 + ? _schemaNode$operation + : [] + ); + }, + ) + .find((operationNode) => operationNode.operation === operation)) === null || + _flatMap$find === void 0 + ? void 0 + : _flatMap$find.type; +} + +function validateDirectives(context) { + for (const directive of context.schema.getDirectives()) { + // Ensure all directives are in fact GraphQL directives. + if (!(0, _directives.isDirective)(directive)) { + context.reportError( + `Expected directive but got: ${(0, _inspect.inspect)(directive)}.`, + directive === null || directive === void 0 ? void 0 : directive.astNode, + ); + continue; + } // Ensure they are named correctly. + + validateName(context, directive); + + if (directive.locations.length === 0) { + context.reportError( + `Directive @${directive.name} must include 1 or more locations.`, + directive.astNode, + ); + } // Ensure the arguments are valid. + + for (const arg of directive.args) { + // Ensure they are named correctly. + validateName(context, arg); // Ensure the type is an input type. + + if (!(0, _definition.isInputType)(arg.type)) { + context.reportError( + `The type of @${directive.name}(${arg.name}:) must be Input Type ` + + `but got: ${(0, _inspect.inspect)(arg.type)}.`, + arg.astNode, + ); + } + + if ( + (0, _definition.isRequiredArgument)(arg) && + arg.deprecationReason != null + ) { + var _arg$astNode; + + context.reportError( + `Required argument @${directive.name}(${arg.name}:) cannot be deprecated.`, + [ + getDeprecatedDirectiveNode(arg.astNode), + (_arg$astNode = arg.astNode) === null || _arg$astNode === void 0 + ? void 0 + : _arg$astNode.type, + ], + ); + } + } + } +} + +function validateName(context, node) { + // Ensure names are valid, however introspection types opt out. + if (node.name.startsWith('__')) { + context.reportError( + `Name "${node.name}" must not begin with "__", which is reserved by GraphQL introspection.`, + node.astNode, + ); + } +} + +function validateTypes(context) { + const validateInputObjectCircularRefs = + createInputObjectCircularRefsValidator(context); + const typeMap = context.schema.getTypeMap(); + + for (const type of Object.values(typeMap)) { + // Ensure all provided types are in fact GraphQL type. + if (!(0, _definition.isNamedType)(type)) { + context.reportError( + `Expected GraphQL named type but got: ${(0, _inspect.inspect)(type)}.`, + type.astNode, + ); + continue; + } // Ensure it is named correctly (excluding introspection types). + + if (!(0, _introspection.isIntrospectionType)(type)) { + validateName(context, type); + } + + if ((0, _definition.isObjectType)(type)) { + // Ensure fields are valid + validateFields(context, type); // Ensure objects implement the interfaces they claim to. + + validateInterfaces(context, type); + } else if ((0, _definition.isInterfaceType)(type)) { + // Ensure fields are valid. + validateFields(context, type); // Ensure interfaces implement the interfaces they claim to. + + validateInterfaces(context, type); + } else if ((0, _definition.isUnionType)(type)) { + // Ensure Unions include valid member types. + validateUnionMembers(context, type); + } else if ((0, _definition.isEnumType)(type)) { + // Ensure Enums have valid values. + validateEnumValues(context, type); + } else if ((0, _definition.isInputObjectType)(type)) { + // Ensure Input Object fields are valid. + validateInputFields(context, type); // Ensure Input Objects do not contain non-nullable circular references + + validateInputObjectCircularRefs(type); + } + } +} + +function validateFields(context, type) { + const fields = Object.values(type.getFields()); // Objects and Interfaces both must define one or more fields. + + if (fields.length === 0) { + context.reportError(`Type ${type.name} must define one or more fields.`, [ + type.astNode, + ...type.extensionASTNodes, + ]); + } + + for (const field of fields) { + // Ensure they are named correctly. + validateName(context, field); // Ensure the type is an output type + + if (!(0, _definition.isOutputType)(field.type)) { + var _field$astNode; + + context.reportError( + `The type of ${type.name}.${field.name} must be Output Type ` + + `but got: ${(0, _inspect.inspect)(field.type)}.`, + (_field$astNode = field.astNode) === null || _field$astNode === void 0 + ? void 0 + : _field$astNode.type, + ); + } // Ensure the arguments are valid + + for (const arg of field.args) { + const argName = arg.name; // Ensure they are named correctly. + + validateName(context, arg); // Ensure the type is an input type + + if (!(0, _definition.isInputType)(arg.type)) { + var _arg$astNode2; + + context.reportError( + `The type of ${type.name}.${field.name}(${argName}:) must be Input ` + + `Type but got: ${(0, _inspect.inspect)(arg.type)}.`, + (_arg$astNode2 = arg.astNode) === null || _arg$astNode2 === void 0 + ? void 0 + : _arg$astNode2.type, + ); + } + + if ( + (0, _definition.isRequiredArgument)(arg) && + arg.deprecationReason != null + ) { + var _arg$astNode3; + + context.reportError( + `Required argument ${type.name}.${field.name}(${argName}:) cannot be deprecated.`, + [ + getDeprecatedDirectiveNode(arg.astNode), + (_arg$astNode3 = arg.astNode) === null || _arg$astNode3 === void 0 + ? void 0 + : _arg$astNode3.type, + ], + ); + } + } + } +} + +function validateInterfaces(context, type) { + const ifaceTypeNames = Object.create(null); + + for (const iface of type.getInterfaces()) { + if (!(0, _definition.isInterfaceType)(iface)) { + context.reportError( + `Type ${(0, _inspect.inspect)( + type, + )} must only implement Interface types, ` + + `it cannot implement ${(0, _inspect.inspect)(iface)}.`, + getAllImplementsInterfaceNodes(type, iface), + ); + continue; + } + + if (type === iface) { + context.reportError( + `Type ${type.name} cannot implement itself because it would create a circular reference.`, + getAllImplementsInterfaceNodes(type, iface), + ); + continue; + } + + if (ifaceTypeNames[iface.name]) { + context.reportError( + `Type ${type.name} can only implement ${iface.name} once.`, + getAllImplementsInterfaceNodes(type, iface), + ); + continue; + } + + ifaceTypeNames[iface.name] = true; + validateTypeImplementsAncestors(context, type, iface); + validateTypeImplementsInterface(context, type, iface); + } +} + +function validateTypeImplementsInterface(context, type, iface) { + const typeFieldMap = type.getFields(); // Assert each interface field is implemented. + + for (const ifaceField of Object.values(iface.getFields())) { + const fieldName = ifaceField.name; + const typeField = typeFieldMap[fieldName]; // Assert interface field exists on type. + + if (!typeField) { + context.reportError( + `Interface field ${iface.name}.${fieldName} expected but ${type.name} does not provide it.`, + [ifaceField.astNode, type.astNode, ...type.extensionASTNodes], + ); + continue; + } // Assert interface field type is satisfied by type field type, by being + // a valid subtype. (covariant) + + if ( + !(0, _typeComparators.isTypeSubTypeOf)( + context.schema, + typeField.type, + ifaceField.type, + ) + ) { + var _ifaceField$astNode, _typeField$astNode; + + context.reportError( + `Interface field ${iface.name}.${fieldName} expects type ` + + `${(0, _inspect.inspect)(ifaceField.type)} but ${ + type.name + }.${fieldName} ` + + `is type ${(0, _inspect.inspect)(typeField.type)}.`, + [ + (_ifaceField$astNode = ifaceField.astNode) === null || + _ifaceField$astNode === void 0 + ? void 0 + : _ifaceField$astNode.type, + (_typeField$astNode = typeField.astNode) === null || + _typeField$astNode === void 0 + ? void 0 + : _typeField$astNode.type, + ], + ); + } // Assert each interface field arg is implemented. + + for (const ifaceArg of ifaceField.args) { + const argName = ifaceArg.name; + const typeArg = typeField.args.find((arg) => arg.name === argName); // Assert interface field arg exists on object field. + + if (!typeArg) { + context.reportError( + `Interface field argument ${iface.name}.${fieldName}(${argName}:) expected but ${type.name}.${fieldName} does not provide it.`, + [ifaceArg.astNode, typeField.astNode], + ); + continue; + } // Assert interface field arg type matches object field arg type. + // (invariant) + // TODO: change to contravariant? + + if (!(0, _typeComparators.isEqualType)(ifaceArg.type, typeArg.type)) { + var _ifaceArg$astNode, _typeArg$astNode; + + context.reportError( + `Interface field argument ${iface.name}.${fieldName}(${argName}:) ` + + `expects type ${(0, _inspect.inspect)(ifaceArg.type)} but ` + + `${type.name}.${fieldName}(${argName}:) is type ` + + `${(0, _inspect.inspect)(typeArg.type)}.`, + [ + (_ifaceArg$astNode = ifaceArg.astNode) === null || + _ifaceArg$astNode === void 0 + ? void 0 + : _ifaceArg$astNode.type, + (_typeArg$astNode = typeArg.astNode) === null || + _typeArg$astNode === void 0 + ? void 0 + : _typeArg$astNode.type, + ], + ); + } // TODO: validate default values? + } // Assert additional arguments must not be required. + + for (const typeArg of typeField.args) { + const argName = typeArg.name; + const ifaceArg = ifaceField.args.find((arg) => arg.name === argName); + + if (!ifaceArg && (0, _definition.isRequiredArgument)(typeArg)) { + context.reportError( + `Object field ${type.name}.${fieldName} includes required argument ${argName} that is missing from the Interface field ${iface.name}.${fieldName}.`, + [typeArg.astNode, ifaceField.astNode], + ); + } + } + } +} + +function validateTypeImplementsAncestors(context, type, iface) { + const ifaceInterfaces = type.getInterfaces(); + + for (const transitive of iface.getInterfaces()) { + if (!ifaceInterfaces.includes(transitive)) { + context.reportError( + transitive === type + ? `Type ${type.name} cannot implement ${iface.name} because it would create a circular reference.` + : `Type ${type.name} must implement ${transitive.name} because it is implemented by ${iface.name}.`, + [ + ...getAllImplementsInterfaceNodes(iface, transitive), + ...getAllImplementsInterfaceNodes(type, iface), + ], + ); + } + } +} + +function validateUnionMembers(context, union) { + const memberTypes = union.getTypes(); + + if (memberTypes.length === 0) { + context.reportError( + `Union type ${union.name} must define one or more member types.`, + [union.astNode, ...union.extensionASTNodes], + ); + } + + const includedTypeNames = Object.create(null); + + for (const memberType of memberTypes) { + if (includedTypeNames[memberType.name]) { + context.reportError( + `Union type ${union.name} can only include type ${memberType.name} once.`, + getUnionMemberTypeNodes(union, memberType.name), + ); + continue; + } + + includedTypeNames[memberType.name] = true; + + if (!(0, _definition.isObjectType)(memberType)) { + context.reportError( + `Union type ${union.name} can only include Object types, ` + + `it cannot include ${(0, _inspect.inspect)(memberType)}.`, + getUnionMemberTypeNodes(union, String(memberType)), + ); + } + } +} + +function validateEnumValues(context, enumType) { + const enumValues = enumType.getValues(); + + if (enumValues.length === 0) { + context.reportError( + `Enum type ${enumType.name} must define one or more values.`, + [enumType.astNode, ...enumType.extensionASTNodes], + ); + } + + for (const enumValue of enumValues) { + // Ensure valid name. + validateName(context, enumValue); + } +} + +function validateInputFields(context, inputObj) { + const fields = Object.values(inputObj.getFields()); + + if (fields.length === 0) { + context.reportError( + `Input Object type ${inputObj.name} must define one or more fields.`, + [inputObj.astNode, ...inputObj.extensionASTNodes], + ); + } // Ensure the arguments are valid + + for (const field of fields) { + // Ensure they are named correctly. + validateName(context, field); // Ensure the type is an input type + + if (!(0, _definition.isInputType)(field.type)) { + var _field$astNode2; + + context.reportError( + `The type of ${inputObj.name}.${field.name} must be Input Type ` + + `but got: ${(0, _inspect.inspect)(field.type)}.`, + (_field$astNode2 = field.astNode) === null || _field$astNode2 === void 0 + ? void 0 + : _field$astNode2.type, + ); + } + + if ( + (0, _definition.isRequiredInputField)(field) && + field.deprecationReason != null + ) { + var _field$astNode3; + + context.reportError( + `Required input field ${inputObj.name}.${field.name} cannot be deprecated.`, + [ + getDeprecatedDirectiveNode(field.astNode), + (_field$astNode3 = field.astNode) === null || + _field$astNode3 === void 0 + ? void 0 + : _field$astNode3.type, + ], + ); + } + + if (inputObj.isOneOf) { + validateOneOfInputObjectField(inputObj, field, context); + } + } +} + +function validateOneOfInputObjectField(type, field, context) { + if ((0, _definition.isNonNullType)(field.type)) { + var _field$astNode4; + + context.reportError( + `OneOf input field ${type.name}.${field.name} must be nullable.`, + (_field$astNode4 = field.astNode) === null || _field$astNode4 === void 0 + ? void 0 + : _field$astNode4.type, + ); + } + + if (field.defaultValue !== undefined) { + context.reportError( + `OneOf input field ${type.name}.${field.name} cannot have a default value.`, + field.astNode, + ); + } +} + +function createInputObjectCircularRefsValidator(context) { + // Modified copy of algorithm from 'src/validation/rules/NoFragmentCycles.js'. + // Tracks already visited types to maintain O(N) and to ensure that cycles + // are not redundantly reported. + const visitedTypes = Object.create(null); // Array of types nodes used to produce meaningful errors + + const fieldPath = []; // Position in the type path + + const fieldPathIndexByTypeName = Object.create(null); + return detectCycleRecursive; // This does a straight-forward DFS to find cycles. + // It does not terminate when a cycle was found but continues to explore + // the graph to find all possible cycles. + + function detectCycleRecursive(inputObj) { + if (visitedTypes[inputObj.name]) { + return; + } + + visitedTypes[inputObj.name] = true; + fieldPathIndexByTypeName[inputObj.name] = fieldPath.length; + const fields = Object.values(inputObj.getFields()); + + for (const field of fields) { + if ( + (0, _definition.isNonNullType)(field.type) && + (0, _definition.isInputObjectType)(field.type.ofType) + ) { + const fieldType = field.type.ofType; + const cycleIndex = fieldPathIndexByTypeName[fieldType.name]; + fieldPath.push(field); + + if (cycleIndex === undefined) { + detectCycleRecursive(fieldType); + } else { + const cyclePath = fieldPath.slice(cycleIndex); + const pathStr = cyclePath.map((fieldObj) => fieldObj.name).join('.'); + context.reportError( + `Cannot reference Input Object "${fieldType.name}" within itself through a series of non-null fields: "${pathStr}".`, + cyclePath.map((fieldObj) => fieldObj.astNode), + ); + } + + fieldPath.pop(); + } + } + + fieldPathIndexByTypeName[inputObj.name] = undefined; + } +} + +function getAllImplementsInterfaceNodes(type, iface) { + const { astNode, extensionASTNodes } = type; + const nodes = + astNode != null ? [astNode, ...extensionASTNodes] : extensionASTNodes; // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + return nodes + .flatMap((typeNode) => { + var _typeNode$interfaces; + + return ( + /* c8 ignore next */ + (_typeNode$interfaces = typeNode.interfaces) !== null && + _typeNode$interfaces !== void 0 + ? _typeNode$interfaces + : [] + ); + }) + .filter((ifaceNode) => ifaceNode.name.value === iface.name); +} + +function getUnionMemberTypeNodes(union, typeName) { + const { astNode, extensionASTNodes } = union; + const nodes = + astNode != null ? [astNode, ...extensionASTNodes] : extensionASTNodes; // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + return nodes + .flatMap((unionNode) => { + var _unionNode$types; + + return ( + /* c8 ignore next */ + (_unionNode$types = unionNode.types) !== null && + _unionNode$types !== void 0 + ? _unionNode$types + : [] + ); + }) + .filter((typeNode) => typeNode.name.value === typeName); +} + +function getDeprecatedDirectiveNode(definitionNode) { + var _definitionNode$direc; + + return definitionNode === null || definitionNode === void 0 + ? void 0 + : (_definitionNode$direc = definitionNode.directives) === null || + _definitionNode$direc === void 0 + ? void 0 + : _definitionNode$direc.find( + (node) => + node.name.value === _directives.GraphQLDeprecatedDirective.name, + ); +} + + +/***/ }), + +/***/ 76625: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, })); -Object.defineProperty(exports, "visitWithTypeInfo", ({ - enumerable: true, - get: function () { - return _index6.visitWithTypeInfo; - }, +exports.TypeInfo = void 0; +exports.visitWithTypeInfo = visitWithTypeInfo; + +var _ast = __nccwpck_require__(45494); + +var _kinds = __nccwpck_require__(11927); + +var _visitor = __nccwpck_require__(5678); + +var _definition = __nccwpck_require__(32150); + +var _introspection = __nccwpck_require__(28344); + +var _typeFromAST = __nccwpck_require__(27664); + +/** + * TypeInfo is a utility class which, given a GraphQL schema, can keep track + * of the current field and type definitions at any point in a GraphQL document + * AST during a recursive descent by calling `enter(node)` and `leave(node)`. + */ +class TypeInfo { + constructor( + schema, + /** + * Initial type may be provided in rare cases to facilitate traversals + * beginning somewhere other than documents. + */ + initialType, + /** @deprecated will be removed in 17.0.0 */ + getFieldDefFn, + ) { + this._schema = schema; + this._typeStack = []; + this._parentTypeStack = []; + this._inputTypeStack = []; + this._fieldDefStack = []; + this._defaultValueStack = []; + this._directive = null; + this._argument = null; + this._enumValue = null; + this._getFieldDef = + getFieldDefFn !== null && getFieldDefFn !== void 0 + ? getFieldDefFn + : getFieldDef; + + if (initialType) { + if ((0, _definition.isInputType)(initialType)) { + this._inputTypeStack.push(initialType); + } + + if ((0, _definition.isCompositeType)(initialType)) { + this._parentTypeStack.push(initialType); + } + + if ((0, _definition.isOutputType)(initialType)) { + this._typeStack.push(initialType); + } + } + } + + get [Symbol.toStringTag]() { + return 'TypeInfo'; + } + + getType() { + if (this._typeStack.length > 0) { + return this._typeStack[this._typeStack.length - 1]; + } + } + + getParentType() { + if (this._parentTypeStack.length > 0) { + return this._parentTypeStack[this._parentTypeStack.length - 1]; + } + } + + getInputType() { + if (this._inputTypeStack.length > 0) { + return this._inputTypeStack[this._inputTypeStack.length - 1]; + } + } + + getParentInputType() { + if (this._inputTypeStack.length > 1) { + return this._inputTypeStack[this._inputTypeStack.length - 2]; + } + } + + getFieldDef() { + if (this._fieldDefStack.length > 0) { + return this._fieldDefStack[this._fieldDefStack.length - 1]; + } + } + + getDefaultValue() { + if (this._defaultValueStack.length > 0) { + return this._defaultValueStack[this._defaultValueStack.length - 1]; + } + } + + getDirective() { + return this._directive; + } + + getArgument() { + return this._argument; + } + + getEnumValue() { + return this._enumValue; + } + + enter(node) { + const schema = this._schema; // Note: many of the types below are explicitly typed as "unknown" to drop + // any assumptions of a valid schema to ensure runtime types are properly + // checked before continuing since TypeInfo is used as part of validation + // which occurs before guarantees of schema and document validity. + + switch (node.kind) { + case _kinds.Kind.SELECTION_SET: { + const namedType = (0, _definition.getNamedType)(this.getType()); + + this._parentTypeStack.push( + (0, _definition.isCompositeType)(namedType) ? namedType : undefined, + ); + + break; + } + + case _kinds.Kind.FIELD: { + const parentType = this.getParentType(); + let fieldDef; + let fieldType; + + if (parentType) { + fieldDef = this._getFieldDef(schema, parentType, node); + + if (fieldDef) { + fieldType = fieldDef.type; + } + } + + this._fieldDefStack.push(fieldDef); + + this._typeStack.push( + (0, _definition.isOutputType)(fieldType) ? fieldType : undefined, + ); + + break; + } + + case _kinds.Kind.DIRECTIVE: + this._directive = schema.getDirective(node.name.value); + break; + + case _kinds.Kind.OPERATION_DEFINITION: { + const rootType = schema.getRootType(node.operation); + + this._typeStack.push( + (0, _definition.isObjectType)(rootType) ? rootType : undefined, + ); + + break; + } + + case _kinds.Kind.INLINE_FRAGMENT: + case _kinds.Kind.FRAGMENT_DEFINITION: { + const typeConditionAST = node.typeCondition; + const outputType = typeConditionAST + ? (0, _typeFromAST.typeFromAST)(schema, typeConditionAST) + : (0, _definition.getNamedType)(this.getType()); + + this._typeStack.push( + (0, _definition.isOutputType)(outputType) ? outputType : undefined, + ); + + break; + } + + case _kinds.Kind.VARIABLE_DEFINITION: { + const inputType = (0, _typeFromAST.typeFromAST)(schema, node.type); + + this._inputTypeStack.push( + (0, _definition.isInputType)(inputType) ? inputType : undefined, + ); + + break; + } + + case _kinds.Kind.ARGUMENT: { + var _this$getDirective; + + let argDef; + let argType; + const fieldOrDirective = + (_this$getDirective = this.getDirective()) !== null && + _this$getDirective !== void 0 + ? _this$getDirective + : this.getFieldDef(); + + if (fieldOrDirective) { + argDef = fieldOrDirective.args.find( + (arg) => arg.name === node.name.value, + ); + + if (argDef) { + argType = argDef.type; + } + } + + this._argument = argDef; + + this._defaultValueStack.push(argDef ? argDef.defaultValue : undefined); + + this._inputTypeStack.push( + (0, _definition.isInputType)(argType) ? argType : undefined, + ); + + break; + } + + case _kinds.Kind.LIST: { + const listType = (0, _definition.getNullableType)(this.getInputType()); + const itemType = (0, _definition.isListType)(listType) + ? listType.ofType + : listType; // List positions never have a default value. + + this._defaultValueStack.push(undefined); + + this._inputTypeStack.push( + (0, _definition.isInputType)(itemType) ? itemType : undefined, + ); + + break; + } + + case _kinds.Kind.OBJECT_FIELD: { + const objectType = (0, _definition.getNamedType)(this.getInputType()); + let inputFieldType; + let inputField; + + if ((0, _definition.isInputObjectType)(objectType)) { + inputField = objectType.getFields()[node.name.value]; + + if (inputField) { + inputFieldType = inputField.type; + } + } + + this._defaultValueStack.push( + inputField ? inputField.defaultValue : undefined, + ); + + this._inputTypeStack.push( + (0, _definition.isInputType)(inputFieldType) + ? inputFieldType + : undefined, + ); + + break; + } + + case _kinds.Kind.ENUM: { + const enumType = (0, _definition.getNamedType)(this.getInputType()); + let enumValue; + + if ((0, _definition.isEnumType)(enumType)) { + enumValue = enumType.getValue(node.value); + } + + this._enumValue = enumValue; + break; + } + + default: // Ignore other nodes + } + } + + leave(node) { + switch (node.kind) { + case _kinds.Kind.SELECTION_SET: + this._parentTypeStack.pop(); + + break; + + case _kinds.Kind.FIELD: + this._fieldDefStack.pop(); + + this._typeStack.pop(); + + break; + + case _kinds.Kind.DIRECTIVE: + this._directive = null; + break; + + case _kinds.Kind.OPERATION_DEFINITION: + case _kinds.Kind.INLINE_FRAGMENT: + case _kinds.Kind.FRAGMENT_DEFINITION: + this._typeStack.pop(); + + break; + + case _kinds.Kind.VARIABLE_DEFINITION: + this._inputTypeStack.pop(); + + break; + + case _kinds.Kind.ARGUMENT: + this._argument = null; + + this._defaultValueStack.pop(); + + this._inputTypeStack.pop(); + + break; + + case _kinds.Kind.LIST: + case _kinds.Kind.OBJECT_FIELD: + this._defaultValueStack.pop(); + + this._inputTypeStack.pop(); + + break; + + case _kinds.Kind.ENUM: + this._enumValue = null; + break; + + default: // Ignore other nodes + } + } +} + +exports.TypeInfo = TypeInfo; + +/** + * Not exactly the same as the executor's definition of getFieldDef, in this + * statically evaluated environment we do not always have an Object type, + * and need to handle Interface and Union types. + */ +function getFieldDef(schema, parentType, fieldNode) { + const name = fieldNode.name.value; + + if ( + name === _introspection.SchemaMetaFieldDef.name && + schema.getQueryType() === parentType + ) { + return _introspection.SchemaMetaFieldDef; + } + + if ( + name === _introspection.TypeMetaFieldDef.name && + schema.getQueryType() === parentType + ) { + return _introspection.TypeMetaFieldDef; + } + + if ( + name === _introspection.TypeNameMetaFieldDef.name && + (0, _definition.isCompositeType)(parentType) + ) { + return _introspection.TypeNameMetaFieldDef; + } + + if ( + (0, _definition.isObjectType)(parentType) || + (0, _definition.isInterfaceType)(parentType) + ) { + return parentType.getFields()[name]; + } +} +/** + * Creates a new visitor instance which maintains a provided TypeInfo instance + * along with visiting visitor. + */ + +function visitWithTypeInfo(typeInfo, visitor) { + return { + enter(...args) { + const node = args[0]; + typeInfo.enter(node); + const fn = (0, _visitor.getEnterLeaveForKind)(visitor, node.kind).enter; + + if (fn) { + const result = fn.apply(visitor, args); + + if (result !== undefined) { + typeInfo.leave(node); + + if ((0, _ast.isNode)(result)) { + typeInfo.enter(result); + } + } + + return result; + } + }, + + leave(...args) { + const node = args[0]; + const fn = (0, _visitor.getEnterLeaveForKind)(visitor, node.kind).leave; + let result; + + if (fn) { + result = fn.apply(visitor, args); + } + + typeInfo.leave(node); + return result; + }, + }; +} + + +/***/ }), + +/***/ 25780: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, })); +exports.assertValidName = assertValidName; +exports.isValidNameError = isValidNameError; -var _version = __nccwpck_require__(81923); +var _devAssert = __nccwpck_require__(46514); -var _graphql = __nccwpck_require__(64215); +var _GraphQLError = __nccwpck_require__(4797); -var _index = __nccwpck_require__(63280); +var _assertName = __nccwpck_require__(74947); -var _index2 = __nccwpck_require__(89537); +/* c8 ignore start */ -var _index3 = __nccwpck_require__(13176); +/** + * Upholds the spec rules about naming. + * @deprecated Please use `assertName` instead. Will be removed in v17 + */ +function assertValidName(name) { + const error = isValidNameError(name); -var _index4 = __nccwpck_require__(82201); + if (error) { + throw error; + } -var _index5 = __nccwpck_require__(50578); + return name; +} +/** + * Returns an Error if a name is invalid. + * @deprecated Please use `assertName` instead. Will be removed in v17 + */ -var _index6 = __nccwpck_require__(676); +function isValidNameError(name) { + typeof name === 'string' || + (0, _devAssert.devAssert)(false, 'Expected name to be a string.'); + + if (name.startsWith('__')) { + return new _GraphQLError.GraphQLError( + `Name "${name}" must not begin with "__", which is reserved by GraphQL introspection.`, + ); + } + + try { + (0, _assertName.assertName)(name); + } catch (error) { + return error; + } +} +/* c8 ignore stop */ /***/ }), -/***/ 11262: -/***/ ((__unused_webpack_module, exports) => { +/***/ 12653: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -279444,40 +281032,320 @@ var _index6 = __nccwpck_require__(676); Object.defineProperty(exports, "__esModule", ({ value: true, })); -exports.addPath = addPath; -exports.pathToArray = pathToArray; +exports.astFromValue = astFromValue; + +var _inspect = __nccwpck_require__(10102); + +var _invariant = __nccwpck_require__(28847); + +var _isIterableObject = __nccwpck_require__(81258); + +var _isObjectLike = __nccwpck_require__(95865); + +var _kinds = __nccwpck_require__(11927); + +var _definition = __nccwpck_require__(32150); + +var _scalars = __nccwpck_require__(93145); /** - * Given a Path and a key, return a new Path containing the new key. + * Produces a GraphQL Value AST given a JavaScript object. + * Function will match JavaScript/JSON values to GraphQL AST schema format + * by using suggested GraphQLInputType. For example: + * + * astFromValue("value", GraphQLString) + * + * A GraphQL type must be provided, which will be used to interpret different + * JavaScript values. + * + * | JSON Value | GraphQL Value | + * | ------------- | -------------------- | + * | Object | Input Object | + * | Array | List | + * | Boolean | Boolean | + * | String | String / Enum Value | + * | Number | Int / Float | + * | Unknown | Enum Value | + * | null | NullValue | + * */ -function addPath(prev, key, typename) { - return { - prev, - key, - typename, - }; +function astFromValue(value, type) { + if ((0, _definition.isNonNullType)(type)) { + const astValue = astFromValue(value, type.ofType); + + if ( + (astValue === null || astValue === void 0 ? void 0 : astValue.kind) === + _kinds.Kind.NULL + ) { + return null; + } + + return astValue; + } // only explicit null, not undefined, NaN + + if (value === null) { + return { + kind: _kinds.Kind.NULL, + }; + } // undefined + + if (value === undefined) { + return null; + } // Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but + // the value is not an array, convert the value using the list's item type. + + if ((0, _definition.isListType)(type)) { + const itemType = type.ofType; + + if ((0, _isIterableObject.isIterableObject)(value)) { + const valuesNodes = []; + + for (const item of value) { + const itemNode = astFromValue(item, itemType); + + if (itemNode != null) { + valuesNodes.push(itemNode); + } + } + + return { + kind: _kinds.Kind.LIST, + values: valuesNodes, + }; + } + + return astFromValue(value, itemType); + } // Populate the fields of the input object by creating ASTs from each value + // in the JavaScript object according to the fields in the input type. + + if ((0, _definition.isInputObjectType)(type)) { + if (!(0, _isObjectLike.isObjectLike)(value)) { + return null; + } + + const fieldNodes = []; + + for (const field of Object.values(type.getFields())) { + const fieldValue = astFromValue(value[field.name], field.type); + + if (fieldValue) { + fieldNodes.push({ + kind: _kinds.Kind.OBJECT_FIELD, + name: { + kind: _kinds.Kind.NAME, + value: field.name, + }, + value: fieldValue, + }); + } + } + + return { + kind: _kinds.Kind.OBJECT, + fields: fieldNodes, + }; + } + + if ((0, _definition.isLeafType)(type)) { + // Since value is an internally represented value, it must be serialized + // to an externally represented value before converting into an AST. + const serialized = type.serialize(value); + + if (serialized == null) { + return null; + } // Others serialize based on their corresponding JavaScript scalar types. + + if (typeof serialized === 'boolean') { + return { + kind: _kinds.Kind.BOOLEAN, + value: serialized, + }; + } // JavaScript numbers can be Int or Float values. + + if (typeof serialized === 'number' && Number.isFinite(serialized)) { + const stringNum = String(serialized); + return integerStringRegExp.test(stringNum) + ? { + kind: _kinds.Kind.INT, + value: stringNum, + } + : { + kind: _kinds.Kind.FLOAT, + value: stringNum, + }; + } + + if (typeof serialized === 'string') { + // Enum types use Enum literals. + if ((0, _definition.isEnumType)(type)) { + return { + kind: _kinds.Kind.ENUM, + value: serialized, + }; + } // ID types can use Int literals. + + if (type === _scalars.GraphQLID && integerStringRegExp.test(serialized)) { + return { + kind: _kinds.Kind.INT, + value: serialized, + }; + } + + return { + kind: _kinds.Kind.STRING, + value: serialized, + }; + } + + throw new TypeError( + `Cannot convert value to AST: ${(0, _inspect.inspect)(serialized)}.`, + ); + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered. + + false || + (0, _invariant.invariant)( + false, + 'Unexpected input type: ' + (0, _inspect.inspect)(type), + ); } /** - * Given a Path, return an Array of the path keys. + * IntValue: + * - NegativeSign? 0 + * - NegativeSign? NonZeroDigit ( Digit+ )? */ -function pathToArray(path) { - const flattened = []; - let curr = path; +const integerStringRegExp = /^-?(?:0|[1-9][0-9]*)$/; - while (curr) { - flattened.push(curr.key); - curr = curr.prev; + +/***/ }), + +/***/ 9337: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.buildASTSchema = buildASTSchema; +exports.buildSchema = buildSchema; + +var _devAssert = __nccwpck_require__(46514); + +var _kinds = __nccwpck_require__(11927); + +var _parser = __nccwpck_require__(50655); + +var _directives = __nccwpck_require__(83614); + +var _schema = __nccwpck_require__(8505); + +var _validate = __nccwpck_require__(14193); + +var _extendSchema = __nccwpck_require__(51832); + +/** + * This takes the ast of a schema document produced by the parse function in + * src/language/parser.js. + * + * If no schema definition is provided, then it will look for types named Query, + * Mutation and Subscription. + * + * Given that AST it constructs a GraphQLSchema. The resulting schema + * has no resolve methods, so execution will use default resolvers. + */ +function buildASTSchema(documentAST, options) { + (documentAST != null && documentAST.kind === _kinds.Kind.DOCUMENT) || + (0, _devAssert.devAssert)(false, 'Must provide valid Document AST.'); + + if ( + (options === null || options === void 0 ? void 0 : options.assumeValid) !== + true && + (options === null || options === void 0 + ? void 0 + : options.assumeValidSDL) !== true + ) { + (0, _validate.assertValidSDL)(documentAST); } - return flattened.reverse(); + const emptySchemaConfig = { + description: undefined, + types: [], + directives: [], + extensions: Object.create(null), + extensionASTNodes: [], + assumeValid: false, + }; + const config = (0, _extendSchema.extendSchemaImpl)( + emptySchemaConfig, + documentAST, + options, + ); + + if (config.astNode == null) { + for (const type of config.types) { + switch (type.name) { + // Note: While this could make early assertions to get the correctly + // typed values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + case 'Query': + // @ts-expect-error validated in `validateSchema` + config.query = type; + break; + + case 'Mutation': + // @ts-expect-error validated in `validateSchema` + config.mutation = type; + break; + + case 'Subscription': + // @ts-expect-error validated in `validateSchema` + config.subscription = type; + break; + } + } + } + + const directives = [ + ...config.directives, // If specified directives were not explicitly declared, add them. + ..._directives.specifiedDirectives.filter((stdDirective) => + config.directives.every( + (directive) => directive.name !== stdDirective.name, + ), + ), + ]; + return new _schema.GraphQLSchema({ ...config, directives }); +} +/** + * A helper function to build a GraphQLSchema directly from a source + * document. + */ + +function buildSchema(source, options) { + const document = (0, _parser.parse)(source, { + noLocation: + options === null || options === void 0 ? void 0 : options.noLocation, + allowLegacyFragmentVariables: + options === null || options === void 0 + ? void 0 + : options.allowLegacyFragmentVariables, + }); + return buildASTSchema(document, { + assumeValidSDL: + options === null || options === void 0 ? void 0 : options.assumeValidSDL, + assumeValid: + options === null || options === void 0 ? void 0 : options.assumeValid, + }); } /***/ }), -/***/ 46514: -/***/ ((__unused_webpack_module, exports) => { +/***/ 9352: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -279485,67 +281353,394 @@ function pathToArray(path) { Object.defineProperty(exports, "__esModule", ({ value: true, })); -exports.devAssert = devAssert; +exports.buildClientSchema = buildClientSchema; -function devAssert(condition, message) { - const booleanCondition = Boolean(condition); +var _devAssert = __nccwpck_require__(46514); + +var _inspect = __nccwpck_require__(10102); + +var _isObjectLike = __nccwpck_require__(95865); + +var _keyValMap = __nccwpck_require__(49268); + +var _parser = __nccwpck_require__(50655); + +var _definition = __nccwpck_require__(32150); + +var _directives = __nccwpck_require__(83614); + +var _introspection = __nccwpck_require__(28344); + +var _scalars = __nccwpck_require__(93145); + +var _schema = __nccwpck_require__(8505); + +var _valueFromAST = __nccwpck_require__(83181); + +/** + * Build a GraphQLSchema for use by client tools. + * + * Given the result of a client running the introspection query, creates and + * returns a GraphQLSchema instance which can be then used with all graphql-js + * tools, but cannot be used to execute a query, as introspection does not + * represent the "resolver", "parse" or "serialize" functions or any other + * server-internal mechanisms. + * + * This function expects a complete introspection result. Don't forget to check + * the "errors" field of a server response before calling this function. + */ +function buildClientSchema(introspection, options) { + ((0, _isObjectLike.isObjectLike)(introspection) && + (0, _isObjectLike.isObjectLike)(introspection.__schema)) || + (0, _devAssert.devAssert)( + false, + `Invalid or incomplete introspection result. Ensure that you are passing "data" property of introspection response and no "errors" was returned alongside: ${(0, + _inspect.inspect)(introspection)}.`, + ); // Get the schema from the introspection result. + + const schemaIntrospection = introspection.__schema; // Iterate through all types, getting the type definition for each. + + const typeMap = (0, _keyValMap.keyValMap)( + schemaIntrospection.types, + (typeIntrospection) => typeIntrospection.name, + (typeIntrospection) => buildType(typeIntrospection), + ); // Include standard types only if they are used. + + for (const stdType of [ + ..._scalars.specifiedScalarTypes, + ..._introspection.introspectionTypes, + ]) { + if (typeMap[stdType.name]) { + typeMap[stdType.name] = stdType; + } + } // Get the root Query, Mutation, and Subscription types. + + const queryType = schemaIntrospection.queryType + ? getObjectType(schemaIntrospection.queryType) + : null; + const mutationType = schemaIntrospection.mutationType + ? getObjectType(schemaIntrospection.mutationType) + : null; + const subscriptionType = schemaIntrospection.subscriptionType + ? getObjectType(schemaIntrospection.subscriptionType) + : null; // Get the directives supported by Introspection, assuming empty-set if + // directives were not queried for. + + const directives = schemaIntrospection.directives + ? schemaIntrospection.directives.map(buildDirective) + : []; // Then produce and return a Schema with these types. + + return new _schema.GraphQLSchema({ + description: schemaIntrospection.description, + query: queryType, + mutation: mutationType, + subscription: subscriptionType, + types: Object.values(typeMap), + directives, + assumeValid: + options === null || options === void 0 ? void 0 : options.assumeValid, + }); // Given a type reference in introspection, return the GraphQLType instance. + // preferring cached instances before building new instances. + + function getType(typeRef) { + if (typeRef.kind === _introspection.TypeKind.LIST) { + const itemRef = typeRef.ofType; + + if (!itemRef) { + throw new Error('Decorated type deeper than introspection query.'); + } + + return new _definition.GraphQLList(getType(itemRef)); + } + + if (typeRef.kind === _introspection.TypeKind.NON_NULL) { + const nullableRef = typeRef.ofType; + + if (!nullableRef) { + throw new Error('Decorated type deeper than introspection query.'); + } + + const nullableType = getType(nullableRef); + return new _definition.GraphQLNonNull( + (0, _definition.assertNullableType)(nullableType), + ); + } + + return getNamedType(typeRef); + } + + function getNamedType(typeRef) { + const typeName = typeRef.name; + + if (!typeName) { + throw new Error( + `Unknown type reference: ${(0, _inspect.inspect)(typeRef)}.`, + ); + } + + const type = typeMap[typeName]; + + if (!type) { + throw new Error( + `Invalid or incomplete schema, unknown type: ${typeName}. Ensure that a full introspection query is used in order to build a client schema.`, + ); + } + + return type; + } + + function getObjectType(typeRef) { + return (0, _definition.assertObjectType)(getNamedType(typeRef)); + } + + function getInterfaceType(typeRef) { + return (0, _definition.assertInterfaceType)(getNamedType(typeRef)); + } // Given a type's introspection result, construct the correct + // GraphQLType instance. + + function buildType(type) { + // eslint-disable-next-line @typescript-eslint/prefer-optional-chain + if (type != null && type.name != null && type.kind != null) { + // FIXME: Properly type IntrospectionType, it's a breaking change so fix in v17 + // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check + switch (type.kind) { + case _introspection.TypeKind.SCALAR: + return buildScalarDef(type); + + case _introspection.TypeKind.OBJECT: + return buildObjectDef(type); + + case _introspection.TypeKind.INTERFACE: + return buildInterfaceDef(type); + + case _introspection.TypeKind.UNION: + return buildUnionDef(type); + + case _introspection.TypeKind.ENUM: + return buildEnumDef(type); + + case _introspection.TypeKind.INPUT_OBJECT: + return buildInputObjectDef(type); + } + } + + const typeStr = (0, _inspect.inspect)(type); + throw new Error( + `Invalid or incomplete introspection result. Ensure that a full introspection query is used in order to build a client schema: ${typeStr}.`, + ); + } + + function buildScalarDef(scalarIntrospection) { + return new _definition.GraphQLScalarType({ + name: scalarIntrospection.name, + description: scalarIntrospection.description, + specifiedByURL: scalarIntrospection.specifiedByURL, + }); + } + + function buildImplementationsList(implementingIntrospection) { + // TODO: Temporary workaround until GraphQL ecosystem will fully support + // 'interfaces' on interface types. + if ( + implementingIntrospection.interfaces === null && + implementingIntrospection.kind === _introspection.TypeKind.INTERFACE + ) { + return []; + } + + if (!implementingIntrospection.interfaces) { + const implementingIntrospectionStr = (0, _inspect.inspect)( + implementingIntrospection, + ); + throw new Error( + `Introspection result missing interfaces: ${implementingIntrospectionStr}.`, + ); + } + + return implementingIntrospection.interfaces.map(getInterfaceType); + } + + function buildObjectDef(objectIntrospection) { + return new _definition.GraphQLObjectType({ + name: objectIntrospection.name, + description: objectIntrospection.description, + interfaces: () => buildImplementationsList(objectIntrospection), + fields: () => buildFieldDefMap(objectIntrospection), + }); + } + + function buildInterfaceDef(interfaceIntrospection) { + return new _definition.GraphQLInterfaceType({ + name: interfaceIntrospection.name, + description: interfaceIntrospection.description, + interfaces: () => buildImplementationsList(interfaceIntrospection), + fields: () => buildFieldDefMap(interfaceIntrospection), + }); + } + + function buildUnionDef(unionIntrospection) { + if (!unionIntrospection.possibleTypes) { + const unionIntrospectionStr = (0, _inspect.inspect)(unionIntrospection); + throw new Error( + `Introspection result missing possibleTypes: ${unionIntrospectionStr}.`, + ); + } + + return new _definition.GraphQLUnionType({ + name: unionIntrospection.name, + description: unionIntrospection.description, + types: () => unionIntrospection.possibleTypes.map(getObjectType), + }); + } + + function buildEnumDef(enumIntrospection) { + if (!enumIntrospection.enumValues) { + const enumIntrospectionStr = (0, _inspect.inspect)(enumIntrospection); + throw new Error( + `Introspection result missing enumValues: ${enumIntrospectionStr}.`, + ); + } + + return new _definition.GraphQLEnumType({ + name: enumIntrospection.name, + description: enumIntrospection.description, + values: (0, _keyValMap.keyValMap)( + enumIntrospection.enumValues, + (valueIntrospection) => valueIntrospection.name, + (valueIntrospection) => ({ + description: valueIntrospection.description, + deprecationReason: valueIntrospection.deprecationReason, + }), + ), + }); + } + + function buildInputObjectDef(inputObjectIntrospection) { + if (!inputObjectIntrospection.inputFields) { + const inputObjectIntrospectionStr = (0, _inspect.inspect)( + inputObjectIntrospection, + ); + throw new Error( + `Introspection result missing inputFields: ${inputObjectIntrospectionStr}.`, + ); + } + + return new _definition.GraphQLInputObjectType({ + name: inputObjectIntrospection.name, + description: inputObjectIntrospection.description, + fields: () => buildInputValueDefMap(inputObjectIntrospection.inputFields), + isOneOf: inputObjectIntrospection.isOneOf, + }); + } + + function buildFieldDefMap(typeIntrospection) { + if (!typeIntrospection.fields) { + throw new Error( + `Introspection result missing fields: ${(0, _inspect.inspect)( + typeIntrospection, + )}.`, + ); + } - if (!booleanCondition) { - throw new Error(message); + return (0, _keyValMap.keyValMap)( + typeIntrospection.fields, + (fieldIntrospection) => fieldIntrospection.name, + buildField, + ); } -} + function buildField(fieldIntrospection) { + const type = getType(fieldIntrospection.type); -/***/ }), + if (!(0, _definition.isOutputType)(type)) { + const typeStr = (0, _inspect.inspect)(type); + throw new Error( + `Introspection must provide output type for fields, but received: ${typeStr}.`, + ); + } -/***/ 42878: -/***/ ((__unused_webpack_module, exports) => { + if (!fieldIntrospection.args) { + const fieldIntrospectionStr = (0, _inspect.inspect)(fieldIntrospection); + throw new Error( + `Introspection result missing field args: ${fieldIntrospectionStr}.`, + ); + } -"use strict"; + return { + description: fieldIntrospection.description, + deprecationReason: fieldIntrospection.deprecationReason, + type, + args: buildInputValueDefMap(fieldIntrospection.args), + }; + } + function buildInputValueDefMap(inputValueIntrospections) { + return (0, _keyValMap.keyValMap)( + inputValueIntrospections, + (inputValue) => inputValue.name, + buildInputValue, + ); + } -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.didYouMean = didYouMean; -const MAX_SUGGESTIONS = 5; -/** - * Given [ A, B, C ] return ' Did you mean A, B, or C?'. - */ + function buildInputValue(inputValueIntrospection) { + const type = getType(inputValueIntrospection.type); -function didYouMean(firstArg, secondArg) { - const [subMessage, suggestionsArg] = secondArg - ? [firstArg, secondArg] - : [undefined, firstArg]; - let message = ' Did you mean '; + if (!(0, _definition.isInputType)(type)) { + const typeStr = (0, _inspect.inspect)(type); + throw new Error( + `Introspection must provide input type for arguments, but received: ${typeStr}.`, + ); + } - if (subMessage) { - message += subMessage + ' '; + const defaultValue = + inputValueIntrospection.defaultValue != null + ? (0, _valueFromAST.valueFromAST)( + (0, _parser.parseValue)(inputValueIntrospection.defaultValue), + type, + ) + : undefined; + return { + description: inputValueIntrospection.description, + type, + defaultValue, + deprecationReason: inputValueIntrospection.deprecationReason, + }; } - const suggestions = suggestionsArg.map((x) => `"${x}"`); - - switch (suggestions.length) { - case 0: - return ''; + function buildDirective(directiveIntrospection) { + if (!directiveIntrospection.args) { + const directiveIntrospectionStr = (0, _inspect.inspect)( + directiveIntrospection, + ); + throw new Error( + `Introspection result missing directive args: ${directiveIntrospectionStr}.`, + ); + } - case 1: - return message + suggestions[0] + '?'; + if (!directiveIntrospection.locations) { + const directiveIntrospectionStr = (0, _inspect.inspect)( + directiveIntrospection, + ); + throw new Error( + `Introspection result missing directive locations: ${directiveIntrospectionStr}.`, + ); + } - case 2: - return message + suggestions[0] + ' or ' + suggestions[1] + '?'; + return new _directives.GraphQLDirective({ + name: directiveIntrospection.name, + description: directiveIntrospection.description, + isRepeatable: directiveIntrospection.isRepeatable, + locations: directiveIntrospection.locations.slice(), + args: buildInputValueDefMap(directiveIntrospection.args), + }); } - - const selected = suggestions.slice(0, MAX_SUGGESTIONS); - const lastItem = selected.pop(); - return message + selected.join(', ') + ', or ' + lastItem + '?'; } /***/ }), -/***/ 93173: -/***/ ((__unused_webpack_module, exports) => { +/***/ 39603: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -279553,182 +281748,223 @@ function didYouMean(firstArg, secondArg) { Object.defineProperty(exports, "__esModule", ({ value: true, })); -exports.groupBy = groupBy; +exports.coerceInputValue = coerceInputValue; -/** - * Groups array items into a Map, given a function to produce grouping key. - */ -function groupBy(list, keyFn) { - const result = new Map(); +var _didYouMean = __nccwpck_require__(42878); - for (const item of list) { - const key = keyFn(item); - const group = result.get(key); +var _inspect = __nccwpck_require__(10102); - if (group === undefined) { - result.set(key, [item]); - } else { - group.push(item); - } - } +var _invariant = __nccwpck_require__(28847); - return result; -} +var _isIterableObject = __nccwpck_require__(81258); +var _isObjectLike = __nccwpck_require__(95865); -/***/ }), +var _Path = __nccwpck_require__(11262); -/***/ 51188: -/***/ ((__unused_webpack_module, exports) => { +var _printPathArray = __nccwpck_require__(94281); -"use strict"; +var _suggestionList = __nccwpck_require__(57704); +var _GraphQLError = __nccwpck_require__(4797); -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.identityFunc = identityFunc; +var _definition = __nccwpck_require__(32150); /** - * Returns the first argument it receives. + * Coerces a JavaScript value given a GraphQL Input Type. */ -function identityFunc(x) { - return x; +function coerceInputValue(inputValue, type, onError = defaultOnError) { + return coerceInputValueImpl(inputValue, type, onError, undefined); } +function defaultOnError(path, invalidValue, error) { + let errorPrefix = 'Invalid value ' + (0, _inspect.inspect)(invalidValue); -/***/ }), - -/***/ 10102: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.inspect = inspect; -const MAX_ARRAY_LENGTH = 10; -const MAX_RECURSIVE_DEPTH = 2; -/** - * Used to print values in error messages. - */ + if (path.length > 0) { + errorPrefix += ` at "value${(0, _printPathArray.printPathArray)(path)}"`; + } -function inspect(value) { - return formatValue(value, []); + error.message = errorPrefix + ': ' + error.message; + throw error; } -function formatValue(value, seenValues) { - switch (typeof value) { - case 'string': - return JSON.stringify(value); - - case 'function': - return value.name ? `[function ${value.name}]` : '[function]'; - - case 'object': - return formatObjectValue(value, seenValues); +function coerceInputValueImpl(inputValue, type, onError, path) { + if ((0, _definition.isNonNullType)(type)) { + if (inputValue != null) { + return coerceInputValueImpl(inputValue, type.ofType, onError, path); + } - default: - return String(value); + onError( + (0, _Path.pathToArray)(path), + inputValue, + new _GraphQLError.GraphQLError( + `Expected non-nullable type "${(0, _inspect.inspect)( + type, + )}" not to be null.`, + ), + ); + return; } -} -function formatObjectValue(value, previouslySeenValues) { - if (value === null) { - return 'null'; + if (inputValue == null) { + // Explicitly return the value null. + return null; } - if (previouslySeenValues.includes(value)) { - return '[Circular]'; - } + if ((0, _definition.isListType)(type)) { + const itemType = type.ofType; - const seenValues = [...previouslySeenValues, value]; + if ((0, _isIterableObject.isIterableObject)(inputValue)) { + return Array.from(inputValue, (itemValue, index) => { + const itemPath = (0, _Path.addPath)(path, index, undefined); + return coerceInputValueImpl(itemValue, itemType, onError, itemPath); + }); + } // Lists accept a non-list value as a list of one. - if (isJSONable(value)) { - const jsonValue = value.toJSON(); // check for infinite recursion + return [coerceInputValueImpl(inputValue, itemType, onError, path)]; + } - if (jsonValue !== value) { - return typeof jsonValue === 'string' - ? jsonValue - : formatValue(jsonValue, seenValues); + if ((0, _definition.isInputObjectType)(type)) { + if ( + !(0, _isObjectLike.isObjectLike)(inputValue) || + Array.isArray(inputValue) + ) { + onError( + (0, _Path.pathToArray)(path), + inputValue, + new _GraphQLError.GraphQLError( + `Expected type "${type.name}" to be an object.`, + ), + ); + return; } - } else if (Array.isArray(value)) { - return formatArray(value, seenValues); - } - return formatObject(value, seenValues); -} + const coercedValue = {}; + const fieldDefs = type.getFields(); -function isJSONable(value) { - return typeof value.toJSON === 'function'; -} + for (const field of Object.values(fieldDefs)) { + const fieldValue = inputValue[field.name]; -function formatObject(object, seenValues) { - const entries = Object.entries(object); + if (fieldValue === undefined) { + if (field.defaultValue !== undefined) { + coercedValue[field.name] = field.defaultValue; + } else if ((0, _definition.isNonNullType)(field.type)) { + const typeStr = (0, _inspect.inspect)(field.type); + onError( + (0, _Path.pathToArray)(path), + inputValue, + new _GraphQLError.GraphQLError( + `Field "${field.name}" of required type "${typeStr}" was not provided.`, + ), + ); + } - if (entries.length === 0) { - return '{}'; - } + continue; + } - if (seenValues.length > MAX_RECURSIVE_DEPTH) { - return '[' + getObjectTag(object) + ']'; - } + coercedValue[field.name] = coerceInputValueImpl( + fieldValue, + field.type, + onError, + (0, _Path.addPath)(path, field.name, type.name), + ); + } // Ensure every provided field is defined. - const properties = entries.map( - ([key, value]) => key + ': ' + formatValue(value, seenValues), - ); - return '{ ' + properties.join(', ') + ' }'; -} + for (const fieldName of Object.keys(inputValue)) { + if (!fieldDefs[fieldName]) { + const suggestions = (0, _suggestionList.suggestionList)( + fieldName, + Object.keys(type.getFields()), + ); + onError( + (0, _Path.pathToArray)(path), + inputValue, + new _GraphQLError.GraphQLError( + `Field "${fieldName}" is not defined by type "${type.name}".` + + (0, _didYouMean.didYouMean)(suggestions), + ), + ); + } + } -function formatArray(array, seenValues) { - if (array.length === 0) { - return '[]'; - } + if (type.isOneOf) { + const keys = Object.keys(coercedValue); - if (seenValues.length > MAX_RECURSIVE_DEPTH) { - return '[Array]'; - } + if (keys.length !== 1) { + onError( + (0, _Path.pathToArray)(path), + inputValue, + new _GraphQLError.GraphQLError( + `Exactly one key must be specified for OneOf type "${type.name}".`, + ), + ); + } - const len = Math.min(MAX_ARRAY_LENGTH, array.length); - const remaining = array.length - len; - const items = []; + const key = keys[0]; + const value = coercedValue[key]; - for (let i = 0; i < len; ++i) { - items.push(formatValue(array[i], seenValues)); - } + if (value === null) { + onError( + (0, _Path.pathToArray)(path).concat(key), + value, + new _GraphQLError.GraphQLError(`Field "${key}" must be non-null.`), + ); + } + } - if (remaining === 1) { - items.push('... 1 more item'); - } else if (remaining > 1) { - items.push(`... ${remaining} more items`); + return coercedValue; } - return '[' + items.join(', ') + ']'; -} + if ((0, _definition.isLeafType)(type)) { + let parseResult; // Scalars and Enums determine if a input value is valid via parseValue(), + // which can throw to indicate failure. If it throws, maintain a reference + // to the original error. -function getObjectTag(object) { - const tag = Object.prototype.toString - .call(object) - .replace(/^\[object /, '') - .replace(/]$/, ''); + try { + parseResult = type.parseValue(inputValue); + } catch (error) { + if (error instanceof _GraphQLError.GraphQLError) { + onError((0, _Path.pathToArray)(path), inputValue, error); + } else { + onError( + (0, _Path.pathToArray)(path), + inputValue, + new _GraphQLError.GraphQLError( + `Expected type "${type.name}". ` + error.message, + { + originalError: error, + }, + ), + ); + } - if (tag === 'Object' && typeof object.constructor === 'function') { - const name = object.constructor.name; + return; + } - if (typeof name === 'string' && name !== '') { - return name; + if (parseResult === undefined) { + onError( + (0, _Path.pathToArray)(path), + inputValue, + new _GraphQLError.GraphQLError(`Expected type "${type.name}".`), + ); } + + return parseResult; } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered. - return tag; + false || + (0, _invariant.invariant)( + false, + 'Unexpected input type: ' + (0, _inspect.inspect)(type), + ); } /***/ }), -/***/ 93481: +/***/ 17232: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -279737,122 +281973,33 @@ function getObjectTag(object) { Object.defineProperty(exports, "__esModule", ({ value: true, })); -exports.instanceOf = void 0; +exports.concatAST = concatAST; -var _inspect = __nccwpck_require__(10102); +var _kinds = __nccwpck_require__(11927); -/* c8 ignore next 3 */ -const isProduction = - globalThis.process && // eslint-disable-next-line no-undef - process.env.NODE_ENV === 'production'; /** - * A replacement for instanceof which includes an error warning when multi-realm - * constructors are detected. - * See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production - * See: https://webpack.js.org/guides/production/ + * Provided a collection of ASTs, presumably each from different files, + * concatenate the ASTs together into batched AST, useful for validating many + * GraphQL source files which together represent one conceptual application. */ +function concatAST(documents) { + const definitions = []; -const instanceOf = - /* c8 ignore next 6 */ - // FIXME: https://github.com/graphql/graphql-js/issues/2317 - isProduction - ? function instanceOf(value, constructor) { - return value instanceof constructor; - } - : function instanceOf(value, constructor) { - if (value instanceof constructor) { - return true; - } - - if (typeof value === 'object' && value !== null) { - var _value$constructor; - - // Prefer Symbol.toStringTag since it is immune to minification. - const className = constructor.prototype[Symbol.toStringTag]; - const valueClassName = // We still need to support constructor's name to detect conflicts with older versions of this library. - Symbol.toStringTag in value // @ts-expect-error TS bug see, https://github.com/microsoft/TypeScript/issues/38009 - ? value[Symbol.toStringTag] - : (_value$constructor = value.constructor) === null || - _value$constructor === void 0 - ? void 0 - : _value$constructor.name; - - if (className === valueClassName) { - const stringifiedValue = (0, _inspect.inspect)(value); - throw new Error(`Cannot use ${className} "${stringifiedValue}" from another module or realm. - -Ensure that there is only one instance of "graphql" in the node_modules -directory. If different versions of "graphql" are the dependencies of other -relied on modules, use "resolutions" to ensure only one version is installed. - -https://yarnpkg.com/en/docs/selective-version-resolutions - -Duplicate "graphql" modules cannot be used at the same time since different -versions may have different capabilities and behavior. The data from one -version used in the function from another could produce confusing and -spurious results.`); - } - } - - return false; - }; -exports.instanceOf = instanceOf; - - -/***/ }), - -/***/ 28847: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.invariant = invariant; - -function invariant(condition, message) { - const booleanCondition = Boolean(condition); - - if (!booleanCondition) { - throw new Error( - message != null ? message : 'Unexpected invariant triggered.', - ); + for (const doc of documents) { + definitions.push(...doc.definitions); } -} - - -/***/ }), - -/***/ 20626: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.isAsyncIterable = isAsyncIterable; -/** - * Returns true if the provided object implements the AsyncIterator protocol via - * implementing a `Symbol.asyncIterator` method. - */ -function isAsyncIterable(maybeAsyncIterable) { - return ( - typeof (maybeAsyncIterable === null || maybeAsyncIterable === void 0 - ? void 0 - : maybeAsyncIterable[Symbol.asyncIterator]) === 'function' - ); + return { + kind: _kinds.Kind.DOCUMENT, + definitions, + }; } /***/ }), -/***/ 81258: -/***/ ((__unused_webpack_module, exports) => { +/***/ 51832: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -279860,605 +282007,815 @@ function isAsyncIterable(maybeAsyncIterable) { Object.defineProperty(exports, "__esModule", ({ value: true, })); -exports.isIterableObject = isIterableObject; - -/** - * Returns true if the provided object is an Object (i.e. not a string literal) - * and implements the Iterator protocol. - * - * This may be used in place of [Array.isArray()][isArray] to determine if - * an object should be iterated-over e.g. Array, Map, Set, Int8Array, - * TypedArray, etc. but excludes string literals. - * - * @example - * ```ts - * isIterableObject([ 1, 2, 3 ]) // true - * isIterableObject(new Map()) // true - * isIterableObject('ABC') // false - * isIterableObject({ key: 'value' }) // false - * isIterableObject({ length: 1, 0: 'Alpha' }) // false - * ``` - */ -function isIterableObject(maybeIterable) { - return ( - typeof maybeIterable === 'object' && - typeof (maybeIterable === null || maybeIterable === void 0 - ? void 0 - : maybeIterable[Symbol.iterator]) === 'function' - ); -} - - -/***/ }), - -/***/ 95865: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - +exports.extendSchema = extendSchema; +exports.extendSchemaImpl = extendSchemaImpl; -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.isObjectLike = isObjectLike; +var _devAssert = __nccwpck_require__(46514); -/** - * Return true if `value` is object-like. A value is object-like if it's not - * `null` and has a `typeof` result of "object". - */ -function isObjectLike(value) { - return typeof value == 'object' && value !== null; -} +var _inspect = __nccwpck_require__(10102); +var _invariant = __nccwpck_require__(28847); -/***/ }), +var _keyMap = __nccwpck_require__(10711); -/***/ 93910: -/***/ ((__unused_webpack_module, exports) => { +var _mapValue = __nccwpck_require__(32223); -"use strict"; +var _kinds = __nccwpck_require__(11927); +var _predicates = __nccwpck_require__(20535); -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.isPromise = isPromise; +var _definition = __nccwpck_require__(32150); -/** - * Returns true if the value acts like a Promise, i.e. has a "then" function, - * otherwise returns false. - */ -function isPromise(value) { - return ( - typeof (value === null || value === void 0 ? void 0 : value.then) === - 'function' - ); -} +var _directives = __nccwpck_require__(83614); +var _introspection = __nccwpck_require__(28344); -/***/ }), +var _scalars = __nccwpck_require__(93145); -/***/ 10711: -/***/ ((__unused_webpack_module, exports) => { +var _schema = __nccwpck_require__(8505); -"use strict"; +var _validate = __nccwpck_require__(14193); +var _values = __nccwpck_require__(94834); -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.keyMap = keyMap; +var _valueFromAST = __nccwpck_require__(83181); /** - * Creates a keyed JS object from an array, given a function to produce the keys - * for each value in the array. - * - * This provides a convenient lookup for the array items if the key function - * produces unique results. - * ```ts - * const phoneBook = [ - * { name: 'Jon', num: '555-1234' }, - * { name: 'Jenny', num: '867-5309' } - * ] - * - * const entriesByName = keyMap( - * phoneBook, - * entry => entry.name - * ) - * - * // { - * // Jon: { name: 'Jon', num: '555-1234' }, - * // Jenny: { name: 'Jenny', num: '867-5309' } - * // } + * Produces a new schema given an existing schema and a document which may + * contain GraphQL type extensions and definitions. The original schema will + * remain unaltered. * - * const jennyEntry = entriesByName['Jenny'] + * Because a schema represents a graph of references, a schema cannot be + * extended without effectively making an entire copy. We do not know until it's + * too late if subgraphs remain unchanged. * - * // { name: 'Jenny', num: '857-6309' } - * ``` + * This algorithm copies the provided schema, applying extensions while + * producing the copy. The original schema remains unaltered. */ -function keyMap(list, keyFn) { - const result = Object.create(null); +function extendSchema(schema, documentAST, options) { + (0, _schema.assertSchema)(schema); + (documentAST != null && documentAST.kind === _kinds.Kind.DOCUMENT) || + (0, _devAssert.devAssert)(false, 'Must provide valid Document AST.'); - for (const item of list) { - result[keyFn(item)] = item; + if ( + (options === null || options === void 0 ? void 0 : options.assumeValid) !== + true && + (options === null || options === void 0 + ? void 0 + : options.assumeValidSDL) !== true + ) { + (0, _validate.assertValidSDLExtension)(documentAST, schema); } - return result; + const schemaConfig = schema.toConfig(); + const extendedConfig = extendSchemaImpl(schemaConfig, documentAST, options); + return schemaConfig === extendedConfig + ? schema + : new _schema.GraphQLSchema(extendedConfig); } - - -/***/ }), - -/***/ 49268: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.keyValMap = keyValMap; - /** - * Creates a keyed JS object from an array, given a function to produce the keys - * and a function to produce the values from each item in the array. - * ```ts - * const phoneBook = [ - * { name: 'Jon', num: '555-1234' }, - * { name: 'Jenny', num: '867-5309' } - * ] - * - * // { Jon: '555-1234', Jenny: '867-5309' } - * const phonesByName = keyValMap( - * phoneBook, - * entry => entry.name, - * entry => entry.num - * ) - * ``` + * @internal */ -function keyValMap(list, keyFn, valFn) { - const result = Object.create(null); - for (const item of list) { - result[keyFn(item)] = valFn(item); - } +function extendSchemaImpl(schemaConfig, documentAST, options) { + var _schemaDef, _schemaDef$descriptio, _schemaDef2, _options$assumeValid; - return result; -} + // Collect the type definitions and extensions found in the document. + const typeDefs = []; + const typeExtensionsMap = Object.create(null); // New directives and types are separate because a directives and types can + // have the same name. For example, a type named "skip". + const directiveDefs = []; + let schemaDef; // Schema extensions are collected which may add additional operation types. -/***/ }), + const schemaExtensions = []; -/***/ 32223: -/***/ ((__unused_webpack_module, exports) => { + for (const def of documentAST.definitions) { + if (def.kind === _kinds.Kind.SCHEMA_DEFINITION) { + schemaDef = def; + } else if (def.kind === _kinds.Kind.SCHEMA_EXTENSION) { + schemaExtensions.push(def); + } else if ((0, _predicates.isTypeDefinitionNode)(def)) { + typeDefs.push(def); + } else if ((0, _predicates.isTypeExtensionNode)(def)) { + const extendedTypeName = def.name.value; + const existingTypeExtensions = typeExtensionsMap[extendedTypeName]; + typeExtensionsMap[extendedTypeName] = existingTypeExtensions + ? existingTypeExtensions.concat([def]) + : [def]; + } else if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + directiveDefs.push(def); + } + } // If this document contains no new types, extensions, or directives then + // return the same unmodified GraphQLSchema instance. -"use strict"; + if ( + Object.keys(typeExtensionsMap).length === 0 && + typeDefs.length === 0 && + directiveDefs.length === 0 && + schemaExtensions.length === 0 && + schemaDef == null + ) { + return schemaConfig; + } + const typeMap = Object.create(null); -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.mapValue = mapValue; + for (const existingType of schemaConfig.types) { + typeMap[existingType.name] = extendNamedType(existingType); + } -/** - * Creates an object map with the same keys as `map` and values generated by - * running each value of `map` thru `fn`. - */ -function mapValue(map, fn) { - const result = Object.create(null); + for (const typeNode of typeDefs) { + var _stdTypeMap$name; - for (const key of Object.keys(map)) { - result[key] = fn(map[key], key); + const name = typeNode.name.value; + typeMap[name] = + (_stdTypeMap$name = stdTypeMap[name]) !== null && + _stdTypeMap$name !== void 0 + ? _stdTypeMap$name + : buildType(typeNode); } - return result; -} + const operationTypes = { + // Get the extended root operation types. + query: schemaConfig.query && replaceNamedType(schemaConfig.query), + mutation: schemaConfig.mutation && replaceNamedType(schemaConfig.mutation), + subscription: + schemaConfig.subscription && replaceNamedType(schemaConfig.subscription), + // Then, incorporate schema definition and all schema extensions. + ...(schemaDef && getOperationTypes([schemaDef])), + ...getOperationTypes(schemaExtensions), + }; // Then produce and return a Schema config with these types. + return { + description: + (_schemaDef = schemaDef) === null || _schemaDef === void 0 + ? void 0 + : (_schemaDef$descriptio = _schemaDef.description) === null || + _schemaDef$descriptio === void 0 + ? void 0 + : _schemaDef$descriptio.value, + ...operationTypes, + types: Object.values(typeMap), + directives: [ + ...schemaConfig.directives.map(replaceDirective), + ...directiveDefs.map(buildDirective), + ], + extensions: Object.create(null), + astNode: + (_schemaDef2 = schemaDef) !== null && _schemaDef2 !== void 0 + ? _schemaDef2 + : schemaConfig.astNode, + extensionASTNodes: schemaConfig.extensionASTNodes.concat(schemaExtensions), + assumeValid: + (_options$assumeValid = + options === null || options === void 0 + ? void 0 + : options.assumeValid) !== null && _options$assumeValid !== void 0 + ? _options$assumeValid + : false, + }; // Below are functions used for producing this schema that have closed over + // this scope and have access to the schema, cache, and newly defined types. -/***/ }), + function replaceType(type) { + if ((0, _definition.isListType)(type)) { + // @ts-expect-error + return new _definition.GraphQLList(replaceType(type.ofType)); + } -/***/ 64217: -/***/ ((__unused_webpack_module, exports) => { + if ((0, _definition.isNonNullType)(type)) { + // @ts-expect-error + return new _definition.GraphQLNonNull(replaceType(type.ofType)); + } // @ts-expect-error FIXME -"use strict"; + return replaceNamedType(type); + } + function replaceNamedType(type) { + // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + return typeMap[type.name]; + } -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.memoize3 = memoize3; + function replaceDirective(directive) { + const config = directive.toConfig(); + return new _directives.GraphQLDirective({ + ...config, + args: (0, _mapValue.mapValue)(config.args, extendArg), + }); + } -/** - * Memoizes the provided three-argument function. - */ -function memoize3(fn) { - let cache0; - return function memoized(a1, a2, a3) { - if (cache0 === undefined) { - cache0 = new WeakMap(); + function extendNamedType(type) { + if ( + (0, _introspection.isIntrospectionType)(type) || + (0, _scalars.isSpecifiedScalarType)(type) + ) { + // Builtin types are not extended. + return type; } - let cache1 = cache0.get(a1); - - if (cache1 === undefined) { - cache1 = new WeakMap(); - cache0.set(a1, cache1); + if ((0, _definition.isScalarType)(type)) { + return extendScalarType(type); } - let cache2 = cache1.get(a2); - - if (cache2 === undefined) { - cache2 = new WeakMap(); - cache1.set(a2, cache2); + if ((0, _definition.isObjectType)(type)) { + return extendObjectType(type); } - let fnResult = cache2.get(a3); - - if (fnResult === undefined) { - fnResult = fn(a1, a2, a3); - cache2.set(a3, fnResult); + if ((0, _definition.isInterfaceType)(type)) { + return extendInterfaceType(type); } - return fnResult; - }; -} + if ((0, _definition.isUnionType)(type)) { + return extendUnionType(type); + } + if ((0, _definition.isEnumType)(type)) { + return extendEnumType(type); + } -/***/ }), + if ((0, _definition.isInputObjectType)(type)) { + return extendInputObjectType(type); + } + /* c8 ignore next 3 */ + // Not reachable, all possible type definition nodes have been considered. -/***/ 20038: -/***/ ((__unused_webpack_module, exports) => { + false || + (0, _invariant.invariant)( + false, + 'Unexpected type: ' + (0, _inspect.inspect)(type), + ); + } -"use strict"; + function extendInputObjectType(type) { + var _typeExtensionsMap$co; + const config = type.toConfig(); + const extensions = + (_typeExtensionsMap$co = typeExtensionsMap[config.name]) !== null && + _typeExtensionsMap$co !== void 0 + ? _typeExtensionsMap$co + : []; + return new _definition.GraphQLInputObjectType({ + ...config, + fields: () => ({ + ...(0, _mapValue.mapValue)(config.fields, (field) => ({ + ...field, + type: replaceType(field.type), + })), + ...buildInputFieldMap(extensions), + }), + extensionASTNodes: config.extensionASTNodes.concat(extensions), + }); + } -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.naturalCompare = naturalCompare; + function extendEnumType(type) { + var _typeExtensionsMap$ty; -/** - * Returns a number indicating whether a reference string comes before, or after, - * or is the same as the given string in natural sort order. - * - * See: https://en.wikipedia.org/wiki/Natural_sort_order - * - */ -function naturalCompare(aStr, bStr) { - let aIndex = 0; - let bIndex = 0; + const config = type.toConfig(); + const extensions = + (_typeExtensionsMap$ty = typeExtensionsMap[type.name]) !== null && + _typeExtensionsMap$ty !== void 0 + ? _typeExtensionsMap$ty + : []; + return new _definition.GraphQLEnumType({ + ...config, + values: { ...config.values, ...buildEnumValueMap(extensions) }, + extensionASTNodes: config.extensionASTNodes.concat(extensions), + }); + } - while (aIndex < aStr.length && bIndex < bStr.length) { - let aChar = aStr.charCodeAt(aIndex); - let bChar = bStr.charCodeAt(bIndex); + function extendScalarType(type) { + var _typeExtensionsMap$co2; - if (isDigit(aChar) && isDigit(bChar)) { - let aNum = 0; + const config = type.toConfig(); + const extensions = + (_typeExtensionsMap$co2 = typeExtensionsMap[config.name]) !== null && + _typeExtensionsMap$co2 !== void 0 + ? _typeExtensionsMap$co2 + : []; + let specifiedByURL = config.specifiedByURL; - do { - ++aIndex; - aNum = aNum * 10 + aChar - DIGIT_0; - aChar = aStr.charCodeAt(aIndex); - } while (isDigit(aChar) && aNum > 0); + for (const extensionNode of extensions) { + var _getSpecifiedByURL; - let bNum = 0; + specifiedByURL = + (_getSpecifiedByURL = getSpecifiedByURL(extensionNode)) !== null && + _getSpecifiedByURL !== void 0 + ? _getSpecifiedByURL + : specifiedByURL; + } - do { - ++bIndex; - bNum = bNum * 10 + bChar - DIGIT_0; - bChar = bStr.charCodeAt(bIndex); - } while (isDigit(bChar) && bNum > 0); + return new _definition.GraphQLScalarType({ + ...config, + specifiedByURL, + extensionASTNodes: config.extensionASTNodes.concat(extensions), + }); + } - if (aNum < bNum) { - return -1; - } + function extendObjectType(type) { + var _typeExtensionsMap$co3; - if (aNum > bNum) { - return 1; - } - } else { - if (aChar < bChar) { - return -1; - } + const config = type.toConfig(); + const extensions = + (_typeExtensionsMap$co3 = typeExtensionsMap[config.name]) !== null && + _typeExtensionsMap$co3 !== void 0 + ? _typeExtensionsMap$co3 + : []; + return new _definition.GraphQLObjectType({ + ...config, + interfaces: () => [ + ...type.getInterfaces().map(replaceNamedType), + ...buildInterfaces(extensions), + ], + fields: () => ({ + ...(0, _mapValue.mapValue)(config.fields, extendField), + ...buildFieldMap(extensions), + }), + extensionASTNodes: config.extensionASTNodes.concat(extensions), + }); + } - if (aChar > bChar) { - return 1; - } + function extendInterfaceType(type) { + var _typeExtensionsMap$co4; - ++aIndex; - ++bIndex; - } + const config = type.toConfig(); + const extensions = + (_typeExtensionsMap$co4 = typeExtensionsMap[config.name]) !== null && + _typeExtensionsMap$co4 !== void 0 + ? _typeExtensionsMap$co4 + : []; + return new _definition.GraphQLInterfaceType({ + ...config, + interfaces: () => [ + ...type.getInterfaces().map(replaceNamedType), + ...buildInterfaces(extensions), + ], + fields: () => ({ + ...(0, _mapValue.mapValue)(config.fields, extendField), + ...buildFieldMap(extensions), + }), + extensionASTNodes: config.extensionASTNodes.concat(extensions), + }); } - return aStr.length - bStr.length; -} + function extendUnionType(type) { + var _typeExtensionsMap$co5; -const DIGIT_0 = 48; -const DIGIT_9 = 57; + const config = type.toConfig(); + const extensions = + (_typeExtensionsMap$co5 = typeExtensionsMap[config.name]) !== null && + _typeExtensionsMap$co5 !== void 0 + ? _typeExtensionsMap$co5 + : []; + return new _definition.GraphQLUnionType({ + ...config, + types: () => [ + ...type.getTypes().map(replaceNamedType), + ...buildUnionTypes(extensions), + ], + extensionASTNodes: config.extensionASTNodes.concat(extensions), + }); + } -function isDigit(code) { - return !isNaN(code) && DIGIT_0 <= code && code <= DIGIT_9; -} + function extendField(field) { + return { + ...field, + type: replaceType(field.type), + args: field.args && (0, _mapValue.mapValue)(field.args, extendArg), + }; + } + function extendArg(arg) { + return { ...arg, type: replaceType(arg.type) }; + } -/***/ }), + function getOperationTypes(nodes) { + const opTypes = {}; -/***/ 94281: -/***/ ((__unused_webpack_module, exports) => { + for (const node of nodes) { + var _node$operationTypes; -"use strict"; + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const operationTypesNodes = + /* c8 ignore next */ + (_node$operationTypes = node.operationTypes) !== null && + _node$operationTypes !== void 0 + ? _node$operationTypes + : []; + for (const operationType of operationTypesNodes) { + // Note: While this could make early assertions to get the correctly + // typed values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + // @ts-expect-error + opTypes[operationType.operation] = getNamedType(operationType.type); + } + } -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.printPathArray = printPathArray; + return opTypes; + } -/** - * Build a string describing the path. - */ -function printPathArray(path) { - return path - .map((key) => - typeof key === 'number' ? '[' + key.toString() + ']' : '.' + key, - ) - .join(''); -} + function getNamedType(node) { + var _stdTypeMap$name2; + const name = node.name.value; + const type = + (_stdTypeMap$name2 = stdTypeMap[name]) !== null && + _stdTypeMap$name2 !== void 0 + ? _stdTypeMap$name2 + : typeMap[name]; -/***/ }), + if (type === undefined) { + throw new Error(`Unknown type: "${name}".`); + } -/***/ 46804: -/***/ ((__unused_webpack_module, exports) => { + return type; + } -"use strict"; + function getWrappedType(node) { + if (node.kind === _kinds.Kind.LIST_TYPE) { + return new _definition.GraphQLList(getWrappedType(node.type)); + } + if (node.kind === _kinds.Kind.NON_NULL_TYPE) { + return new _definition.GraphQLNonNull(getWrappedType(node.type)); + } -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.promiseForObject = promiseForObject; + return getNamedType(node); + } -/** - * This function transforms a JS object `ObjMap>` into - * a `Promise>` - * - * This is akin to bluebird's `Promise.props`, but implemented only using - * `Promise.all` so it will work with any implementation of ES6 promises. - */ -function promiseForObject(object) { - return Promise.all(Object.values(object)).then((resolvedValues) => { - const resolvedObject = Object.create(null); + function buildDirective(node) { + var _node$description; - for (const [i, key] of Object.keys(object).entries()) { - resolvedObject[key] = resolvedValues[i]; - } + return new _directives.GraphQLDirective({ + name: node.name.value, + description: + (_node$description = node.description) === null || + _node$description === void 0 + ? void 0 + : _node$description.value, + // @ts-expect-error + locations: node.locations.map(({ value }) => value), + isRepeatable: node.repeatable, + args: buildArgumentMap(node.arguments), + astNode: node, + }); + } - return resolvedObject; - }); -} + function buildFieldMap(nodes) { + const fieldConfigMap = Object.create(null); + for (const node of nodes) { + var _node$fields; -/***/ }), + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const nodeFields = + /* c8 ignore next */ + (_node$fields = node.fields) !== null && _node$fields !== void 0 + ? _node$fields + : []; -/***/ 63925: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + for (const field of nodeFields) { + var _field$description; -"use strict"; + fieldConfigMap[field.name.value] = { + // Note: While this could make assertions to get the correctly typed + // value, that would throw immediately while type system validation + // with validateSchema() will produce more actionable results. + type: getWrappedType(field.type), + description: + (_field$description = field.description) === null || + _field$description === void 0 + ? void 0 + : _field$description.value, + args: buildArgumentMap(field.arguments), + deprecationReason: getDeprecationReason(field), + astNode: field, + }; + } + } + return fieldConfigMap; + } -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.promiseReduce = promiseReduce; + function buildArgumentMap(args) { + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const argsNodes = + /* c8 ignore next */ + args !== null && args !== void 0 ? args : []; + const argConfigMap = Object.create(null); -var _isPromise = __nccwpck_require__(93910); + for (const arg of argsNodes) { + var _arg$description; -/** - * Similar to Array.prototype.reduce(), however the reducing callback may return - * a Promise, in which case reduction will continue after each promise resolves. - * - * If the callback does not return a Promise, then this function will also not - * return a Promise. - */ -function promiseReduce(values, callbackFn, initialValue) { - let accumulator = initialValue; + // Note: While this could make assertions to get the correctly typed + // value, that would throw immediately while type system validation + // with validateSchema() will produce more actionable results. + const type = getWrappedType(arg.type); + argConfigMap[arg.name.value] = { + type, + description: + (_arg$description = arg.description) === null || + _arg$description === void 0 + ? void 0 + : _arg$description.value, + defaultValue: (0, _valueFromAST.valueFromAST)(arg.defaultValue, type), + deprecationReason: getDeprecationReason(arg), + astNode: arg, + }; + } - for (const value of values) { - accumulator = (0, _isPromise.isPromise)(accumulator) - ? accumulator.then((resolved) => callbackFn(resolved, value)) - : callbackFn(accumulator, value); + return argConfigMap; } - return accumulator; -} + function buildInputFieldMap(nodes) { + const inputFieldMap = Object.create(null); + for (const node of nodes) { + var _node$fields2; -/***/ }), + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const fieldsNodes = + /* c8 ignore next */ + (_node$fields2 = node.fields) !== null && _node$fields2 !== void 0 + ? _node$fields2 + : []; -/***/ 57704: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + for (const field of fieldsNodes) { + var _field$description2; -"use strict"; + // Note: While this could make assertions to get the correctly typed + // value, that would throw immediately while type system validation + // with validateSchema() will produce more actionable results. + const type = getWrappedType(field.type); + inputFieldMap[field.name.value] = { + type, + description: + (_field$description2 = field.description) === null || + _field$description2 === void 0 + ? void 0 + : _field$description2.value, + defaultValue: (0, _valueFromAST.valueFromAST)( + field.defaultValue, + type, + ), + deprecationReason: getDeprecationReason(field), + astNode: field, + }; + } + } + return inputFieldMap; + } -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.suggestionList = suggestionList; + function buildEnumValueMap(nodes) { + const enumValueMap = Object.create(null); -var _naturalCompare = __nccwpck_require__(20038); + for (const node of nodes) { + var _node$values; -/** - * Given an invalid input string and a list of valid options, returns a filtered - * list of valid options sorted based on their similarity with the input. - */ -function suggestionList(input, options) { - const optionsByDistance = Object.create(null); - const lexicalDistance = new LexicalDistance(input); - const threshold = Math.floor(input.length * 0.4) + 1; + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const valuesNodes = + /* c8 ignore next */ + (_node$values = node.values) !== null && _node$values !== void 0 + ? _node$values + : []; - for (const option of options) { - const distance = lexicalDistance.measure(option, threshold); + for (const value of valuesNodes) { + var _value$description; - if (distance !== undefined) { - optionsByDistance[option] = distance; + enumValueMap[value.name.value] = { + description: + (_value$description = value.description) === null || + _value$description === void 0 + ? void 0 + : _value$description.value, + deprecationReason: getDeprecationReason(value), + astNode: value, + }; + } } + + return enumValueMap; } - return Object.keys(optionsByDistance).sort((a, b) => { - const distanceDiff = optionsByDistance[a] - optionsByDistance[b]; - return distanceDiff !== 0 - ? distanceDiff - : (0, _naturalCompare.naturalCompare)(a, b); - }); -} -/** - * Computes the lexical distance between strings A and B. - * - * The "distance" between two strings is given by counting the minimum number - * of edits needed to transform string A into string B. An edit can be an - * insertion, deletion, or substitution of a single character, or a swap of two - * adjacent characters. - * - * Includes a custom alteration from Damerau-Levenshtein to treat case changes - * as a single edit which helps identify mis-cased values with an edit distance - * of 1. - * - * This distance can be useful for detecting typos in input or sorting - */ + function buildInterfaces(nodes) { + // Note: While this could make assertions to get the correctly typed + // values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + // @ts-expect-error + return nodes.flatMap( + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + (node) => { + var _node$interfaces$map, _node$interfaces; -class LexicalDistance { - constructor(input) { - this._input = input; - this._inputLowerCase = input.toLowerCase(); - this._inputArray = stringToArray(this._inputLowerCase); - this._rows = [ - new Array(input.length + 1).fill(0), - new Array(input.length + 1).fill(0), - new Array(input.length + 1).fill(0), - ]; + return ( + /* c8 ignore next */ + (_node$interfaces$map = + (_node$interfaces = node.interfaces) === null || + _node$interfaces === void 0 + ? void 0 + : _node$interfaces.map(getNamedType)) !== null && + _node$interfaces$map !== void 0 + ? _node$interfaces$map + : [] + ); + }, + ); } - measure(option, threshold) { - if (this._input === option) { - return 0; - } + function buildUnionTypes(nodes) { + // Note: While this could make assertions to get the correctly typed + // values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + // @ts-expect-error + return nodes.flatMap( + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + (node) => { + var _node$types$map, _node$types; - const optionLowerCase = option.toLowerCase(); // Any case change counts as a single edit + return ( + /* c8 ignore next */ + (_node$types$map = + (_node$types = node.types) === null || _node$types === void 0 + ? void 0 + : _node$types.map(getNamedType)) !== null && + _node$types$map !== void 0 + ? _node$types$map + : [] + ); + }, + ); + } - if (this._inputLowerCase === optionLowerCase) { - return 1; - } + function buildType(astNode) { + var _typeExtensionsMap$na; - let a = stringToArray(optionLowerCase); - let b = this._inputArray; + const name = astNode.name.value; + const extensionASTNodes = + (_typeExtensionsMap$na = typeExtensionsMap[name]) !== null && + _typeExtensionsMap$na !== void 0 + ? _typeExtensionsMap$na + : []; - if (a.length < b.length) { - const tmp = a; - a = b; - b = tmp; - } + switch (astNode.kind) { + case _kinds.Kind.OBJECT_TYPE_DEFINITION: { + var _astNode$description; - const aLength = a.length; - const bLength = b.length; + const allNodes = [astNode, ...extensionASTNodes]; + return new _definition.GraphQLObjectType({ + name, + description: + (_astNode$description = astNode.description) === null || + _astNode$description === void 0 + ? void 0 + : _astNode$description.value, + interfaces: () => buildInterfaces(allNodes), + fields: () => buildFieldMap(allNodes), + astNode, + extensionASTNodes, + }); + } - if (aLength - bLength > threshold) { - return undefined; - } + case _kinds.Kind.INTERFACE_TYPE_DEFINITION: { + var _astNode$description2; - const rows = this._rows; + const allNodes = [astNode, ...extensionASTNodes]; + return new _definition.GraphQLInterfaceType({ + name, + description: + (_astNode$description2 = astNode.description) === null || + _astNode$description2 === void 0 + ? void 0 + : _astNode$description2.value, + interfaces: () => buildInterfaces(allNodes), + fields: () => buildFieldMap(allNodes), + astNode, + extensionASTNodes, + }); + } - for (let j = 0; j <= bLength; j++) { - rows[0][j] = j; - } + case _kinds.Kind.ENUM_TYPE_DEFINITION: { + var _astNode$description3; - for (let i = 1; i <= aLength; i++) { - const upRow = rows[(i - 1) % 3]; - const currentRow = rows[i % 3]; - let smallestCell = (currentRow[0] = i); + const allNodes = [astNode, ...extensionASTNodes]; + return new _definition.GraphQLEnumType({ + name, + description: + (_astNode$description3 = astNode.description) === null || + _astNode$description3 === void 0 + ? void 0 + : _astNode$description3.value, + values: buildEnumValueMap(allNodes), + astNode, + extensionASTNodes, + }); + } - for (let j = 1; j <= bLength; j++) { - const cost = a[i - 1] === b[j - 1] ? 0 : 1; - let currentCell = Math.min( - upRow[j] + 1, // delete - currentRow[j - 1] + 1, // insert - upRow[j - 1] + cost, // substitute - ); + case _kinds.Kind.UNION_TYPE_DEFINITION: { + var _astNode$description4; - if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { - // transposition - const doubleDiagonalCell = rows[(i - 2) % 3][j - 2]; - currentCell = Math.min(currentCell, doubleDiagonalCell + 1); - } + const allNodes = [astNode, ...extensionASTNodes]; + return new _definition.GraphQLUnionType({ + name, + description: + (_astNode$description4 = astNode.description) === null || + _astNode$description4 === void 0 + ? void 0 + : _astNode$description4.value, + types: () => buildUnionTypes(allNodes), + astNode, + extensionASTNodes, + }); + } - if (currentCell < smallestCell) { - smallestCell = currentCell; - } + case _kinds.Kind.SCALAR_TYPE_DEFINITION: { + var _astNode$description5; - currentRow[j] = currentCell; - } // Early exit, since distance can't go smaller than smallest element of the previous row. + return new _definition.GraphQLScalarType({ + name, + description: + (_astNode$description5 = astNode.description) === null || + _astNode$description5 === void 0 + ? void 0 + : _astNode$description5.value, + specifiedByURL: getSpecifiedByURL(astNode), + astNode, + extensionASTNodes, + }); + } - if (smallestCell > threshold) { - return undefined; + case _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION: { + var _astNode$description6; + + const allNodes = [astNode, ...extensionASTNodes]; + return new _definition.GraphQLInputObjectType({ + name, + description: + (_astNode$description6 = astNode.description) === null || + _astNode$description6 === void 0 + ? void 0 + : _astNode$description6.value, + fields: () => buildInputFieldMap(allNodes), + astNode, + extensionASTNodes, + isOneOf: isOneOf(astNode), + }); } } - - const distance = rows[aLength % 3][bLength]; - return distance <= threshold ? distance : undefined; } } -function stringToArray(str) { - const strLength = str.length; - const array = new Array(strLength); +const stdTypeMap = (0, _keyMap.keyMap)( + [..._scalars.specifiedScalarTypes, ..._introspection.introspectionTypes], + (type) => type.name, +); +/** + * Given a field or enum value node, returns the string value for the + * deprecation reason. + */ - for (let i = 0; i < strLength; ++i) { - array[i] = str.charCodeAt(i); - } +function getDeprecationReason(node) { + const deprecated = (0, _values.getDirectiveValues)( + _directives.GraphQLDeprecatedDirective, + node, + ); // @ts-expect-error validated by `getDirectiveValues` - return array; + return deprecated === null || deprecated === void 0 + ? void 0 + : deprecated.reason; } +/** + * Given a scalar node, returns the string value for the specifiedByURL. + */ +function getSpecifiedByURL(node) { + const specifiedBy = (0, _values.getDirectiveValues)( + _directives.GraphQLSpecifiedByDirective, + node, + ); // @ts-expect-error validated by `getDirectiveValues` -/***/ }), - -/***/ 15472: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.toError = toError; - -var _inspect = __nccwpck_require__(10102); - + return specifiedBy === null || specifiedBy === void 0 + ? void 0 + : specifiedBy.url; +} /** - * Sometimes a non-error is thrown, wrap it as an Error instance to ensure a consistent Error interface. + * Given an input object node, returns if the node should be OneOf. */ -function toError(thrownValue) { - return thrownValue instanceof Error - ? thrownValue - : new NonErrorThrown(thrownValue); -} -class NonErrorThrown extends Error { - constructor(thrownValue) { - super('Unexpected error value: ' + (0, _inspect.inspect)(thrownValue)); - this.name = 'NonErrorThrown'; - this.thrownValue = thrownValue; - } +function isOneOf(node) { + return Boolean( + (0, _values.getDirectiveValues)(_directives.GraphQLOneOfDirective, node), + ); } /***/ }), -/***/ 74728: -/***/ ((__unused_webpack_module, exports) => { +/***/ 59366: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -280466,465 +282823,553 @@ class NonErrorThrown extends Error { Object.defineProperty(exports, "__esModule", ({ value: true, })); -exports.toObjMap = toObjMap; +exports.DangerousChangeType = exports.BreakingChangeType = void 0; +exports.findBreakingChanges = findBreakingChanges; +exports.findDangerousChanges = findDangerousChanges; -function toObjMap(obj) { - if (obj == null) { - return Object.create(null); - } +var _inspect = __nccwpck_require__(10102); - if (Object.getPrototypeOf(obj) === null) { - return obj; - } +var _invariant = __nccwpck_require__(28847); - const map = Object.create(null); +var _keyMap = __nccwpck_require__(10711); - for (const [key, value] of Object.entries(obj)) { - map[key] = value; - } +var _printer = __nccwpck_require__(68203); - return map; -} +var _definition = __nccwpck_require__(32150); +var _scalars = __nccwpck_require__(93145); -/***/ }), +var _astFromValue = __nccwpck_require__(12653); -/***/ 45494: -/***/ ((__unused_webpack_module, exports) => { +var _sortValueNode = __nccwpck_require__(82278); -"use strict"; +var BreakingChangeType; +exports.BreakingChangeType = BreakingChangeType; + +(function (BreakingChangeType) { + BreakingChangeType['TYPE_REMOVED'] = 'TYPE_REMOVED'; + BreakingChangeType['TYPE_CHANGED_KIND'] = 'TYPE_CHANGED_KIND'; + BreakingChangeType['TYPE_REMOVED_FROM_UNION'] = 'TYPE_REMOVED_FROM_UNION'; + BreakingChangeType['VALUE_REMOVED_FROM_ENUM'] = 'VALUE_REMOVED_FROM_ENUM'; + BreakingChangeType['REQUIRED_INPUT_FIELD_ADDED'] = + 'REQUIRED_INPUT_FIELD_ADDED'; + BreakingChangeType['IMPLEMENTED_INTERFACE_REMOVED'] = + 'IMPLEMENTED_INTERFACE_REMOVED'; + BreakingChangeType['FIELD_REMOVED'] = 'FIELD_REMOVED'; + BreakingChangeType['FIELD_CHANGED_KIND'] = 'FIELD_CHANGED_KIND'; + BreakingChangeType['REQUIRED_ARG_ADDED'] = 'REQUIRED_ARG_ADDED'; + BreakingChangeType['ARG_REMOVED'] = 'ARG_REMOVED'; + BreakingChangeType['ARG_CHANGED_KIND'] = 'ARG_CHANGED_KIND'; + BreakingChangeType['DIRECTIVE_REMOVED'] = 'DIRECTIVE_REMOVED'; + BreakingChangeType['DIRECTIVE_ARG_REMOVED'] = 'DIRECTIVE_ARG_REMOVED'; + BreakingChangeType['REQUIRED_DIRECTIVE_ARG_ADDED'] = + 'REQUIRED_DIRECTIVE_ARG_ADDED'; + BreakingChangeType['DIRECTIVE_REPEATABLE_REMOVED'] = + 'DIRECTIVE_REPEATABLE_REMOVED'; + BreakingChangeType['DIRECTIVE_LOCATION_REMOVED'] = + 'DIRECTIVE_LOCATION_REMOVED'; +})( + BreakingChangeType || (exports.BreakingChangeType = BreakingChangeType = {}), +); +var DangerousChangeType; +exports.DangerousChangeType = DangerousChangeType; -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.Token = - exports.QueryDocumentKeys = - exports.OperationTypeNode = - exports.Location = - void 0; -exports.isNode = isNode; +(function (DangerousChangeType) { + DangerousChangeType['VALUE_ADDED_TO_ENUM'] = 'VALUE_ADDED_TO_ENUM'; + DangerousChangeType['TYPE_ADDED_TO_UNION'] = 'TYPE_ADDED_TO_UNION'; + DangerousChangeType['OPTIONAL_INPUT_FIELD_ADDED'] = + 'OPTIONAL_INPUT_FIELD_ADDED'; + DangerousChangeType['OPTIONAL_ARG_ADDED'] = 'OPTIONAL_ARG_ADDED'; + DangerousChangeType['IMPLEMENTED_INTERFACE_ADDED'] = + 'IMPLEMENTED_INTERFACE_ADDED'; + DangerousChangeType['ARG_DEFAULT_VALUE_CHANGE'] = 'ARG_DEFAULT_VALUE_CHANGE'; +})( + DangerousChangeType || + (exports.DangerousChangeType = DangerousChangeType = {}), +); /** - * Contains a range of UTF-8 character offsets and token references that - * identify the region of the source from which the AST derived. + * Given two schemas, returns an Array containing descriptions of all the types + * of breaking changes covered by the other functions down below. */ -class Location { - /** - * The character offset at which this Node begins. - */ - - /** - * The character offset at which this Node ends. - */ - - /** - * The Token at which this Node begins. - */ - - /** - * The Token at which this Node ends. - */ - - /** - * The Source document the AST represents. - */ - constructor(startToken, endToken, source) { - this.start = startToken.start; - this.end = endToken.end; - this.startToken = startToken; - this.endToken = endToken; - this.source = source; - } - - get [Symbol.toStringTag]() { - return 'Location'; - } - - toJSON() { - return { - start: this.start, - end: this.end, - }; - } +function findBreakingChanges(oldSchema, newSchema) { + // @ts-expect-error + return findSchemaChanges(oldSchema, newSchema).filter( + (change) => change.type in BreakingChangeType, + ); } /** - * Represents a range of characters represented by a lexical token - * within a Source. + * Given two schemas, returns an Array containing descriptions of all the types + * of potentially dangerous changes covered by the other functions down below. */ -exports.Location = Location; +function findDangerousChanges(oldSchema, newSchema) { + // @ts-expect-error + return findSchemaChanges(oldSchema, newSchema).filter( + (change) => change.type in DangerousChangeType, + ); +} -class Token { - /** - * The kind of Token. - */ +function findSchemaChanges(oldSchema, newSchema) { + return [ + ...findTypeChanges(oldSchema, newSchema), + ...findDirectiveChanges(oldSchema, newSchema), + ]; +} - /** - * The character offset at which this Node begins. - */ +function findDirectiveChanges(oldSchema, newSchema) { + const schemaChanges = []; + const directivesDiff = diff( + oldSchema.getDirectives(), + newSchema.getDirectives(), + ); - /** - * The character offset at which this Node ends. - */ + for (const oldDirective of directivesDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_REMOVED, + description: `${oldDirective.name} was removed.`, + }); + } - /** - * The 1-indexed line number on which this Token appears. - */ + for (const [oldDirective, newDirective] of directivesDiff.persisted) { + const argsDiff = diff(oldDirective.args, newDirective.args); - /** - * The 1-indexed column number at which this Token begins. - */ + for (const newArg of argsDiff.added) { + if ((0, _definition.isRequiredArgument)(newArg)) { + schemaChanges.push({ + type: BreakingChangeType.REQUIRED_DIRECTIVE_ARG_ADDED, + description: `A required arg ${newArg.name} on directive ${oldDirective.name} was added.`, + }); + } + } - /** - * For non-punctuation tokens, represents the interpreted value of the token. - * - * Note: is undefined for punctuation tokens, but typed as string for - * convenience in the parser. - */ + for (const oldArg of argsDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_ARG_REMOVED, + description: `${oldArg.name} was removed from ${oldDirective.name}.`, + }); + } - /** - * Tokens exist as nodes in a double-linked-list amongst all tokens - * including ignored tokens. is always the first node and - * the last. - */ - constructor(kind, start, end, line, column, value) { - this.kind = kind; - this.start = start; - this.end = end; - this.line = line; - this.column = column; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + if (oldDirective.isRepeatable && !newDirective.isRepeatable) { + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_REPEATABLE_REMOVED, + description: `Repeatable flag was removed from ${oldDirective.name}.`, + }); + } - this.value = value; - this.prev = null; - this.next = null; + for (const location of oldDirective.locations) { + if (!newDirective.locations.includes(location)) { + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_LOCATION_REMOVED, + description: `${location} was removed from ${oldDirective.name}.`, + }); + } + } } - get [Symbol.toStringTag]() { - return 'Token'; + return schemaChanges; +} + +function findTypeChanges(oldSchema, newSchema) { + const schemaChanges = []; + const typesDiff = diff( + Object.values(oldSchema.getTypeMap()), + Object.values(newSchema.getTypeMap()), + ); + + for (const oldType of typesDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.TYPE_REMOVED, + description: (0, _scalars.isSpecifiedScalarType)(oldType) + ? `Standard scalar ${oldType.name} was removed because it is not referenced anymore.` + : `${oldType.name} was removed.`, + }); } - toJSON() { - return { - kind: this.kind, - value: this.value, - line: this.line, - column: this.column, - }; + for (const [oldType, newType] of typesDiff.persisted) { + if ( + (0, _definition.isEnumType)(oldType) && + (0, _definition.isEnumType)(newType) + ) { + schemaChanges.push(...findEnumTypeChanges(oldType, newType)); + } else if ( + (0, _definition.isUnionType)(oldType) && + (0, _definition.isUnionType)(newType) + ) { + schemaChanges.push(...findUnionTypeChanges(oldType, newType)); + } else if ( + (0, _definition.isInputObjectType)(oldType) && + (0, _definition.isInputObjectType)(newType) + ) { + schemaChanges.push(...findInputObjectTypeChanges(oldType, newType)); + } else if ( + (0, _definition.isObjectType)(oldType) && + (0, _definition.isObjectType)(newType) + ) { + schemaChanges.push( + ...findFieldChanges(oldType, newType), + ...findImplementedInterfacesChanges(oldType, newType), + ); + } else if ( + (0, _definition.isInterfaceType)(oldType) && + (0, _definition.isInterfaceType)(newType) + ) { + schemaChanges.push( + ...findFieldChanges(oldType, newType), + ...findImplementedInterfacesChanges(oldType, newType), + ); + } else if (oldType.constructor !== newType.constructor) { + schemaChanges.push({ + type: BreakingChangeType.TYPE_CHANGED_KIND, + description: + `${oldType.name} changed from ` + + `${typeKindName(oldType)} to ${typeKindName(newType)}.`, + }); + } } + + return schemaChanges; } -/** - * The list of all possible AST node types. - */ -exports.Token = Token; +function findInputObjectTypeChanges(oldType, newType) { + const schemaChanges = []; + const fieldsDiff = diff( + Object.values(oldType.getFields()), + Object.values(newType.getFields()), + ); -/** - * @internal - */ -const QueryDocumentKeys = { - Name: [], - Document: ['definitions'], - OperationDefinition: [ - 'name', - 'variableDefinitions', - 'directives', - 'selectionSet', - ], - VariableDefinition: ['variable', 'type', 'defaultValue', 'directives'], - Variable: ['name'], - SelectionSet: ['selections'], - Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'], - Argument: ['name', 'value'], - FragmentSpread: ['name', 'directives'], - InlineFragment: ['typeCondition', 'directives', 'selectionSet'], - FragmentDefinition: [ - 'name', // Note: fragment variable definitions are deprecated and will removed in v17.0.0 - 'variableDefinitions', - 'typeCondition', - 'directives', - 'selectionSet', - ], - IntValue: [], - FloatValue: [], - StringValue: [], - BooleanValue: [], - NullValue: [], - EnumValue: [], - ListValue: ['values'], - ObjectValue: ['fields'], - ObjectField: ['name', 'value'], - Directive: ['name', 'arguments'], - NamedType: ['name'], - ListType: ['type'], - NonNullType: ['type'], - SchemaDefinition: ['description', 'directives', 'operationTypes'], - OperationTypeDefinition: ['type'], - ScalarTypeDefinition: ['description', 'name', 'directives'], - ObjectTypeDefinition: [ - 'description', - 'name', - 'interfaces', - 'directives', - 'fields', - ], - FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'], - InputValueDefinition: [ - 'description', - 'name', - 'type', - 'defaultValue', - 'directives', - ], - InterfaceTypeDefinition: [ - 'description', - 'name', - 'interfaces', - 'directives', - 'fields', - ], - UnionTypeDefinition: ['description', 'name', 'directives', 'types'], - EnumTypeDefinition: ['description', 'name', 'directives', 'values'], - EnumValueDefinition: ['description', 'name', 'directives'], - InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'], - DirectiveDefinition: ['description', 'name', 'arguments', 'locations'], - SchemaExtension: ['directives', 'operationTypes'], - ScalarTypeExtension: ['name', 'directives'], - ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'], - InterfaceTypeExtension: ['name', 'interfaces', 'directives', 'fields'], - UnionTypeExtension: ['name', 'directives', 'types'], - EnumTypeExtension: ['name', 'directives', 'values'], - InputObjectTypeExtension: ['name', 'directives', 'fields'], -}; -exports.QueryDocumentKeys = QueryDocumentKeys; -const kindValues = new Set(Object.keys(QueryDocumentKeys)); -/** - * @internal - */ + for (const newField of fieldsDiff.added) { + if ((0, _definition.isRequiredInputField)(newField)) { + schemaChanges.push({ + type: BreakingChangeType.REQUIRED_INPUT_FIELD_ADDED, + description: `A required field ${newField.name} on input type ${oldType.name} was added.`, + }); + } else { + schemaChanges.push({ + type: DangerousChangeType.OPTIONAL_INPUT_FIELD_ADDED, + description: `An optional field ${newField.name} on input type ${oldType.name} was added.`, + }); + } + } + + for (const oldField of fieldsDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.FIELD_REMOVED, + description: `${oldType.name}.${oldField.name} was removed.`, + }); + } -function isNode(maybeNode) { - const maybeKind = - maybeNode === null || maybeNode === void 0 ? void 0 : maybeNode.kind; - return typeof maybeKind === 'string' && kindValues.has(maybeKind); + for (const [oldField, newField] of fieldsDiff.persisted) { + const isSafe = isChangeSafeForInputObjectFieldOrFieldArg( + oldField.type, + newField.type, + ); + + if (!isSafe) { + schemaChanges.push({ + type: BreakingChangeType.FIELD_CHANGED_KIND, + description: + `${oldType.name}.${oldField.name} changed type from ` + + `${String(oldField.type)} to ${String(newField.type)}.`, + }); + } + } + + return schemaChanges; } -/** Name */ -var OperationTypeNode; -exports.OperationTypeNode = OperationTypeNode; +function findUnionTypeChanges(oldType, newType) { + const schemaChanges = []; + const possibleTypesDiff = diff(oldType.getTypes(), newType.getTypes()); -(function (OperationTypeNode) { - OperationTypeNode['QUERY'] = 'query'; - OperationTypeNode['MUTATION'] = 'mutation'; - OperationTypeNode['SUBSCRIPTION'] = 'subscription'; -})(OperationTypeNode || (exports.OperationTypeNode = OperationTypeNode = {})); + for (const newPossibleType of possibleTypesDiff.added) { + schemaChanges.push({ + type: DangerousChangeType.TYPE_ADDED_TO_UNION, + description: `${newPossibleType.name} was added to union type ${oldType.name}.`, + }); + } + for (const oldPossibleType of possibleTypesDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.TYPE_REMOVED_FROM_UNION, + description: `${oldPossibleType.name} was removed from union type ${oldType.name}.`, + }); + } -/***/ }), + return schemaChanges; +} -/***/ 52671: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function findEnumTypeChanges(oldType, newType) { + const schemaChanges = []; + const valuesDiff = diff(oldType.getValues(), newType.getValues()); -"use strict"; + for (const newValue of valuesDiff.added) { + schemaChanges.push({ + type: DangerousChangeType.VALUE_ADDED_TO_ENUM, + description: `${newValue.name} was added to enum type ${oldType.name}.`, + }); + } + for (const oldValue of valuesDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM, + description: `${oldValue.name} was removed from enum type ${oldType.name}.`, + }); + } -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.dedentBlockStringLines = dedentBlockStringLines; -exports.isPrintableAsBlockString = isPrintableAsBlockString; -exports.printBlockString = printBlockString; + return schemaChanges; +} -var _characterClasses = __nccwpck_require__(7234); +function findImplementedInterfacesChanges(oldType, newType) { + const schemaChanges = []; + const interfacesDiff = diff(oldType.getInterfaces(), newType.getInterfaces()); -/** - * Produces the value of a block string from its parsed raw value, similar to - * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc. - * - * This implements the GraphQL spec's BlockStringValue() static algorithm. - * - * @internal - */ -function dedentBlockStringLines(lines) { - var _firstNonEmptyLine2; + for (const newInterface of interfacesDiff.added) { + schemaChanges.push({ + type: DangerousChangeType.IMPLEMENTED_INTERFACE_ADDED, + description: `${newInterface.name} added to interfaces implemented by ${oldType.name}.`, + }); + } - let commonIndent = Number.MAX_SAFE_INTEGER; - let firstNonEmptyLine = null; - let lastNonEmptyLine = -1; + for (const oldInterface of interfacesDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.IMPLEMENTED_INTERFACE_REMOVED, + description: `${oldType.name} no longer implements interface ${oldInterface.name}.`, + }); + } - for (let i = 0; i < lines.length; ++i) { - var _firstNonEmptyLine; + return schemaChanges; +} - const line = lines[i]; - const indent = leadingWhitespace(line); +function findFieldChanges(oldType, newType) { + const schemaChanges = []; + const fieldsDiff = diff( + Object.values(oldType.getFields()), + Object.values(newType.getFields()), + ); - if (indent === line.length) { - continue; // skip empty lines - } + for (const oldField of fieldsDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.FIELD_REMOVED, + description: `${oldType.name}.${oldField.name} was removed.`, + }); + } - firstNonEmptyLine = - (_firstNonEmptyLine = firstNonEmptyLine) !== null && - _firstNonEmptyLine !== void 0 - ? _firstNonEmptyLine - : i; - lastNonEmptyLine = i; + for (const [oldField, newField] of fieldsDiff.persisted) { + schemaChanges.push(...findArgChanges(oldType, oldField, newField)); + const isSafe = isChangeSafeForObjectOrInterfaceField( + oldField.type, + newField.type, + ); - if (i !== 0 && indent < commonIndent) { - commonIndent = indent; + if (!isSafe) { + schemaChanges.push({ + type: BreakingChangeType.FIELD_CHANGED_KIND, + description: + `${oldType.name}.${oldField.name} changed type from ` + + `${String(oldField.type)} to ${String(newField.type)}.`, + }); } } - return lines // Remove common indentation from all lines but first. - .map((line, i) => (i === 0 ? line : line.slice(commonIndent))) // Remove leading and trailing blank lines. - .slice( - (_firstNonEmptyLine2 = firstNonEmptyLine) !== null && - _firstNonEmptyLine2 !== void 0 - ? _firstNonEmptyLine2 - : 0, - lastNonEmptyLine + 1, - ); + return schemaChanges; } -function leadingWhitespace(str) { - let i = 0; +function findArgChanges(oldType, oldField, newField) { + const schemaChanges = []; + const argsDiff = diff(oldField.args, newField.args); - while ( - i < str.length && - (0, _characterClasses.isWhiteSpace)(str.charCodeAt(i)) - ) { - ++i; + for (const oldArg of argsDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.ARG_REMOVED, + description: `${oldType.name}.${oldField.name} arg ${oldArg.name} was removed.`, + }); } - return i; -} -/** - * @internal - */ + for (const [oldArg, newArg] of argsDiff.persisted) { + const isSafe = isChangeSafeForInputObjectFieldOrFieldArg( + oldArg.type, + newArg.type, + ); -function isPrintableAsBlockString(value) { - if (value === '') { - return true; // empty string is printable + if (!isSafe) { + schemaChanges.push({ + type: BreakingChangeType.ARG_CHANGED_KIND, + description: + `${oldType.name}.${oldField.name} arg ${oldArg.name} has changed type from ` + + `${String(oldArg.type)} to ${String(newArg.type)}.`, + }); + } else if (oldArg.defaultValue !== undefined) { + if (newArg.defaultValue === undefined) { + schemaChanges.push({ + type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, + description: `${oldType.name}.${oldField.name} arg ${oldArg.name} defaultValue was removed.`, + }); + } else { + // Since we looking only for client's observable changes we should + // compare default values in the same representation as they are + // represented inside introspection. + const oldValueStr = stringifyValue(oldArg.defaultValue, oldArg.type); + const newValueStr = stringifyValue(newArg.defaultValue, newArg.type); + + if (oldValueStr !== newValueStr) { + schemaChanges.push({ + type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, + description: `${oldType.name}.${oldField.name} arg ${oldArg.name} has changed defaultValue from ${oldValueStr} to ${newValueStr}.`, + }); + } + } + } } - let isEmptyLine = true; - let hasIndent = false; - let hasCommonIndent = true; - let seenNonEmptyLine = false; + for (const newArg of argsDiff.added) { + if ((0, _definition.isRequiredArgument)(newArg)) { + schemaChanges.push({ + type: BreakingChangeType.REQUIRED_ARG_ADDED, + description: `A required arg ${newArg.name} on ${oldType.name}.${oldField.name} was added.`, + }); + } else { + schemaChanges.push({ + type: DangerousChangeType.OPTIONAL_ARG_ADDED, + description: `An optional arg ${newArg.name} on ${oldType.name}.${oldField.name} was added.`, + }); + } + } - for (let i = 0; i < value.length; ++i) { - switch (value.codePointAt(i)) { - case 0x0000: - case 0x0001: - case 0x0002: - case 0x0003: - case 0x0004: - case 0x0005: - case 0x0006: - case 0x0007: - case 0x0008: - case 0x000b: - case 0x000c: - case 0x000e: - case 0x000f: - return false; - // Has non-printable characters + return schemaChanges; +} - case 0x000d: - // \r - return false; - // Has \r or \r\n which will be replaced as \n +function isChangeSafeForObjectOrInterfaceField(oldType, newType) { + if ((0, _definition.isListType)(oldType)) { + return ( + // if they're both lists, make sure the underlying types are compatible + ((0, _definition.isListType)(newType) && + isChangeSafeForObjectOrInterfaceField( + oldType.ofType, + newType.ofType, + )) || // moving from nullable to non-null of the same underlying type is safe + ((0, _definition.isNonNullType)(newType) && + isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType)) + ); + } - case 10: - // \n - if (isEmptyLine && !seenNonEmptyLine) { - return false; // Has leading new line - } + if ((0, _definition.isNonNullType)(oldType)) { + // if they're both non-null, make sure the underlying types are compatible + return ( + (0, _definition.isNonNullType)(newType) && + isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType) + ); + } - seenNonEmptyLine = true; - isEmptyLine = true; - hasIndent = false; - break; + return ( + // if they're both named types, see if their names are equivalent + ((0, _definition.isNamedType)(newType) && oldType.name === newType.name) || // moving from nullable to non-null of the same underlying type is safe + ((0, _definition.isNonNullType)(newType) && + isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType)) + ); +} - case 9: // \t +function isChangeSafeForInputObjectFieldOrFieldArg(oldType, newType) { + if ((0, _definition.isListType)(oldType)) { + // if they're both lists, make sure the underlying types are compatible + return ( + (0, _definition.isListType)(newType) && + isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType) + ); + } - case 32: - // - hasIndent || (hasIndent = isEmptyLine); - break; + if ((0, _definition.isNonNullType)(oldType)) { + return ( + // if they're both non-null, make sure the underlying types are + // compatible + ((0, _definition.isNonNullType)(newType) && + isChangeSafeForInputObjectFieldOrFieldArg( + oldType.ofType, + newType.ofType, + )) || // moving from non-null to nullable of the same underlying type is safe + (!(0, _definition.isNonNullType)(newType) && + isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType)) + ); + } // if they're both named types, see if their names are equivalent - default: - hasCommonIndent && (hasCommonIndent = hasIndent); - isEmptyLine = false; - } + return (0, _definition.isNamedType)(newType) && oldType.name === newType.name; +} + +function typeKindName(type) { + if ((0, _definition.isScalarType)(type)) { + return 'a Scalar type'; } - if (isEmptyLine) { - return false; // Has trailing empty lines + if ((0, _definition.isObjectType)(type)) { + return 'an Object type'; } - if (hasCommonIndent && seenNonEmptyLine) { - return false; // Has internal indent + if ((0, _definition.isInterfaceType)(type)) { + return 'an Interface type'; } - return true; -} -/** - * Print a block string in the indented block form by adding a leading and - * trailing blank line. However, if a block string starts with whitespace and is - * a single-line, adding a leading blank line would strip that whitespace. - * - * @internal - */ + if ((0, _definition.isUnionType)(type)) { + return 'a Union type'; + } -function printBlockString(value, options) { - const escapedValue = value.replace(/"""/g, '\\"""'); // Expand a block string's raw value into independent lines. + if ((0, _definition.isEnumType)(type)) { + return 'an Enum type'; + } - const lines = escapedValue.split(/\r\n|[\n\r]/g); - const isSingleLine = lines.length === 1; // If common indentation is found we can fix some of those cases by adding leading new line + if ((0, _definition.isInputObjectType)(type)) { + return 'an Input type'; + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered. - const forceLeadingNewLine = - lines.length > 1 && - lines - .slice(1) - .every( - (line) => - line.length === 0 || - (0, _characterClasses.isWhiteSpace)(line.charCodeAt(0)), - ); // Trailing triple quotes just looks confusing but doesn't force trailing new line + false || + (0, _invariant.invariant)( + false, + 'Unexpected type: ' + (0, _inspect.inspect)(type), + ); +} - const hasTrailingTripleQuotes = escapedValue.endsWith('\\"""'); // Trailing quote (single or double) or slash forces trailing new line +function stringifyValue(value, type) { + const ast = (0, _astFromValue.astFromValue)(value, type); + ast != null || (0, _invariant.invariant)(false); + return (0, _printer.print)((0, _sortValueNode.sortValueNode)(ast)); +} - const hasTrailingQuote = value.endsWith('"') && !hasTrailingTripleQuotes; - const hasTrailingSlash = value.endsWith('\\'); - const forceTrailingNewline = hasTrailingQuote || hasTrailingSlash; - const printAsMultipleLines = - !(options !== null && options !== void 0 && options.minimize) && // add leading and trailing new lines only if it improves readability - (!isSingleLine || - value.length > 70 || - forceTrailingNewline || - forceLeadingNewLine || - hasTrailingTripleQuotes); - let result = ''; // Format a multi-line block quote to account for leading space. +function diff(oldArray, newArray) { + const added = []; + const removed = []; + const persisted = []; + const oldMap = (0, _keyMap.keyMap)(oldArray, ({ name }) => name); + const newMap = (0, _keyMap.keyMap)(newArray, ({ name }) => name); - const skipLeadingNewLine = - isSingleLine && (0, _characterClasses.isWhiteSpace)(value.charCodeAt(0)); + for (const oldItem of oldArray) { + const newItem = newMap[oldItem.name]; - if ((printAsMultipleLines && !skipLeadingNewLine) || forceLeadingNewLine) { - result += '\n'; + if (newItem === undefined) { + removed.push(oldItem); + } else { + persisted.push([oldItem, newItem]); + } } - result += escapedValue; - - if (printAsMultipleLines || forceTrailingNewline) { - result += '\n'; + for (const newItem of newArray) { + if (oldMap[newItem.name] === undefined) { + added.push(newItem); + } } - return '"""' + result + '"""'; + return { + added, + persisted, + removed, + }; } /***/ }), -/***/ 7234: +/***/ 747: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -280933,82 +283378,203 @@ function printBlockString(value, options) { Object.defineProperty(exports, "__esModule", ({ value: true, })); -exports.isDigit = isDigit; -exports.isLetter = isLetter; -exports.isNameContinue = isNameContinue; -exports.isNameStart = isNameStart; -exports.isWhiteSpace = isWhiteSpace; +exports.getIntrospectionQuery = getIntrospectionQuery; /** - * ``` - * WhiteSpace :: - * - "Horizontal Tab (U+0009)" - * - "Space (U+0020)" - * ``` - * @internal - */ -function isWhiteSpace(code) { - return code === 0x0009 || code === 0x0020; -} -/** - * ``` - * Digit :: one of - * - `0` `1` `2` `3` `4` `5` `6` `7` `8` `9` - * ``` - * @internal + * Produce the GraphQL query recommended for a full schema introspection. + * Accepts optional IntrospectionOptions. */ +function getIntrospectionQuery(options) { + const optionsWithDefault = { + descriptions: true, + specifiedByUrl: false, + directiveIsRepeatable: false, + schemaDescription: false, + inputValueDeprecation: false, + oneOf: false, + ...options, + }; + const descriptions = optionsWithDefault.descriptions ? 'description' : ''; + const specifiedByUrl = optionsWithDefault.specifiedByUrl + ? 'specifiedByURL' + : ''; + const directiveIsRepeatable = optionsWithDefault.directiveIsRepeatable + ? 'isRepeatable' + : ''; + const schemaDescription = optionsWithDefault.schemaDescription + ? descriptions + : ''; -function isDigit(code) { - return code >= 0x0030 && code <= 0x0039; -} -/** - * ``` - * Letter :: one of - * - `A` `B` `C` `D` `E` `F` `G` `H` `I` `J` `K` `L` `M` - * - `N` `O` `P` `Q` `R` `S` `T` `U` `V` `W` `X` `Y` `Z` - * - `a` `b` `c` `d` `e` `f` `g` `h` `i` `j` `k` `l` `m` - * - `n` `o` `p` `q` `r` `s` `t` `u` `v` `w` `x` `y` `z` - * ``` - * @internal - */ + function inputDeprecation(str) { + return optionsWithDefault.inputValueDeprecation ? str : ''; + } -function isLetter(code) { - return ( - (code >= 0x0061 && code <= 0x007a) || // A-Z - (code >= 0x0041 && code <= 0x005a) // a-z - ); -} -/** - * ``` - * NameStart :: - * - Letter - * - `_` - * ``` - * @internal - */ + const oneOf = optionsWithDefault.oneOf ? 'isOneOf' : ''; + return ` + query IntrospectionQuery { + __schema { + ${schemaDescription} + queryType { name kind } + mutationType { name kind } + subscriptionType { name kind } + types { + ...FullType + } + directives { + name + ${descriptions} + ${directiveIsRepeatable} + locations + args${inputDeprecation('(includeDeprecated: true)')} { + ...InputValue + } + } + } + } -function isNameStart(code) { - return isLetter(code) || code === 0x005f; + fragment FullType on __Type { + kind + name + ${descriptions} + ${specifiedByUrl} + ${oneOf} + fields(includeDeprecated: true) { + name + ${descriptions} + args${inputDeprecation('(includeDeprecated: true)')} { + ...InputValue + } + type { + ...TypeRef + } + isDeprecated + deprecationReason + } + inputFields${inputDeprecation('(includeDeprecated: true)')} { + ...InputValue + } + interfaces { + ...TypeRef + } + enumValues(includeDeprecated: true) { + name + ${descriptions} + isDeprecated + deprecationReason + } + possibleTypes { + ...TypeRef + } + } + + fragment InputValue on __InputValue { + name + ${descriptions} + type { ...TypeRef } + defaultValue + ${inputDeprecation('isDeprecated')} + ${inputDeprecation('deprecationReason')} + } + + fragment TypeRef on __Type { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + } + } + } + } + } + } + } + } + } + } + `; } + + +/***/ }), + +/***/ 92854: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.getOperationAST = getOperationAST; + +var _kinds = __nccwpck_require__(11927); + /** - * ``` - * NameContinue :: - * - Letter - * - Digit - * - `_` - * ``` - * @internal + * Returns an operation AST given a document AST and optionally an operation + * name. If a name is not provided, an operation is only returned if only one is + * provided in the document. */ +function getOperationAST(documentAST, operationName) { + let operation = null; -function isNameContinue(code) { - return isLetter(code) || isDigit(code) || code === 0x005f; + for (const definition of documentAST.definitions) { + if (definition.kind === _kinds.Kind.OPERATION_DEFINITION) { + var _definition$name; + + if (operationName == null) { + // If no operation name was provided, only return an Operation if there + // is one defined in the document. Upon encountering the second, return + // null. + if (operation) { + return null; + } + + operation = definition; + } else if ( + ((_definition$name = definition.name) === null || + _definition$name === void 0 + ? void 0 + : _definition$name.value) === operationName + ) { + return definition; + } + } + } + + return operation; } /***/ }), -/***/ 71553: -/***/ ((__unused_webpack_module, exports) => { +/***/ 81605: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -281016,45 +283582,73 @@ function isNameContinue(code) { Object.defineProperty(exports, "__esModule", ({ value: true, })); -exports.DirectiveLocation = void 0; +exports.getOperationRootType = getOperationRootType; -/** - * The set of allowed directive location values. - */ -var DirectiveLocation; -exports.DirectiveLocation = DirectiveLocation; +var _GraphQLError = __nccwpck_require__(4797); -(function (DirectiveLocation) { - DirectiveLocation['QUERY'] = 'QUERY'; - DirectiveLocation['MUTATION'] = 'MUTATION'; - DirectiveLocation['SUBSCRIPTION'] = 'SUBSCRIPTION'; - DirectiveLocation['FIELD'] = 'FIELD'; - DirectiveLocation['FRAGMENT_DEFINITION'] = 'FRAGMENT_DEFINITION'; - DirectiveLocation['FRAGMENT_SPREAD'] = 'FRAGMENT_SPREAD'; - DirectiveLocation['INLINE_FRAGMENT'] = 'INLINE_FRAGMENT'; - DirectiveLocation['VARIABLE_DEFINITION'] = 'VARIABLE_DEFINITION'; - DirectiveLocation['SCHEMA'] = 'SCHEMA'; - DirectiveLocation['SCALAR'] = 'SCALAR'; - DirectiveLocation['OBJECT'] = 'OBJECT'; - DirectiveLocation['FIELD_DEFINITION'] = 'FIELD_DEFINITION'; - DirectiveLocation['ARGUMENT_DEFINITION'] = 'ARGUMENT_DEFINITION'; - DirectiveLocation['INTERFACE'] = 'INTERFACE'; - DirectiveLocation['UNION'] = 'UNION'; - DirectiveLocation['ENUM'] = 'ENUM'; - DirectiveLocation['ENUM_VALUE'] = 'ENUM_VALUE'; - DirectiveLocation['INPUT_OBJECT'] = 'INPUT_OBJECT'; - DirectiveLocation['INPUT_FIELD_DEFINITION'] = 'INPUT_FIELD_DEFINITION'; -})(DirectiveLocation || (exports.DirectiveLocation = DirectiveLocation = {})); /** - * The enum type representing the directive location values. + * Extracts the root type of the operation from the schema. * - * @deprecated Please use `DirectiveLocation`. Will be remove in v17. + * @deprecated Please use `GraphQLSchema.getRootType` instead. Will be removed in v17 */ +function getOperationRootType(schema, operation) { + if (operation.operation === 'query') { + const queryType = schema.getQueryType(); + + if (!queryType) { + throw new _GraphQLError.GraphQLError( + 'Schema does not define the required query root type.', + { + nodes: operation, + }, + ); + } + + return queryType; + } + + if (operation.operation === 'mutation') { + const mutationType = schema.getMutationType(); + + if (!mutationType) { + throw new _GraphQLError.GraphQLError( + 'Schema is not configured for mutations.', + { + nodes: operation, + }, + ); + } + + return mutationType; + } + + if (operation.operation === 'subscription') { + const subscriptionType = schema.getSubscriptionType(); + + if (!subscriptionType) { + throw new _GraphQLError.GraphQLError( + 'Schema is not configured for subscriptions.', + { + nodes: operation, + }, + ); + } + + return subscriptionType; + } + + throw new _GraphQLError.GraphQLError( + 'Can only have query, mutation and subscription operations.', + { + nodes: operation, + }, + ); +} /***/ }), -/***/ 89537: +/***/ 676: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -281063,292 +283657,475 @@ exports.DirectiveLocation = DirectiveLocation; Object.defineProperty(exports, "__esModule", ({ value: true, })); -Object.defineProperty(exports, "BREAK", ({ +Object.defineProperty(exports, "BreakingChangeType", ({ enumerable: true, get: function () { - return _visitor.BREAK; + return _findBreakingChanges.BreakingChangeType; }, })); -Object.defineProperty(exports, "DirectiveLocation", ({ +Object.defineProperty(exports, "DangerousChangeType", ({ enumerable: true, get: function () { - return _directiveLocation.DirectiveLocation; + return _findBreakingChanges.DangerousChangeType; }, })); -Object.defineProperty(exports, "Kind", ({ +Object.defineProperty(exports, "TypeInfo", ({ enumerable: true, get: function () { - return _kinds.Kind; + return _TypeInfo.TypeInfo; }, })); -Object.defineProperty(exports, "Lexer", ({ +Object.defineProperty(exports, "assertValidName", ({ enumerable: true, get: function () { - return _lexer.Lexer; + return _assertValidName.assertValidName; }, })); -Object.defineProperty(exports, "Location", ({ +Object.defineProperty(exports, "astFromValue", ({ enumerable: true, get: function () { - return _ast.Location; + return _astFromValue.astFromValue; }, })); -Object.defineProperty(exports, "OperationTypeNode", ({ +Object.defineProperty(exports, "buildASTSchema", ({ enumerable: true, get: function () { - return _ast.OperationTypeNode; + return _buildASTSchema.buildASTSchema; }, })); -Object.defineProperty(exports, "Source", ({ +Object.defineProperty(exports, "buildClientSchema", ({ enumerable: true, get: function () { - return _source.Source; + return _buildClientSchema.buildClientSchema; }, })); -Object.defineProperty(exports, "Token", ({ +Object.defineProperty(exports, "buildSchema", ({ enumerable: true, get: function () { - return _ast.Token; + return _buildASTSchema.buildSchema; }, })); -Object.defineProperty(exports, "TokenKind", ({ +Object.defineProperty(exports, "coerceInputValue", ({ enumerable: true, get: function () { - return _tokenKind.TokenKind; + return _coerceInputValue.coerceInputValue; }, })); -Object.defineProperty(exports, "getEnterLeaveForKind", ({ +Object.defineProperty(exports, "concatAST", ({ enumerable: true, get: function () { - return _visitor.getEnterLeaveForKind; + return _concatAST.concatAST; }, })); -Object.defineProperty(exports, "getLocation", ({ +Object.defineProperty(exports, "doTypesOverlap", ({ enumerable: true, get: function () { - return _location.getLocation; + return _typeComparators.doTypesOverlap; }, })); -Object.defineProperty(exports, "getVisitFn", ({ +Object.defineProperty(exports, "extendSchema", ({ enumerable: true, get: function () { - return _visitor.getVisitFn; + return _extendSchema.extendSchema; }, })); -Object.defineProperty(exports, "isConstValueNode", ({ +Object.defineProperty(exports, "findBreakingChanges", ({ enumerable: true, get: function () { - return _predicates.isConstValueNode; + return _findBreakingChanges.findBreakingChanges; }, })); -Object.defineProperty(exports, "isDefinitionNode", ({ +Object.defineProperty(exports, "findDangerousChanges", ({ enumerable: true, get: function () { - return _predicates.isDefinitionNode; + return _findBreakingChanges.findDangerousChanges; }, })); -Object.defineProperty(exports, "isExecutableDefinitionNode", ({ +Object.defineProperty(exports, "getIntrospectionQuery", ({ enumerable: true, get: function () { - return _predicates.isExecutableDefinitionNode; + return _getIntrospectionQuery.getIntrospectionQuery; }, })); -Object.defineProperty(exports, "isSelectionNode", ({ +Object.defineProperty(exports, "getOperationAST", ({ enumerable: true, get: function () { - return _predicates.isSelectionNode; + return _getOperationAST.getOperationAST; }, })); -Object.defineProperty(exports, "isTypeDefinitionNode", ({ +Object.defineProperty(exports, "getOperationRootType", ({ enumerable: true, get: function () { - return _predicates.isTypeDefinitionNode; + return _getOperationRootType.getOperationRootType; }, })); -Object.defineProperty(exports, "isTypeExtensionNode", ({ +Object.defineProperty(exports, "introspectionFromSchema", ({ enumerable: true, get: function () { - return _predicates.isTypeExtensionNode; + return _introspectionFromSchema.introspectionFromSchema; }, })); -Object.defineProperty(exports, "isTypeNode", ({ +Object.defineProperty(exports, "isEqualType", ({ enumerable: true, get: function () { - return _predicates.isTypeNode; + return _typeComparators.isEqualType; }, })); -Object.defineProperty(exports, "isTypeSystemDefinitionNode", ({ +Object.defineProperty(exports, "isTypeSubTypeOf", ({ enumerable: true, get: function () { - return _predicates.isTypeSystemDefinitionNode; + return _typeComparators.isTypeSubTypeOf; }, })); -Object.defineProperty(exports, "isTypeSystemExtensionNode", ({ +Object.defineProperty(exports, "isValidNameError", ({ enumerable: true, get: function () { - return _predicates.isTypeSystemExtensionNode; + return _assertValidName.isValidNameError; }, })); -Object.defineProperty(exports, "isValueNode", ({ +Object.defineProperty(exports, "lexicographicSortSchema", ({ enumerable: true, get: function () { - return _predicates.isValueNode; + return _lexicographicSortSchema.lexicographicSortSchema; }, })); -Object.defineProperty(exports, "parse", ({ +Object.defineProperty(exports, "printIntrospectionSchema", ({ enumerable: true, get: function () { - return _parser.parse; + return _printSchema.printIntrospectionSchema; }, })); -Object.defineProperty(exports, "parseConstValue", ({ +Object.defineProperty(exports, "printSchema", ({ enumerable: true, get: function () { - return _parser.parseConstValue; + return _printSchema.printSchema; }, })); -Object.defineProperty(exports, "parseType", ({ +Object.defineProperty(exports, "printType", ({ enumerable: true, get: function () { - return _parser.parseType; + return _printSchema.printType; }, })); -Object.defineProperty(exports, "parseValue", ({ +Object.defineProperty(exports, "separateOperations", ({ enumerable: true, get: function () { - return _parser.parseValue; + return _separateOperations.separateOperations; }, })); -Object.defineProperty(exports, "print", ({ +Object.defineProperty(exports, "stripIgnoredCharacters", ({ enumerable: true, get: function () { - return _printer.print; + return _stripIgnoredCharacters.stripIgnoredCharacters; }, })); -Object.defineProperty(exports, "printLocation", ({ +Object.defineProperty(exports, "typeFromAST", ({ enumerable: true, get: function () { - return _printLocation.printLocation; + return _typeFromAST.typeFromAST; }, })); -Object.defineProperty(exports, "printSourceLocation", ({ +Object.defineProperty(exports, "valueFromAST", ({ enumerable: true, get: function () { - return _printLocation.printSourceLocation; + return _valueFromAST.valueFromAST; }, })); -Object.defineProperty(exports, "visit", ({ +Object.defineProperty(exports, "valueFromASTUntyped", ({ enumerable: true, get: function () { - return _visitor.visit; + return _valueFromASTUntyped.valueFromASTUntyped; }, })); -Object.defineProperty(exports, "visitInParallel", ({ +Object.defineProperty(exports, "visitWithTypeInfo", ({ enumerable: true, get: function () { - return _visitor.visitInParallel; + return _TypeInfo.visitWithTypeInfo; }, })); -var _source = __nccwpck_require__(65521); +var _getIntrospectionQuery = __nccwpck_require__(747); + +var _getOperationAST = __nccwpck_require__(92854); + +var _getOperationRootType = __nccwpck_require__(81605); + +var _introspectionFromSchema = __nccwpck_require__(47371); + +var _buildClientSchema = __nccwpck_require__(9352); + +var _buildASTSchema = __nccwpck_require__(9337); + +var _extendSchema = __nccwpck_require__(51832); + +var _lexicographicSortSchema = __nccwpck_require__(19447); + +var _printSchema = __nccwpck_require__(84166); + +var _typeFromAST = __nccwpck_require__(27664); + +var _valueFromAST = __nccwpck_require__(83181); + +var _valueFromASTUntyped = __nccwpck_require__(86699); + +var _astFromValue = __nccwpck_require__(12653); + +var _TypeInfo = __nccwpck_require__(76625); + +var _coerceInputValue = __nccwpck_require__(39603); + +var _concatAST = __nccwpck_require__(17232); + +var _separateOperations = __nccwpck_require__(29125); + +var _stripIgnoredCharacters = __nccwpck_require__(17766); + +var _typeComparators = __nccwpck_require__(10333); + +var _assertValidName = __nccwpck_require__(25780); + +var _findBreakingChanges = __nccwpck_require__(59366); + + +/***/ }), + +/***/ 47371: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.introspectionFromSchema = introspectionFromSchema; + +var _invariant = __nccwpck_require__(28847); + +var _parser = __nccwpck_require__(50655); + +var _execute = __nccwpck_require__(83677); + +var _getIntrospectionQuery = __nccwpck_require__(747); + +/** + * Build an IntrospectionQuery from a GraphQLSchema + * + * IntrospectionQuery is useful for utilities that care about type and field + * relationships, but do not need to traverse through those relationships. + * + * This is the inverse of buildClientSchema. The primary use case is outside + * of the server context, for instance when doing schema comparisons. + */ +function introspectionFromSchema(schema, options) { + const optionsWithDefaults = { + specifiedByUrl: true, + directiveIsRepeatable: true, + schemaDescription: true, + inputValueDeprecation: true, + oneOf: true, + ...options, + }; + const document = (0, _parser.parse)( + (0, _getIntrospectionQuery.getIntrospectionQuery)(optionsWithDefaults), + ); + const result = (0, _execute.executeSync)({ + schema, + document, + }); + (!result.errors && result.data) || (0, _invariant.invariant)(false); + return result.data; +} + + +/***/ }), + +/***/ 19447: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.lexicographicSortSchema = lexicographicSortSchema; + +var _inspect = __nccwpck_require__(10102); + +var _invariant = __nccwpck_require__(28847); + +var _keyValMap = __nccwpck_require__(49268); + +var _naturalCompare = __nccwpck_require__(20038); + +var _definition = __nccwpck_require__(32150); + +var _directives = __nccwpck_require__(83614); + +var _introspection = __nccwpck_require__(28344); + +var _schema = __nccwpck_require__(8505); + +/** + * Sort GraphQLSchema. + * + * This function returns a sorted copy of the given GraphQLSchema. + */ +function lexicographicSortSchema(schema) { + const schemaConfig = schema.toConfig(); + const typeMap = (0, _keyValMap.keyValMap)( + sortByName(schemaConfig.types), + (type) => type.name, + sortNamedType, + ); + return new _schema.GraphQLSchema({ + ...schemaConfig, + types: Object.values(typeMap), + directives: sortByName(schemaConfig.directives).map(sortDirective), + query: replaceMaybeType(schemaConfig.query), + mutation: replaceMaybeType(schemaConfig.mutation), + subscription: replaceMaybeType(schemaConfig.subscription), + }); + + function replaceType(type) { + if ((0, _definition.isListType)(type)) { + // @ts-expect-error + return new _definition.GraphQLList(replaceType(type.ofType)); + } else if ((0, _definition.isNonNullType)(type)) { + // @ts-expect-error + return new _definition.GraphQLNonNull(replaceType(type.ofType)); + } // @ts-expect-error FIXME: TS Conversion + + return replaceNamedType(type); + } -var _location = __nccwpck_require__(61922); + function replaceNamedType(type) { + return typeMap[type.name]; + } -var _printLocation = __nccwpck_require__(35250); + function replaceMaybeType(maybeType) { + return maybeType && replaceNamedType(maybeType); + } -var _kinds = __nccwpck_require__(11927); + function sortDirective(directive) { + const config = directive.toConfig(); + return new _directives.GraphQLDirective({ + ...config, + locations: sortBy(config.locations, (x) => x), + args: sortArgs(config.args), + }); + } -var _tokenKind = __nccwpck_require__(91565); + function sortArgs(args) { + return sortObjMap(args, (arg) => ({ ...arg, type: replaceType(arg.type) })); + } -var _lexer = __nccwpck_require__(24605); + function sortFields(fieldsMap) { + return sortObjMap(fieldsMap, (field) => ({ + ...field, + type: replaceType(field.type), + args: field.args && sortArgs(field.args), + })); + } -var _parser = __nccwpck_require__(50655); + function sortInputFields(fieldsMap) { + return sortObjMap(fieldsMap, (field) => ({ + ...field, + type: replaceType(field.type), + })); + } -var _printer = __nccwpck_require__(68203); + function sortTypes(array) { + return sortByName(array).map(replaceNamedType); + } -var _visitor = __nccwpck_require__(5678); + function sortNamedType(type) { + if ( + (0, _definition.isScalarType)(type) || + (0, _introspection.isIntrospectionType)(type) + ) { + return type; + } -var _ast = __nccwpck_require__(45494); + if ((0, _definition.isObjectType)(type)) { + const config = type.toConfig(); + return new _definition.GraphQLObjectType({ + ...config, + interfaces: () => sortTypes(config.interfaces), + fields: () => sortFields(config.fields), + }); + } -var _predicates = __nccwpck_require__(20535); + if ((0, _definition.isInterfaceType)(type)) { + const config = type.toConfig(); + return new _definition.GraphQLInterfaceType({ + ...config, + interfaces: () => sortTypes(config.interfaces), + fields: () => sortFields(config.fields), + }); + } -var _directiveLocation = __nccwpck_require__(71553); + if ((0, _definition.isUnionType)(type)) { + const config = type.toConfig(); + return new _definition.GraphQLUnionType({ + ...config, + types: () => sortTypes(config.types), + }); + } + if ((0, _definition.isEnumType)(type)) { + const config = type.toConfig(); + return new _definition.GraphQLEnumType({ + ...config, + values: sortObjMap(config.values, (value) => value), + }); + } -/***/ }), + if ((0, _definition.isInputObjectType)(type)) { + const config = type.toConfig(); + return new _definition.GraphQLInputObjectType({ + ...config, + fields: () => sortInputFields(config.fields), + }); + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered. -/***/ 11927: -/***/ ((__unused_webpack_module, exports) => { + false || + (0, _invariant.invariant)( + false, + 'Unexpected type: ' + (0, _inspect.inspect)(type), + ); + } +} -"use strict"; +function sortObjMap(map, sortValueFn) { + const sortedMap = Object.create(null); + for (const key of Object.keys(map).sort(_naturalCompare.naturalCompare)) { + sortedMap[key] = sortValueFn(map[key]); + } -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.Kind = void 0; + return sortedMap; +} -/** - * The set of allowed kind values for AST nodes. - */ -var Kind; -exports.Kind = Kind; +function sortByName(array) { + return sortBy(array, (obj) => obj.name); +} -(function (Kind) { - Kind['NAME'] = 'Name'; - Kind['DOCUMENT'] = 'Document'; - Kind['OPERATION_DEFINITION'] = 'OperationDefinition'; - Kind['VARIABLE_DEFINITION'] = 'VariableDefinition'; - Kind['SELECTION_SET'] = 'SelectionSet'; - Kind['FIELD'] = 'Field'; - Kind['ARGUMENT'] = 'Argument'; - Kind['FRAGMENT_SPREAD'] = 'FragmentSpread'; - Kind['INLINE_FRAGMENT'] = 'InlineFragment'; - Kind['FRAGMENT_DEFINITION'] = 'FragmentDefinition'; - Kind['VARIABLE'] = 'Variable'; - Kind['INT'] = 'IntValue'; - Kind['FLOAT'] = 'FloatValue'; - Kind['STRING'] = 'StringValue'; - Kind['BOOLEAN'] = 'BooleanValue'; - Kind['NULL'] = 'NullValue'; - Kind['ENUM'] = 'EnumValue'; - Kind['LIST'] = 'ListValue'; - Kind['OBJECT'] = 'ObjectValue'; - Kind['OBJECT_FIELD'] = 'ObjectField'; - Kind['DIRECTIVE'] = 'Directive'; - Kind['NAMED_TYPE'] = 'NamedType'; - Kind['LIST_TYPE'] = 'ListType'; - Kind['NON_NULL_TYPE'] = 'NonNullType'; - Kind['SCHEMA_DEFINITION'] = 'SchemaDefinition'; - Kind['OPERATION_TYPE_DEFINITION'] = 'OperationTypeDefinition'; - Kind['SCALAR_TYPE_DEFINITION'] = 'ScalarTypeDefinition'; - Kind['OBJECT_TYPE_DEFINITION'] = 'ObjectTypeDefinition'; - Kind['FIELD_DEFINITION'] = 'FieldDefinition'; - Kind['INPUT_VALUE_DEFINITION'] = 'InputValueDefinition'; - Kind['INTERFACE_TYPE_DEFINITION'] = 'InterfaceTypeDefinition'; - Kind['UNION_TYPE_DEFINITION'] = 'UnionTypeDefinition'; - Kind['ENUM_TYPE_DEFINITION'] = 'EnumTypeDefinition'; - Kind['ENUM_VALUE_DEFINITION'] = 'EnumValueDefinition'; - Kind['INPUT_OBJECT_TYPE_DEFINITION'] = 'InputObjectTypeDefinition'; - Kind['DIRECTIVE_DEFINITION'] = 'DirectiveDefinition'; - Kind['SCHEMA_EXTENSION'] = 'SchemaExtension'; - Kind['SCALAR_TYPE_EXTENSION'] = 'ScalarTypeExtension'; - Kind['OBJECT_TYPE_EXTENSION'] = 'ObjectTypeExtension'; - Kind['INTERFACE_TYPE_EXTENSION'] = 'InterfaceTypeExtension'; - Kind['UNION_TYPE_EXTENSION'] = 'UnionTypeExtension'; - Kind['ENUM_TYPE_EXTENSION'] = 'EnumTypeExtension'; - Kind['INPUT_OBJECT_TYPE_EXTENSION'] = 'InputObjectTypeExtension'; -})(Kind || (exports.Kind = Kind = {})); -/** - * The enum type representing the possible kind values of AST nodes. - * - * @deprecated Please use `Kind`. Will be remove in v17. - */ +function sortBy(array, mapToKey) { + return array.slice().sort((obj1, obj2) => { + const key1 = mapToKey(obj1); + const key2 = mapToKey(obj2); + return (0, _naturalCompare.naturalCompare)(key1, key2); + }); +} /***/ }), -/***/ 24605: +/***/ 84166: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -281357,1012 +284134,1057 @@ exports.Kind = Kind; Object.defineProperty(exports, "__esModule", ({ value: true, })); -exports.Lexer = void 0; -exports.isPunctuatorTokenKind = isPunctuatorTokenKind; +exports.printIntrospectionSchema = printIntrospectionSchema; +exports.printSchema = printSchema; +exports.printType = printType; -var _syntaxError = __nccwpck_require__(52295); +var _inspect = __nccwpck_require__(10102); -var _ast = __nccwpck_require__(45494); +var _invariant = __nccwpck_require__(28847); var _blockString = __nccwpck_require__(52671); -var _characterClasses = __nccwpck_require__(7234); +var _kinds = __nccwpck_require__(11927); -var _tokenKind = __nccwpck_require__(91565); +var _printer = __nccwpck_require__(68203); + +var _definition = __nccwpck_require__(32150); + +var _directives = __nccwpck_require__(83614); + +var _introspection = __nccwpck_require__(28344); + +var _scalars = __nccwpck_require__(93145); + +var _astFromValue = __nccwpck_require__(12653); + +function printSchema(schema) { + return printFilteredSchema( + schema, + (n) => !(0, _directives.isSpecifiedDirective)(n), + isDefinedType, + ); +} + +function printIntrospectionSchema(schema) { + return printFilteredSchema( + schema, + _directives.isSpecifiedDirective, + _introspection.isIntrospectionType, + ); +} + +function isDefinedType(type) { + return ( + !(0, _scalars.isSpecifiedScalarType)(type) && + !(0, _introspection.isIntrospectionType)(type) + ); +} + +function printFilteredSchema(schema, directiveFilter, typeFilter) { + const directives = schema.getDirectives().filter(directiveFilter); + const types = Object.values(schema.getTypeMap()).filter(typeFilter); + return [ + printSchemaDefinition(schema), + ...directives.map((directive) => printDirective(directive)), + ...types.map((type) => printType(type)), + ] + .filter(Boolean) + .join('\n\n'); +} + +function printSchemaDefinition(schema) { + if (schema.description == null && isSchemaOfCommonNames(schema)) { + return; + } + + const operationTypes = []; + const queryType = schema.getQueryType(); + + if (queryType) { + operationTypes.push(` query: ${queryType.name}`); + } + + const mutationType = schema.getMutationType(); + + if (mutationType) { + operationTypes.push(` mutation: ${mutationType.name}`); + } + + const subscriptionType = schema.getSubscriptionType(); + + if (subscriptionType) { + operationTypes.push(` subscription: ${subscriptionType.name}`); + } + return printDescription(schema) + `schema {\n${operationTypes.join('\n')}\n}`; +} /** - * Given a Source object, creates a Lexer for that source. - * A Lexer is a stateful stream generator in that every time - * it is advanced, it returns the next token in the Source. Assuming the - * source lexes, the final Token emitted by the lexer will be of kind - * EOF, after which the lexer will repeatedly return the same EOF token - * whenever called. + * GraphQL schema define root types for each type of operation. These types are + * the same as any other type and can be named in any manner, however there is + * a common naming convention: + * + * ```graphql + * schema { + * query: Query + * mutation: Mutation + * subscription: Subscription + * } + * ``` + * + * When using this naming convention, the schema description can be omitted. */ -class Lexer { - /** - * The previously focused non-ignored token. - */ - /** - * The currently focused non-ignored token. - */ +function isSchemaOfCommonNames(schema) { + const queryType = schema.getQueryType(); - /** - * The (1-indexed) line containing the current token. - */ + if (queryType && queryType.name !== 'Query') { + return false; + } - /** - * The character offset at which the current line begins. - */ - constructor(source) { - const startOfFileToken = new _ast.Token( - _tokenKind.TokenKind.SOF, - 0, - 0, - 0, - 0, - ); - this.source = source; - this.lastToken = startOfFileToken; - this.token = startOfFileToken; - this.line = 1; - this.lineStart = 0; + const mutationType = schema.getMutationType(); + + if (mutationType && mutationType.name !== 'Mutation') { + return false; } - get [Symbol.toStringTag]() { - return 'Lexer'; + const subscriptionType = schema.getSubscriptionType(); + + if (subscriptionType && subscriptionType.name !== 'Subscription') { + return false; } - /** - * Advances the token stream to the next non-ignored token. - */ - advance() { - this.lastToken = this.token; - const token = (this.token = this.lookahead()); - return token; + return true; +} + +function printType(type) { + if ((0, _definition.isScalarType)(type)) { + return printScalar(type); } - /** - * Looks ahead and returns the next non-ignored token, but does not change - * the state of Lexer. - */ - lookahead() { - let token = this.token; + if ((0, _definition.isObjectType)(type)) { + return printObject(type); + } - if (token.kind !== _tokenKind.TokenKind.EOF) { - do { - if (token.next) { - token = token.next; - } else { - // Read the next token and form a link in the token linked-list. - const nextToken = readNextToken(this, token.end); // @ts-expect-error next is only mutable during parsing. + if ((0, _definition.isInterfaceType)(type)) { + return printInterface(type); + } - token.next = nextToken; // @ts-expect-error prev is only mutable during parsing. + if ((0, _definition.isUnionType)(type)) { + return printUnion(type); + } - nextToken.prev = token; - token = nextToken; - } - } while (token.kind === _tokenKind.TokenKind.COMMENT); - } + if ((0, _definition.isEnumType)(type)) { + return printEnum(type); + } - return token; + if ((0, _definition.isInputObjectType)(type)) { + return printInputObject(type); } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered. + + false || + (0, _invariant.invariant)( + false, + 'Unexpected type: ' + (0, _inspect.inspect)(type), + ); } -/** - * @internal - */ -exports.Lexer = Lexer; +function printScalar(type) { + return ( + printDescription(type) + `scalar ${type.name}` + printSpecifiedByURL(type) + ); +} -function isPunctuatorTokenKind(kind) { +function printImplementedInterfaces(type) { + const interfaces = type.getInterfaces(); + return interfaces.length + ? ' implements ' + interfaces.map((i) => i.name).join(' & ') + : ''; +} + +function printObject(type) { return ( - kind === _tokenKind.TokenKind.BANG || - kind === _tokenKind.TokenKind.DOLLAR || - kind === _tokenKind.TokenKind.AMP || - kind === _tokenKind.TokenKind.PAREN_L || - kind === _tokenKind.TokenKind.PAREN_R || - kind === _tokenKind.TokenKind.SPREAD || - kind === _tokenKind.TokenKind.COLON || - kind === _tokenKind.TokenKind.EQUALS || - kind === _tokenKind.TokenKind.AT || - kind === _tokenKind.TokenKind.BRACKET_L || - kind === _tokenKind.TokenKind.BRACKET_R || - kind === _tokenKind.TokenKind.BRACE_L || - kind === _tokenKind.TokenKind.PIPE || - kind === _tokenKind.TokenKind.BRACE_R + printDescription(type) + + `type ${type.name}` + + printImplementedInterfaces(type) + + printFields(type) ); } -/** - * A Unicode scalar value is any Unicode code point except surrogate code - * points. In other words, the inclusive ranges of values 0x0000 to 0xD7FF and - * 0xE000 to 0x10FFFF. - * - * SourceCharacter :: - * - "Any Unicode scalar value" - */ -function isUnicodeScalarValue(code) { +function printInterface(type) { return ( - (code >= 0x0000 && code <= 0xd7ff) || (code >= 0xe000 && code <= 0x10ffff) + printDescription(type) + + `interface ${type.name}` + + printImplementedInterfaces(type) + + printFields(type) ); } -/** - * The GraphQL specification defines source text as a sequence of unicode scalar - * values (which Unicode defines to exclude surrogate code points). However - * JavaScript defines strings as a sequence of UTF-16 code units which may - * include surrogates. A surrogate pair is a valid source character as it - * encodes a supplementary code point (above U+FFFF), but unpaired surrogate - * code points are not valid source characters. - */ -function isSupplementaryCodePoint(body, location) { +function printUnion(type) { + const types = type.getTypes(); + const possibleTypes = types.length ? ' = ' + types.join(' | ') : ''; + return printDescription(type) + 'union ' + type.name + possibleTypes; +} + +function printEnum(type) { + const values = type + .getValues() + .map( + (value, i) => + printDescription(value, ' ', !i) + + ' ' + + value.name + + printDeprecated(value.deprecationReason), + ); + return printDescription(type) + `enum ${type.name}` + printBlock(values); +} + +function printInputObject(type) { + const fields = Object.values(type.getFields()).map( + (f, i) => printDescription(f, ' ', !i) + ' ' + printInputValue(f), + ); return ( - isLeadingSurrogate(body.charCodeAt(location)) && - isTrailingSurrogate(body.charCodeAt(location + 1)) + printDescription(type) + + `input ${type.name}` + + (type.isOneOf ? ' @oneOf' : '') + + printBlock(fields) ); } -function isLeadingSurrogate(code) { - return code >= 0xd800 && code <= 0xdbff; +function printFields(type) { + const fields = Object.values(type.getFields()).map( + (f, i) => + printDescription(f, ' ', !i) + + ' ' + + f.name + + printArgs(f.args, ' ') + + ': ' + + String(f.type) + + printDeprecated(f.deprecationReason), + ); + return printBlock(fields); } -function isTrailingSurrogate(code) { - return code >= 0xdc00 && code <= 0xdfff; +function printBlock(items) { + return items.length !== 0 ? ' {\n' + items.join('\n') + '\n}' : ''; } -/** - * Prints the code point (or end of file reference) at a given location in a - * source for use in error messages. - * - * Printable ASCII is printed quoted, while other points are printed in Unicode - * code point form (ie. U+1234). - */ -function printCodePointAt(lexer, location) { - const code = lexer.source.body.codePointAt(location); +function printArgs(args, indentation = '') { + if (args.length === 0) { + return ''; + } // If every arg does not have a description, print them on one line. - if (code === undefined) { - return _tokenKind.TokenKind.EOF; - } else if (code >= 0x0020 && code <= 0x007e) { - // Printable ASCII - const char = String.fromCodePoint(code); - return char === '"' ? "'\"'" : `"${char}"`; - } // Unicode code point + if (args.every((arg) => !arg.description)) { + return '(' + args.map(printInputValue).join(', ') + ')'; + } - return 'U+' + code.toString(16).toUpperCase().padStart(4, '0'); + return ( + '(\n' + + args + .map( + (arg, i) => + printDescription(arg, ' ' + indentation, !i) + + ' ' + + indentation + + printInputValue(arg), + ) + .join('\n') + + '\n' + + indentation + + ')' + ); +} + +function printInputValue(arg) { + const defaultAST = (0, _astFromValue.astFromValue)( + arg.defaultValue, + arg.type, + ); + let argDecl = arg.name + ': ' + String(arg.type); + + if (defaultAST) { + argDecl += ` = ${(0, _printer.print)(defaultAST)}`; + } + + return argDecl + printDeprecated(arg.deprecationReason); +} + +function printDirective(directive) { + return ( + printDescription(directive) + + 'directive @' + + directive.name + + printArgs(directive.args) + + (directive.isRepeatable ? ' repeatable' : '') + + ' on ' + + directive.locations.join(' | ') + ); +} + +function printDeprecated(reason) { + if (reason == null) { + return ''; + } + + if (reason !== _directives.DEFAULT_DEPRECATION_REASON) { + const astValue = (0, _printer.print)({ + kind: _kinds.Kind.STRING, + value: reason, + }); + return ` @deprecated(reason: ${astValue})`; + } + + return ' @deprecated'; +} + +function printSpecifiedByURL(scalar) { + if (scalar.specifiedByURL == null) { + return ''; + } + + const astValue = (0, _printer.print)({ + kind: _kinds.Kind.STRING, + value: scalar.specifiedByURL, + }); + return ` @specifiedBy(url: ${astValue})`; +} + +function printDescription(def, indentation = '', firstInBlock = true) { + const { description } = def; + + if (description == null) { + return ''; + } + + const blockString = (0, _printer.print)({ + kind: _kinds.Kind.STRING, + value: description, + block: (0, _blockString.isPrintableAsBlockString)(description), + }); + const prefix = + indentation && !firstInBlock ? '\n' + indentation : indentation; + return prefix + blockString.replace(/\n/g, '\n' + indentation) + '\n'; } + + +/***/ }), + +/***/ 29125: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.separateOperations = separateOperations; + +var _kinds = __nccwpck_require__(11927); + +var _visitor = __nccwpck_require__(5678); + /** - * Create a token with line and column location information. + * separateOperations accepts a single AST document which may contain many + * operations and fragments and returns a collection of AST documents each of + * which contains a single operation as well the fragment definitions it + * refers to. */ +function separateOperations(documentAST) { + const operations = []; + const depGraph = Object.create(null); // Populate metadata and build a dependency graph. -function createToken(lexer, kind, start, end, value) { - const line = lexer.line; - const col = 1 + start - lexer.lineStart; - return new _ast.Token(kind, start, end, line, col, value); + for (const definitionNode of documentAST.definitions) { + switch (definitionNode.kind) { + case _kinds.Kind.OPERATION_DEFINITION: + operations.push(definitionNode); + break; + + case _kinds.Kind.FRAGMENT_DEFINITION: + depGraph[definitionNode.name.value] = collectDependencies( + definitionNode.selectionSet, + ); + break; + + default: // ignore non-executable definitions + } + } // For each operation, produce a new synthesized AST which includes only what + // is necessary for completing that operation. + + const separatedDocumentASTs = Object.create(null); + + for (const operation of operations) { + const dependencies = new Set(); + + for (const fragmentName of collectDependencies(operation.selectionSet)) { + collectTransitiveDependencies(dependencies, depGraph, fragmentName); + } // Provides the empty string for anonymous operations. + + const operationName = operation.name ? operation.name.value : ''; // The list of definition nodes to be included for this operation, sorted + // to retain the same order as the original document. + + separatedDocumentASTs[operationName] = { + kind: _kinds.Kind.DOCUMENT, + definitions: documentAST.definitions.filter( + (node) => + node === operation || + (node.kind === _kinds.Kind.FRAGMENT_DEFINITION && + dependencies.has(node.name.value)), + ), + }; + } + + return separatedDocumentASTs; +} + +// From a dependency graph, collects a list of transitive dependencies by +// recursing through a dependency graph. +function collectTransitiveDependencies(collected, depGraph, fromName) { + if (!collected.has(fromName)) { + collected.add(fromName); + const immediateDeps = depGraph[fromName]; + + if (immediateDeps !== undefined) { + for (const toName of immediateDeps) { + collectTransitiveDependencies(collected, depGraph, toName); + } + } + } } + +function collectDependencies(selectionSet) { + const dependencies = []; + (0, _visitor.visit)(selectionSet, { + FragmentSpread(node) { + dependencies.push(node.name.value); + }, + }); + return dependencies; +} + + +/***/ }), + +/***/ 82278: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.sortValueNode = sortValueNode; + +var _naturalCompare = __nccwpck_require__(20038); + +var _kinds = __nccwpck_require__(11927); + /** - * Gets the next token from the source starting at the given position. + * Sort ValueNode. * - * This skips over whitespace until it finds the next lexable token, then lexes - * punctuators immediately or calls the appropriate helper function for more - * complicated tokens. + * This function returns a sorted copy of the given ValueNode. + * + * @internal */ +function sortValueNode(valueNode) { + switch (valueNode.kind) { + case _kinds.Kind.OBJECT: + return { ...valueNode, fields: sortFields(valueNode.fields) }; -function readNextToken(lexer, start) { - const body = lexer.source.body; - const bodyLength = body.length; - let position = start; + case _kinds.Kind.LIST: + return { ...valueNode, values: valueNode.values.map(sortValueNode) }; - while (position < bodyLength) { - const code = body.charCodeAt(position); // SourceCharacter + case _kinds.Kind.INT: + case _kinds.Kind.FLOAT: + case _kinds.Kind.STRING: + case _kinds.Kind.BOOLEAN: + case _kinds.Kind.NULL: + case _kinds.Kind.ENUM: + case _kinds.Kind.VARIABLE: + return valueNode; + } +} - switch (code) { - // Ignored :: - // - UnicodeBOM - // - WhiteSpace - // - LineTerminator - // - Comment - // - Comma - // - // UnicodeBOM :: "Byte Order Mark (U+FEFF)" - // - // WhiteSpace :: - // - "Horizontal Tab (U+0009)" - // - "Space (U+0020)" - // - // Comma :: , - case 0xfeff: // +function sortFields(fields) { + return fields + .map((fieldNode) => ({ + ...fieldNode, + value: sortValueNode(fieldNode.value), + })) + .sort((fieldA, fieldB) => + (0, _naturalCompare.naturalCompare)(fieldA.name.value, fieldB.name.value), + ); +} - case 0x0009: // \t - case 0x0020: // +/***/ }), - case 0x002c: - // , - ++position; - continue; - // LineTerminator :: - // - "New Line (U+000A)" - // - "Carriage Return (U+000D)" [lookahead != "New Line (U+000A)"] - // - "Carriage Return (U+000D)" "New Line (U+000A)" +/***/ 17766: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - case 0x000a: - // \n - ++position; - ++lexer.line; - lexer.lineStart = position; - continue; +"use strict"; - case 0x000d: - // \r - if (body.charCodeAt(position + 1) === 0x000a) { - position += 2; - } else { - ++position; - } - ++lexer.line; - lexer.lineStart = position; - continue; - // Comment +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.stripIgnoredCharacters = stripIgnoredCharacters; - case 0x0023: - // # - return readComment(lexer, position); - // Token :: - // - Punctuator - // - Name - // - IntValue - // - FloatValue - // - StringValue - // - // Punctuator :: one of ! $ & ( ) ... : = @ [ ] { | } +var _blockString = __nccwpck_require__(52671); - case 0x0021: - // ! - return createToken( - lexer, - _tokenKind.TokenKind.BANG, - position, - position + 1, - ); +var _lexer = __nccwpck_require__(24605); - case 0x0024: - // $ - return createToken( - lexer, - _tokenKind.TokenKind.DOLLAR, - position, - position + 1, - ); +var _source = __nccwpck_require__(65521); - case 0x0026: - // & - return createToken( - lexer, - _tokenKind.TokenKind.AMP, - position, - position + 1, - ); +var _tokenKind = __nccwpck_require__(91565); - case 0x0028: - // ( - return createToken( - lexer, - _tokenKind.TokenKind.PAREN_L, - position, - position + 1, - ); +/** + * Strips characters that are not significant to the validity or execution + * of a GraphQL document: + * - UnicodeBOM + * - WhiteSpace + * - LineTerminator + * - Comment + * - Comma + * - BlockString indentation + * + * Note: It is required to have a delimiter character between neighboring + * non-punctuator tokens and this function always uses single space as delimiter. + * + * It is guaranteed that both input and output documents if parsed would result + * in the exact same AST except for nodes location. + * + * Warning: It is guaranteed that this function will always produce stable results. + * However, it's not guaranteed that it will stay the same between different + * releases due to bugfixes or changes in the GraphQL specification. + * + * Query example: + * + * ```graphql + * query SomeQuery($foo: String!, $bar: String) { + * someField(foo: $foo, bar: $bar) { + * a + * b { + * c + * d + * } + * } + * } + * ``` + * + * Becomes: + * + * ```graphql + * query SomeQuery($foo:String!$bar:String){someField(foo:$foo bar:$bar){a b{c d}}} + * ``` + * + * SDL example: + * + * ```graphql + * """ + * Type description + * """ + * type Foo { + * """ + * Field description + * """ + * bar: String + * } + * ``` + * + * Becomes: + * + * ```graphql + * """Type description""" type Foo{"""Field description""" bar:String} + * ``` + */ +function stripIgnoredCharacters(source) { + const sourceObj = (0, _source.isSource)(source) + ? source + : new _source.Source(source); + const body = sourceObj.body; + const lexer = new _lexer.Lexer(sourceObj); + let strippedBody = ''; + let wasLastAddedTokenNonPunctuator = false; - case 0x0029: - // ) - return createToken( - lexer, - _tokenKind.TokenKind.PAREN_R, - position, - position + 1, - ); + while (lexer.advance().kind !== _tokenKind.TokenKind.EOF) { + const currentToken = lexer.token; + const tokenKind = currentToken.kind; + /** + * Every two non-punctuator tokens should have space between them. + * Also prevent case of non-punctuator token following by spread resulting + * in invalid token (e.g. `1...` is invalid Float token). + */ - case 0x002e: - // . - if ( - body.charCodeAt(position + 1) === 0x002e && - body.charCodeAt(position + 2) === 0x002e - ) { - return createToken( - lexer, - _tokenKind.TokenKind.SPREAD, - position, - position + 3, - ); - } + const isNonPunctuator = !(0, _lexer.isPunctuatorTokenKind)( + currentToken.kind, + ); - break; + if (wasLastAddedTokenNonPunctuator) { + if ( + isNonPunctuator || + currentToken.kind === _tokenKind.TokenKind.SPREAD + ) { + strippedBody += ' '; + } + } - case 0x003a: - // : - return createToken( - lexer, - _tokenKind.TokenKind.COLON, - position, - position + 1, - ); + const tokenBody = body.slice(currentToken.start, currentToken.end); - case 0x003d: - // = - return createToken( - lexer, - _tokenKind.TokenKind.EQUALS, - position, - position + 1, - ); + if (tokenKind === _tokenKind.TokenKind.BLOCK_STRING) { + strippedBody += (0, _blockString.printBlockString)(currentToken.value, { + minimize: true, + }); + } else { + strippedBody += tokenBody; + } - case 0x0040: - // @ - return createToken( - lexer, - _tokenKind.TokenKind.AT, - position, - position + 1, - ); + wasLastAddedTokenNonPunctuator = isNonPunctuator; + } - case 0x005b: - // [ - return createToken( - lexer, - _tokenKind.TokenKind.BRACKET_L, - position, - position + 1, - ); + return strippedBody; +} - case 0x005d: - // ] - return createToken( - lexer, - _tokenKind.TokenKind.BRACKET_R, - position, - position + 1, - ); - case 0x007b: - // { - return createToken( - lexer, - _tokenKind.TokenKind.BRACE_L, - position, - position + 1, - ); +/***/ }), - case 0x007c: - // | - return createToken( - lexer, - _tokenKind.TokenKind.PIPE, - position, - position + 1, - ); +/***/ 10333: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - case 0x007d: - // } - return createToken( - lexer, - _tokenKind.TokenKind.BRACE_R, - position, - position + 1, - ); - // StringValue +"use strict"; - case 0x0022: - // " - if ( - body.charCodeAt(position + 1) === 0x0022 && - body.charCodeAt(position + 2) === 0x0022 - ) { - return readBlockString(lexer, position); - } - return readString(lexer, position); - } // IntValue | FloatValue (Digit | -) +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.doTypesOverlap = doTypesOverlap; +exports.isEqualType = isEqualType; +exports.isTypeSubTypeOf = isTypeSubTypeOf; - if ((0, _characterClasses.isDigit)(code) || code === 0x002d) { - return readNumber(lexer, position, code); - } // Name +var _definition = __nccwpck_require__(32150); - if ((0, _characterClasses.isNameStart)(code)) { - return readName(lexer, position); - } +/** + * Provided two types, return true if the types are equal (invariant). + */ +function isEqualType(typeA, typeB) { + // Equivalent types are equal. + if (typeA === typeB) { + return true; + } // If either type is non-null, the other must also be non-null. - throw (0, _syntaxError.syntaxError)( - lexer.source, - position, - code === 0x0027 - ? 'Unexpected single quote character (\'), did you mean to use a double quote (")?' - : isUnicodeScalarValue(code) || isSupplementaryCodePoint(body, position) - ? `Unexpected character: ${printCodePointAt(lexer, position)}.` - : `Invalid character: ${printCodePointAt(lexer, position)}.`, - ); - } + if ( + (0, _definition.isNonNullType)(typeA) && + (0, _definition.isNonNullType)(typeB) + ) { + return isEqualType(typeA.ofType, typeB.ofType); + } // If either type is a list, the other must also be a list. - return createToken(lexer, _tokenKind.TokenKind.EOF, bodyLength, bodyLength); + if ( + (0, _definition.isListType)(typeA) && + (0, _definition.isListType)(typeB) + ) { + return isEqualType(typeA.ofType, typeB.ofType); + } // Otherwise the types are not equal. + + return false; } /** - * Reads a comment token from the source file. - * - * ``` - * Comment :: # CommentChar* [lookahead != CommentChar] - * - * CommentChar :: SourceCharacter but not LineTerminator - * ``` + * Provided a type and a super type, return true if the first type is either + * equal or a subset of the second super type (covariant). */ -function readComment(lexer, start) { - const body = lexer.source.body; - const bodyLength = body.length; - let position = start + 1; +function isTypeSubTypeOf(schema, maybeSubType, superType) { + // Equivalent type is a valid subtype + if (maybeSubType === superType) { + return true; + } // If superType is non-null, maybeSubType must also be non-null. - while (position < bodyLength) { - const code = body.charCodeAt(position); // LineTerminator (\n | \r) + if ((0, _definition.isNonNullType)(superType)) { + if ((0, _definition.isNonNullType)(maybeSubType)) { + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); + } - if (code === 0x000a || code === 0x000d) { - break; - } // SourceCharacter + return false; + } - if (isUnicodeScalarValue(code)) { - ++position; - } else if (isSupplementaryCodePoint(body, position)) { - position += 2; - } else { - break; + if ((0, _definition.isNonNullType)(maybeSubType)) { + // If superType is nullable, maybeSubType may be non-null or nullable. + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType); + } // If superType type is a list, maybeSubType type must also be a list. + + if ((0, _definition.isListType)(superType)) { + if ((0, _definition.isListType)(maybeSubType)) { + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); } + + return false; } - return createToken( - lexer, - _tokenKind.TokenKind.COMMENT, - start, - position, - body.slice(start + 1, position), + if ((0, _definition.isListType)(maybeSubType)) { + // If superType is not a list, maybeSubType must also be not a list. + return false; + } // If superType type is an abstract type, check if it is super type of maybeSubType. + // Otherwise, the child type is not a valid subtype of the parent type. + + return ( + (0, _definition.isAbstractType)(superType) && + ((0, _definition.isInterfaceType)(maybeSubType) || + (0, _definition.isObjectType)(maybeSubType)) && + schema.isSubType(superType, maybeSubType) ); } /** - * Reads a number token from the source file, either a FloatValue or an IntValue - * depending on whether a FractionalPart or ExponentPart is encountered. - * - * ``` - * IntValue :: IntegerPart [lookahead != {Digit, `.`, NameStart}] - * - * IntegerPart :: - * - NegativeSign? 0 - * - NegativeSign? NonZeroDigit Digit* - * - * NegativeSign :: - - * - * NonZeroDigit :: Digit but not `0` - * - * FloatValue :: - * - IntegerPart FractionalPart ExponentPart [lookahead != {Digit, `.`, NameStart}] - * - IntegerPart FractionalPart [lookahead != {Digit, `.`, NameStart}] - * - IntegerPart ExponentPart [lookahead != {Digit, `.`, NameStart}] - * - * FractionalPart :: . Digit+ - * - * ExponentPart :: ExponentIndicator Sign? Digit+ + * Provided two composite types, determine if they "overlap". Two composite + * types overlap when the Sets of possible concrete types for each intersect. * - * ExponentIndicator :: one of `e` `E` + * This is often used to determine if a fragment of a given type could possibly + * be visited in a context of another type. * - * Sign :: one of + - - * ``` + * This function is commutative. */ -function readNumber(lexer, start, firstCode) { - const body = lexer.source.body; - let position = start; - let code = firstCode; - let isFloat = false; // NegativeSign (-) +function doTypesOverlap(schema, typeA, typeB) { + // Equivalent types overlap + if (typeA === typeB) { + return true; + } - if (code === 0x002d) { - code = body.charCodeAt(++position); - } // Zero (0) + if ((0, _definition.isAbstractType)(typeA)) { + if ((0, _definition.isAbstractType)(typeB)) { + // If both types are abstract, then determine if there is any intersection + // between possible concrete types of each. + return schema + .getPossibleTypes(typeA) + .some((type) => schema.isSubType(typeB, type)); + } // Determine if the latter type is a possible concrete type of the former. - if (code === 0x0030) { - code = body.charCodeAt(++position); + return schema.isSubType(typeA, typeB); + } - if ((0, _characterClasses.isDigit)(code)) { - throw (0, _syntaxError.syntaxError)( - lexer.source, - position, - `Invalid number, unexpected digit after 0: ${printCodePointAt( - lexer, - position, - )}.`, - ); - } - } else { - position = readDigits(lexer, position, code); - code = body.charCodeAt(position); - } // Full stop (.) + if ((0, _definition.isAbstractType)(typeB)) { + // Determine if the former type is a possible concrete type of the latter. + return schema.isSubType(typeB, typeA); + } // Otherwise the types do not overlap. - if (code === 0x002e) { - isFloat = true; - code = body.charCodeAt(++position); - position = readDigits(lexer, position, code); - code = body.charCodeAt(position); - } // E e + return false; +} - if (code === 0x0045 || code === 0x0065) { - isFloat = true; - code = body.charCodeAt(++position); // + - - if (code === 0x002b || code === 0x002d) { - code = body.charCodeAt(++position); +/***/ }), + +/***/ 27664: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.typeFromAST = typeFromAST; + +var _kinds = __nccwpck_require__(11927); + +var _definition = __nccwpck_require__(32150); + +function typeFromAST(schema, typeNode) { + switch (typeNode.kind) { + case _kinds.Kind.LIST_TYPE: { + const innerType = typeFromAST(schema, typeNode.type); + return innerType && new _definition.GraphQLList(innerType); } - position = readDigits(lexer, position, code); - code = body.charCodeAt(position); - } // Numbers cannot be followed by . or NameStart + case _kinds.Kind.NON_NULL_TYPE: { + const innerType = typeFromAST(schema, typeNode.type); + return innerType && new _definition.GraphQLNonNull(innerType); + } - if (code === 0x002e || (0, _characterClasses.isNameStart)(code)) { - throw (0, _syntaxError.syntaxError)( - lexer.source, - position, - `Invalid number, expected digit but got: ${printCodePointAt( - lexer, - position, - )}.`, - ); + case _kinds.Kind.NAMED_TYPE: + return schema.getType(typeNode.name.value); } - - return createToken( - lexer, - isFloat ? _tokenKind.TokenKind.FLOAT : _tokenKind.TokenKind.INT, - start, - position, - body.slice(start, position), - ); } -/** - * Returns the new position in the source after reading one or more digits. - */ -function readDigits(lexer, start, firstCode) { - if (!(0, _characterClasses.isDigit)(firstCode)) { - throw (0, _syntaxError.syntaxError)( - lexer.source, - start, - `Invalid number, expected digit but got: ${printCodePointAt( - lexer, - start, - )}.`, - ); - } - const body = lexer.source.body; - let position = start + 1; // +1 to skip first firstCode +/***/ }), - while ((0, _characterClasses.isDigit)(body.charCodeAt(position))) { - ++position; - } +/***/ 83181: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.valueFromAST = valueFromAST; + +var _inspect = __nccwpck_require__(10102); + +var _invariant = __nccwpck_require__(28847); + +var _keyMap = __nccwpck_require__(10711); + +var _kinds = __nccwpck_require__(11927); + +var _definition = __nccwpck_require__(32150); - return position; -} /** - * Reads a single-quote string token from the source file. + * Produces a JavaScript value given a GraphQL Value AST. * - * ``` - * StringValue :: - * - `""` [lookahead != `"`] - * - `"` StringCharacter+ `"` + * A GraphQL type must be provided, which will be used to interpret different + * GraphQL Value literals. * - * StringCharacter :: - * - SourceCharacter but not `"` or `\` or LineTerminator - * - `\u` EscapedUnicode - * - `\` EscapedCharacter + * Returns `undefined` when the value could not be validly coerced according to + * the provided type. * - * EscapedUnicode :: - * - `{` HexDigit+ `}` - * - HexDigit HexDigit HexDigit HexDigit + * | GraphQL Value | JSON Value | + * | -------------------- | ------------- | + * | Input Object | Object | + * | List | Array | + * | Boolean | Boolean | + * | String | String | + * | Int / Float | Number | + * | Enum Value | Unknown | + * | NullValue | null | * - * EscapedCharacter :: one of `"` `\` `/` `b` `f` `n` `r` `t` - * ``` */ +function valueFromAST(valueNode, type, variables) { + if (!valueNode) { + // When there is no node, then there is also no value. + // Importantly, this is different from returning the value null. + return; + } -function readString(lexer, start) { - const body = lexer.source.body; - const bodyLength = body.length; - let position = start + 1; - let chunkStart = position; - let value = ''; + if (valueNode.kind === _kinds.Kind.VARIABLE) { + const variableName = valueNode.name.value; - while (position < bodyLength) { - const code = body.charCodeAt(position); // Closing Quote (") + if (variables == null || variables[variableName] === undefined) { + // No valid return value. + return; + } - if (code === 0x0022) { - value += body.slice(chunkStart, position); - return createToken( - lexer, - _tokenKind.TokenKind.STRING, - start, - position + 1, - value, - ); - } // Escape Sequence (\) + const variableValue = variables[variableName]; - if (code === 0x005c) { - value += body.slice(chunkStart, position); - const escape = - body.charCodeAt(position + 1) === 0x0075 // u - ? body.charCodeAt(position + 2) === 0x007b // { - ? readEscapedUnicodeVariableWidth(lexer, position) - : readEscapedUnicodeFixedWidth(lexer, position) - : readEscapedCharacter(lexer, position); - value += escape.value; - position += escape.size; - chunkStart = position; - continue; - } // LineTerminator (\n | \r) + if (variableValue === null && (0, _definition.isNonNullType)(type)) { + return; // Invalid: intentionally return no value. + } // Note: This does no further checking that this variable is correct. + // This assumes that this query has been validated and the variable + // usage here is of the correct type. - if (code === 0x000a || code === 0x000d) { - break; - } // SourceCharacter + return variableValue; + } - if (isUnicodeScalarValue(code)) { - ++position; - } else if (isSupplementaryCodePoint(body, position)) { - position += 2; - } else { - throw (0, _syntaxError.syntaxError)( - lexer.source, - position, - `Invalid character within String: ${printCodePointAt( - lexer, - position, - )}.`, - ); + if ((0, _definition.isNonNullType)(type)) { + if (valueNode.kind === _kinds.Kind.NULL) { + return; // Invalid: intentionally return no value. } + + return valueFromAST(valueNode, type.ofType, variables); } - throw (0, _syntaxError.syntaxError)( - lexer.source, - position, - 'Unterminated string.', - ); -} // The string value and lexed size of an escape sequence. + if (valueNode.kind === _kinds.Kind.NULL) { + // This is explicitly returning the value null. + return null; + } -function readEscapedUnicodeVariableWidth(lexer, position) { - const body = lexer.source.body; - let point = 0; - let size = 3; // Cannot be larger than 12 chars (\u{00000000}). + if ((0, _definition.isListType)(type)) { + const itemType = type.ofType; - while (size < 12) { - const code = body.charCodeAt(position + size++); // Closing Brace (}) + if (valueNode.kind === _kinds.Kind.LIST) { + const coercedValues = []; - if (code === 0x007d) { - // Must be at least 5 chars (\u{0}) and encode a Unicode scalar value. - if (size < 5 || !isUnicodeScalarValue(point)) { - break; + for (const itemNode of valueNode.values) { + if (isMissingVariable(itemNode, variables)) { + // If an array contains a missing variable, it is either coerced to + // null or if the item type is non-null, it considered invalid. + if ((0, _definition.isNonNullType)(itemType)) { + return; // Invalid: intentionally return no value. + } + + coercedValues.push(null); + } else { + const itemValue = valueFromAST(itemNode, itemType, variables); + + if (itemValue === undefined) { + return; // Invalid: intentionally return no value. + } + + coercedValues.push(itemValue); + } } - return { - value: String.fromCodePoint(point), - size, - }; - } // Append this hex digit to the code point. + return coercedValues; + } - point = (point << 4) | readHexDigit(code); + const coercedValue = valueFromAST(valueNode, itemType, variables); - if (point < 0) { - break; + if (coercedValue === undefined) { + return; // Invalid: intentionally return no value. } + + return [coercedValue]; } - throw (0, _syntaxError.syntaxError)( - lexer.source, - position, - `Invalid Unicode escape sequence: "${body.slice( - position, - position + size, - )}".`, - ); -} + if ((0, _definition.isInputObjectType)(type)) { + if (valueNode.kind !== _kinds.Kind.OBJECT) { + return; // Invalid: intentionally return no value. + } -function readEscapedUnicodeFixedWidth(lexer, position) { - const body = lexer.source.body; - const code = read16BitHexCode(body, position + 2); + const coercedObj = Object.create(null); + const fieldNodes = (0, _keyMap.keyMap)( + valueNode.fields, + (field) => field.name.value, + ); - if (isUnicodeScalarValue(code)) { - return { - value: String.fromCodePoint(code), - size: 6, - }; - } // GraphQL allows JSON-style surrogate pair escape sequences, but only when - // a valid pair is formed. + for (const field of Object.values(type.getFields())) { + const fieldNode = fieldNodes[field.name]; - if (isLeadingSurrogate(code)) { - // \u - if ( - body.charCodeAt(position + 6) === 0x005c && - body.charCodeAt(position + 7) === 0x0075 - ) { - const trailingCode = read16BitHexCode(body, position + 8); + if (!fieldNode || isMissingVariable(fieldNode.value, variables)) { + if (field.defaultValue !== undefined) { + coercedObj[field.name] = field.defaultValue; + } else if ((0, _definition.isNonNullType)(field.type)) { + return; // Invalid: intentionally return no value. + } - if (isTrailingSurrogate(trailingCode)) { - // JavaScript defines strings as a sequence of UTF-16 code units and - // encodes Unicode code points above U+FFFF using a surrogate pair of - // code units. Since this is a surrogate pair escape sequence, just - // include both codes into the JavaScript string value. Had JavaScript - // not been internally based on UTF-16, then this surrogate pair would - // be decoded to retrieve the supplementary code point. - return { - value: String.fromCodePoint(code, trailingCode), - size: 12, - }; + continue; } - } - } - - throw (0, _syntaxError.syntaxError)( - lexer.source, - position, - `Invalid Unicode escape sequence: "${body.slice(position, position + 6)}".`, - ); -} -/** - * Reads four hexadecimal characters and returns the positive integer that 16bit - * hexadecimal string represents. For example, "000f" will return 15, and "dead" - * will return 57005. - * - * Returns a negative number if any char was not a valid hexadecimal digit. - */ -function read16BitHexCode(body, position) { - // readHexDigit() returns -1 on error. ORing a negative value with any other - // value always produces a negative value. - return ( - (readHexDigit(body.charCodeAt(position)) << 12) | - (readHexDigit(body.charCodeAt(position + 1)) << 8) | - (readHexDigit(body.charCodeAt(position + 2)) << 4) | - readHexDigit(body.charCodeAt(position + 3)) - ); -} -/** - * Reads a hexadecimal character and returns its positive integer value (0-15). - * - * '0' becomes 0, '9' becomes 9 - * 'A' becomes 10, 'F' becomes 15 - * 'a' becomes 10, 'f' becomes 15 - * - * Returns -1 if the provided character code was not a valid hexadecimal digit. - * - * HexDigit :: one of - * - `0` `1` `2` `3` `4` `5` `6` `7` `8` `9` - * - `A` `B` `C` `D` `E` `F` - * - `a` `b` `c` `d` `e` `f` - */ + const fieldValue = valueFromAST(fieldNode.value, field.type, variables); -function readHexDigit(code) { - return code >= 0x0030 && code <= 0x0039 // 0-9 - ? code - 0x0030 - : code >= 0x0041 && code <= 0x0046 // A-F - ? code - 0x0037 - : code >= 0x0061 && code <= 0x0066 // a-f - ? code - 0x0057 - : -1; -} -/** - * | Escaped Character | Code Point | Character Name | - * | ----------------- | ---------- | ---------------------------- | - * | `"` | U+0022 | double quote | - * | `\` | U+005C | reverse solidus (back slash) | - * | `/` | U+002F | solidus (forward slash) | - * | `b` | U+0008 | backspace | - * | `f` | U+000C | form feed | - * | `n` | U+000A | line feed (new line) | - * | `r` | U+000D | carriage return | - * | `t` | U+0009 | horizontal tab | - */ + if (fieldValue === undefined) { + return; // Invalid: intentionally return no value. + } -function readEscapedCharacter(lexer, position) { - const body = lexer.source.body; - const code = body.charCodeAt(position + 1); + coercedObj[field.name] = fieldValue; + } - switch (code) { - case 0x0022: - // " - return { - value: '\u0022', - size: 2, - }; + if (type.isOneOf) { + const keys = Object.keys(coercedObj); - case 0x005c: - // \ - return { - value: '\u005c', - size: 2, - }; + if (keys.length !== 1) { + return; // Invalid: not exactly one key, intentionally return no value. + } - case 0x002f: - // / - return { - value: '\u002f', - size: 2, - }; + if (coercedObj[keys[0]] === null) { + return; // Invalid: value not non-null, intentionally return no value. + } + } - case 0x0062: - // b - return { - value: '\u0008', - size: 2, - }; + return coercedObj; + } - case 0x0066: - // f - return { - value: '\u000c', - size: 2, - }; + if ((0, _definition.isLeafType)(type)) { + // Scalars and Enums fulfill parsing a literal value via parseLiteral(). + // Invalid values represent a failure to parse correctly, in which case + // no value is returned. + let result; - case 0x006e: - // n - return { - value: '\u000a', - size: 2, - }; + try { + result = type.parseLiteral(valueNode, variables); + } catch (_error) { + return; // Invalid: intentionally return no value. + } - case 0x0072: - // r - return { - value: '\u000d', - size: 2, - }; + if (result === undefined) { + return; // Invalid: intentionally return no value. + } - case 0x0074: - // t - return { - value: '\u0009', - size: 2, - }; + return result; } + /* c8 ignore next 3 */ + // Not reachable, all possible input types have been considered. - throw (0, _syntaxError.syntaxError)( - lexer.source, - position, - `Invalid character escape sequence: "${body.slice( - position, - position + 2, - )}".`, + false || + (0, _invariant.invariant)( + false, + 'Unexpected input type: ' + (0, _inspect.inspect)(type), + ); +} // Returns true if the provided valueNode is a variable which is not defined +// in the set of variables. + +function isMissingVariable(valueNode, variables) { + return ( + valueNode.kind === _kinds.Kind.VARIABLE && + (variables == null || variables[valueNode.name.value] === undefined) ); } -/** - * Reads a block string token from the source file. - * - * ``` - * StringValue :: - * - `"""` BlockStringCharacter* `"""` - * - * BlockStringCharacter :: - * - SourceCharacter but not `"""` or `\"""` - * - `\"""` - * ``` - */ -function readBlockString(lexer, start) { - const body = lexer.source.body; - const bodyLength = body.length; - let lineStart = lexer.lineStart; - let position = start + 3; - let chunkStart = position; - let currentLine = ''; - const blockLines = []; - while (position < bodyLength) { - const code = body.charCodeAt(position); // Closing Triple-Quote (""") - - if ( - code === 0x0022 && - body.charCodeAt(position + 1) === 0x0022 && - body.charCodeAt(position + 2) === 0x0022 - ) { - currentLine += body.slice(chunkStart, position); - blockLines.push(currentLine); - const token = createToken( - lexer, - _tokenKind.TokenKind.BLOCK_STRING, - start, - position + 3, // Return a string of the lines joined with U+000A. - (0, _blockString.dedentBlockStringLines)(blockLines).join('\n'), - ); - lexer.line += blockLines.length - 1; - lexer.lineStart = lineStart; - return token; - } // Escaped Triple-Quote (\""") +/***/ }), - if ( - code === 0x005c && - body.charCodeAt(position + 1) === 0x0022 && - body.charCodeAt(position + 2) === 0x0022 && - body.charCodeAt(position + 3) === 0x0022 - ) { - currentLine += body.slice(chunkStart, position); - chunkStart = position + 1; // skip only slash +/***/ 86699: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - position += 4; - continue; - } // LineTerminator +"use strict"; - if (code === 0x000a || code === 0x000d) { - currentLine += body.slice(chunkStart, position); - blockLines.push(currentLine); - if (code === 0x000d && body.charCodeAt(position + 1) === 0x000a) { - position += 2; - } else { - ++position; - } +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.valueFromASTUntyped = valueFromASTUntyped; - currentLine = ''; - chunkStart = position; - lineStart = position; - continue; - } // SourceCharacter +var _keyValMap = __nccwpck_require__(49268); - if (isUnicodeScalarValue(code)) { - ++position; - } else if (isSupplementaryCodePoint(body, position)) { - position += 2; - } else { - throw (0, _syntaxError.syntaxError)( - lexer.source, - position, - `Invalid character within String: ${printCodePointAt( - lexer, - position, - )}.`, - ); - } - } +var _kinds = __nccwpck_require__(11927); - throw (0, _syntaxError.syntaxError)( - lexer.source, - position, - 'Unterminated string.', - ); -} /** - * Reads an alphanumeric + underscore name from the source. + * Produces a JavaScript value given a GraphQL Value AST. + * + * Unlike `valueFromAST()`, no type is provided. The resulting JavaScript value + * will reflect the provided GraphQL value AST. + * + * | GraphQL Value | JavaScript Value | + * | -------------------- | ---------------- | + * | Input Object | Object | + * | List | Array | + * | Boolean | Boolean | + * | String / Enum | String | + * | Int / Float | Number | + * | Null | null | * - * ``` - * Name :: - * - NameStart NameContinue* [lookahead != NameContinue] - * ``` */ +function valueFromASTUntyped(valueNode, variables) { + switch (valueNode.kind) { + case _kinds.Kind.NULL: + return null; -function readName(lexer, start) { - const body = lexer.source.body; - const bodyLength = body.length; - let position = start + 1; + case _kinds.Kind.INT: + return parseInt(valueNode.value, 10); - while (position < bodyLength) { - const code = body.charCodeAt(position); + case _kinds.Kind.FLOAT: + return parseFloat(valueNode.value); - if ((0, _characterClasses.isNameContinue)(code)) { - ++position; - } else { - break; - } - } + case _kinds.Kind.STRING: + case _kinds.Kind.ENUM: + case _kinds.Kind.BOOLEAN: + return valueNode.value; - return createToken( - lexer, - _tokenKind.TokenKind.NAME, - start, - position, - body.slice(start, position), - ); + case _kinds.Kind.LIST: + return valueNode.values.map((node) => + valueFromASTUntyped(node, variables), + ); + + case _kinds.Kind.OBJECT: + return (0, _keyValMap.keyValMap)( + valueNode.fields, + (field) => field.name.value, + (field) => valueFromASTUntyped(field.value, variables), + ); + + case _kinds.Kind.VARIABLE: + return variables === null || variables === void 0 + ? void 0 + : variables[valueNode.name.value]; + } } /***/ }), -/***/ 61922: +/***/ 28263: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -282371,1628 +285193,1209 @@ function readName(lexer, start) { Object.defineProperty(exports, "__esModule", ({ value: true, })); -exports.getLocation = getLocation; +exports.ValidationContext = + exports.SDLValidationContext = + exports.ASTValidationContext = + void 0; -var _invariant = __nccwpck_require__(28847); +var _kinds = __nccwpck_require__(11927); -const LineRegExp = /\r\n|[\n\r]/g; -/** - * Represents a location in a Source. - */ +var _visitor = __nccwpck_require__(5678); + +var _TypeInfo = __nccwpck_require__(76625); /** - * Takes a Source and a UTF-8 character offset, and returns the corresponding - * line and column as a SourceLocation. + * An instance of this class is passed as the "this" context to all validators, + * allowing access to commonly useful contextual information from within a + * validation rule. */ -function getLocation(source, position) { - let lastLineStart = 0; - let line = 1; +class ASTValidationContext { + constructor(ast, onError) { + this._ast = ast; + this._fragments = undefined; + this._fragmentSpreads = new Map(); + this._recursivelyReferencedFragments = new Map(); + this._onError = onError; + } - for (const match of source.body.matchAll(LineRegExp)) { - typeof match.index === 'number' || (0, _invariant.invariant)(false); + get [Symbol.toStringTag]() { + return 'ASTValidationContext'; + } - if (match.index >= position) { - break; + reportError(error) { + this._onError(error); + } + + getDocument() { + return this._ast; + } + + getFragment(name) { + let fragments; + + if (this._fragments) { + fragments = this._fragments; + } else { + fragments = Object.create(null); + + for (const defNode of this.getDocument().definitions) { + if (defNode.kind === _kinds.Kind.FRAGMENT_DEFINITION) { + fragments[defNode.name.value] = defNode; + } + } + + this._fragments = fragments; } - lastLineStart = match.index + match[0].length; - line += 1; + return fragments[name]; } - return { - line, - column: position + 1 - lastLineStart, - }; + getFragmentSpreads(node) { + let spreads = this._fragmentSpreads.get(node); + + if (!spreads) { + spreads = []; + const setsToVisit = [node]; + let set; + + while ((set = setsToVisit.pop())) { + for (const selection of set.selections) { + if (selection.kind === _kinds.Kind.FRAGMENT_SPREAD) { + spreads.push(selection); + } else if (selection.selectionSet) { + setsToVisit.push(selection.selectionSet); + } + } + } + + this._fragmentSpreads.set(node, spreads); + } + + return spreads; + } + + getRecursivelyReferencedFragments(operation) { + let fragments = this._recursivelyReferencedFragments.get(operation); + + if (!fragments) { + fragments = []; + const collectedNames = Object.create(null); + const nodesToVisit = [operation.selectionSet]; + let node; + + while ((node = nodesToVisit.pop())) { + for (const spread of this.getFragmentSpreads(node)) { + const fragName = spread.name.value; + + if (collectedNames[fragName] !== true) { + collectedNames[fragName] = true; + const fragment = this.getFragment(fragName); + + if (fragment) { + fragments.push(fragment); + nodesToVisit.push(fragment.selectionSet); + } + } + } + } + + this._recursivelyReferencedFragments.set(operation, fragments); + } + + return fragments; + } } +exports.ASTValidationContext = ASTValidationContext; -/***/ }), +class SDLValidationContext extends ASTValidationContext { + constructor(ast, schema, onError) { + super(ast, onError); + this._schema = schema; + } -/***/ 50655: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + get [Symbol.toStringTag]() { + return 'SDLValidationContext'; + } -"use strict"; + getSchema() { + return this._schema; + } +} +exports.SDLValidationContext = SDLValidationContext; -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.Parser = void 0; -exports.parse = parse; -exports.parseConstValue = parseConstValue; -exports.parseType = parseType; -exports.parseValue = parseValue; +class ValidationContext extends ASTValidationContext { + constructor(schema, ast, typeInfo, onError) { + super(ast, onError); + this._schema = schema; + this._typeInfo = typeInfo; + this._variableUsages = new Map(); + this._recursiveVariableUsages = new Map(); + } -var _syntaxError = __nccwpck_require__(52295); + get [Symbol.toStringTag]() { + return 'ValidationContext'; + } + + getSchema() { + return this._schema; + } + + getVariableUsages(node) { + let usages = this._variableUsages.get(node); + + if (!usages) { + const newUsages = []; + const typeInfo = new _TypeInfo.TypeInfo(this._schema); + (0, _visitor.visit)( + node, + (0, _TypeInfo.visitWithTypeInfo)(typeInfo, { + VariableDefinition: () => false, -var _ast = __nccwpck_require__(45494); + Variable(variable) { + newUsages.push({ + node: variable, + type: typeInfo.getInputType(), + defaultValue: typeInfo.getDefaultValue(), + parentType: typeInfo.getParentInputType(), + }); + }, + }), + ); + usages = newUsages; -var _directiveLocation = __nccwpck_require__(71553); + this._variableUsages.set(node, usages); + } -var _kinds = __nccwpck_require__(11927); + return usages; + } -var _lexer = __nccwpck_require__(24605); + getRecursiveVariableUsages(operation) { + let usages = this._recursiveVariableUsages.get(operation); -var _source = __nccwpck_require__(65521); + if (!usages) { + usages = this.getVariableUsages(operation); -var _tokenKind = __nccwpck_require__(91565); + for (const frag of this.getRecursivelyReferencedFragments(operation)) { + usages = usages.concat(this.getVariableUsages(frag)); + } -/** - * Given a GraphQL source, parses it into a Document. - * Throws GraphQLError if a syntax error is encountered. - */ -function parse(source, options) { - const parser = new Parser(source, options); - const document = parser.parseDocument(); - Object.defineProperty(document, 'tokenCount', { - enumerable: false, - value: parser.tokenCount, - }); - return document; -} -/** - * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for - * that value. - * Throws GraphQLError if a syntax error is encountered. - * - * This is useful within tools that operate upon GraphQL Values directly and - * in isolation of complete GraphQL documents. - * - * Consider providing the results to the utility function: valueFromAST(). - */ + this._recursiveVariableUsages.set(operation, usages); + } -function parseValue(source, options) { - const parser = new Parser(source, options); - parser.expectToken(_tokenKind.TokenKind.SOF); - const value = parser.parseValueLiteral(false); - parser.expectToken(_tokenKind.TokenKind.EOF); - return value; -} -/** - * Similar to parseValue(), but raises a parse error if it encounters a - * variable. The return type will be a constant value. - */ + return usages; + } -function parseConstValue(source, options) { - const parser = new Parser(source, options); - parser.expectToken(_tokenKind.TokenKind.SOF); - const value = parser.parseConstValueLiteral(); - parser.expectToken(_tokenKind.TokenKind.EOF); - return value; -} -/** - * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for - * that type. - * Throws GraphQLError if a syntax error is encountered. - * - * This is useful within tools that operate upon GraphQL Types directly and - * in isolation of complete GraphQL documents. - * - * Consider providing the results to the utility function: typeFromAST(). - */ + getType() { + return this._typeInfo.getType(); + } -function parseType(source, options) { - const parser = new Parser(source, options); - parser.expectToken(_tokenKind.TokenKind.SOF); - const type = parser.parseTypeReference(); - parser.expectToken(_tokenKind.TokenKind.EOF); - return type; -} -/** - * This class is exported only to assist people in implementing their own parsers - * without duplicating too much code and should be used only as last resort for cases - * such as experimental syntax or if certain features could not be contributed upstream. - * - * It is still part of the internal API and is versioned, so any changes to it are never - * considered breaking changes. If you still need to support multiple versions of the - * library, please use the `versionInfo` variable for version detection. - * - * @internal - */ + getParentType() { + return this._typeInfo.getParentType(); + } -class Parser { - constructor(source, options = {}) { - const sourceObj = (0, _source.isSource)(source) - ? source - : new _source.Source(source); - this._lexer = new _lexer.Lexer(sourceObj); - this._options = options; - this._tokenCounter = 0; + getInputType() { + return this._typeInfo.getInputType(); } - get tokenCount() { - return this._tokenCounter; + getParentInputType() { + return this._typeInfo.getParentInputType(); } - /** - * Converts a name lex token into a name parse node. - */ - parseName() { - const token = this.expectToken(_tokenKind.TokenKind.NAME); - return this.node(token, { - kind: _kinds.Kind.NAME, - value: token.value, - }); - } // Implements the parsing rules in the Document section. + getFieldDef() { + return this._typeInfo.getFieldDef(); + } - /** - * Document : Definition+ - */ + getDirective() { + return this._typeInfo.getDirective(); + } - parseDocument() { - return this.node(this._lexer.token, { - kind: _kinds.Kind.DOCUMENT, - definitions: this.many( - _tokenKind.TokenKind.SOF, - this.parseDefinition, - _tokenKind.TokenKind.EOF, - ), - }); + getArgument() { + return this._typeInfo.getArgument(); } - /** - * Definition : - * - ExecutableDefinition - * - TypeSystemDefinition - * - TypeSystemExtension - * - * ExecutableDefinition : - * - OperationDefinition - * - FragmentDefinition - * - * TypeSystemDefinition : - * - SchemaDefinition - * - TypeDefinition - * - DirectiveDefinition - * - * TypeDefinition : - * - ScalarTypeDefinition - * - ObjectTypeDefinition - * - InterfaceTypeDefinition - * - UnionTypeDefinition - * - EnumTypeDefinition - * - InputObjectTypeDefinition - */ - parseDefinition() { - if (this.peek(_tokenKind.TokenKind.BRACE_L)) { - return this.parseOperationDefinition(); - } // Many definitions begin with a description and require a lookahead. + getEnumValue() { + return this._typeInfo.getEnumValue(); + } +} - const hasDescription = this.peekDescription(); - const keywordToken = hasDescription - ? this._lexer.lookahead() - : this._lexer.token; +exports.ValidationContext = ValidationContext; - if (keywordToken.kind === _tokenKind.TokenKind.NAME) { - switch (keywordToken.value) { - case 'schema': - return this.parseSchemaDefinition(); - case 'scalar': - return this.parseScalarTypeDefinition(); +/***/ }), - case 'type': - return this.parseObjectTypeDefinition(); +/***/ 82201: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - case 'interface': - return this.parseInterfaceTypeDefinition(); +"use strict"; - case 'union': - return this.parseUnionTypeDefinition(); - case 'enum': - return this.parseEnumTypeDefinition(); +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +Object.defineProperty(exports, "ExecutableDefinitionsRule", ({ + enumerable: true, + get: function () { + return _ExecutableDefinitionsRule.ExecutableDefinitionsRule; + }, +})); +Object.defineProperty(exports, "FieldsOnCorrectTypeRule", ({ + enumerable: true, + get: function () { + return _FieldsOnCorrectTypeRule.FieldsOnCorrectTypeRule; + }, +})); +Object.defineProperty(exports, "FragmentsOnCompositeTypesRule", ({ + enumerable: true, + get: function () { + return _FragmentsOnCompositeTypesRule.FragmentsOnCompositeTypesRule; + }, +})); +Object.defineProperty(exports, "KnownArgumentNamesRule", ({ + enumerable: true, + get: function () { + return _KnownArgumentNamesRule.KnownArgumentNamesRule; + }, +})); +Object.defineProperty(exports, "KnownDirectivesRule", ({ + enumerable: true, + get: function () { + return _KnownDirectivesRule.KnownDirectivesRule; + }, +})); +Object.defineProperty(exports, "KnownFragmentNamesRule", ({ + enumerable: true, + get: function () { + return _KnownFragmentNamesRule.KnownFragmentNamesRule; + }, +})); +Object.defineProperty(exports, "KnownTypeNamesRule", ({ + enumerable: true, + get: function () { + return _KnownTypeNamesRule.KnownTypeNamesRule; + }, +})); +Object.defineProperty(exports, "LoneAnonymousOperationRule", ({ + enumerable: true, + get: function () { + return _LoneAnonymousOperationRule.LoneAnonymousOperationRule; + }, +})); +Object.defineProperty(exports, "LoneSchemaDefinitionRule", ({ + enumerable: true, + get: function () { + return _LoneSchemaDefinitionRule.LoneSchemaDefinitionRule; + }, +})); +Object.defineProperty(exports, "MaxIntrospectionDepthRule", ({ + enumerable: true, + get: function () { + return _MaxIntrospectionDepthRule.MaxIntrospectionDepthRule; + }, +})); +Object.defineProperty(exports, "NoDeprecatedCustomRule", ({ + enumerable: true, + get: function () { + return _NoDeprecatedCustomRule.NoDeprecatedCustomRule; + }, +})); +Object.defineProperty(exports, "NoFragmentCyclesRule", ({ + enumerable: true, + get: function () { + return _NoFragmentCyclesRule.NoFragmentCyclesRule; + }, +})); +Object.defineProperty(exports, "NoSchemaIntrospectionCustomRule", ({ + enumerable: true, + get: function () { + return _NoSchemaIntrospectionCustomRule.NoSchemaIntrospectionCustomRule; + }, +})); +Object.defineProperty(exports, "NoUndefinedVariablesRule", ({ + enumerable: true, + get: function () { + return _NoUndefinedVariablesRule.NoUndefinedVariablesRule; + }, +})); +Object.defineProperty(exports, "NoUnusedFragmentsRule", ({ + enumerable: true, + get: function () { + return _NoUnusedFragmentsRule.NoUnusedFragmentsRule; + }, +})); +Object.defineProperty(exports, "NoUnusedVariablesRule", ({ + enumerable: true, + get: function () { + return _NoUnusedVariablesRule.NoUnusedVariablesRule; + }, +})); +Object.defineProperty(exports, "OverlappingFieldsCanBeMergedRule", ({ + enumerable: true, + get: function () { + return _OverlappingFieldsCanBeMergedRule.OverlappingFieldsCanBeMergedRule; + }, +})); +Object.defineProperty(exports, "PossibleFragmentSpreadsRule", ({ + enumerable: true, + get: function () { + return _PossibleFragmentSpreadsRule.PossibleFragmentSpreadsRule; + }, +})); +Object.defineProperty(exports, "PossibleTypeExtensionsRule", ({ + enumerable: true, + get: function () { + return _PossibleTypeExtensionsRule.PossibleTypeExtensionsRule; + }, +})); +Object.defineProperty(exports, "ProvidedRequiredArgumentsRule", ({ + enumerable: true, + get: function () { + return _ProvidedRequiredArgumentsRule.ProvidedRequiredArgumentsRule; + }, +})); +Object.defineProperty(exports, "ScalarLeafsRule", ({ + enumerable: true, + get: function () { + return _ScalarLeafsRule.ScalarLeafsRule; + }, +})); +Object.defineProperty(exports, "SingleFieldSubscriptionsRule", ({ + enumerable: true, + get: function () { + return _SingleFieldSubscriptionsRule.SingleFieldSubscriptionsRule; + }, +})); +Object.defineProperty(exports, "UniqueArgumentDefinitionNamesRule", ({ + enumerable: true, + get: function () { + return _UniqueArgumentDefinitionNamesRule.UniqueArgumentDefinitionNamesRule; + }, +})); +Object.defineProperty(exports, "UniqueArgumentNamesRule", ({ + enumerable: true, + get: function () { + return _UniqueArgumentNamesRule.UniqueArgumentNamesRule; + }, +})); +Object.defineProperty(exports, "UniqueDirectiveNamesRule", ({ + enumerable: true, + get: function () { + return _UniqueDirectiveNamesRule.UniqueDirectiveNamesRule; + }, +})); +Object.defineProperty(exports, "UniqueDirectivesPerLocationRule", ({ + enumerable: true, + get: function () { + return _UniqueDirectivesPerLocationRule.UniqueDirectivesPerLocationRule; + }, +})); +Object.defineProperty(exports, "UniqueEnumValueNamesRule", ({ + enumerable: true, + get: function () { + return _UniqueEnumValueNamesRule.UniqueEnumValueNamesRule; + }, +})); +Object.defineProperty(exports, "UniqueFieldDefinitionNamesRule", ({ + enumerable: true, + get: function () { + return _UniqueFieldDefinitionNamesRule.UniqueFieldDefinitionNamesRule; + }, +})); +Object.defineProperty(exports, "UniqueFragmentNamesRule", ({ + enumerable: true, + get: function () { + return _UniqueFragmentNamesRule.UniqueFragmentNamesRule; + }, +})); +Object.defineProperty(exports, "UniqueInputFieldNamesRule", ({ + enumerable: true, + get: function () { + return _UniqueInputFieldNamesRule.UniqueInputFieldNamesRule; + }, +})); +Object.defineProperty(exports, "UniqueOperationNamesRule", ({ + enumerable: true, + get: function () { + return _UniqueOperationNamesRule.UniqueOperationNamesRule; + }, +})); +Object.defineProperty(exports, "UniqueOperationTypesRule", ({ + enumerable: true, + get: function () { + return _UniqueOperationTypesRule.UniqueOperationTypesRule; + }, +})); +Object.defineProperty(exports, "UniqueTypeNamesRule", ({ + enumerable: true, + get: function () { + return _UniqueTypeNamesRule.UniqueTypeNamesRule; + }, +})); +Object.defineProperty(exports, "UniqueVariableNamesRule", ({ + enumerable: true, + get: function () { + return _UniqueVariableNamesRule.UniqueVariableNamesRule; + }, +})); +Object.defineProperty(exports, "ValidationContext", ({ + enumerable: true, + get: function () { + return _ValidationContext.ValidationContext; + }, +})); +Object.defineProperty(exports, "ValuesOfCorrectTypeRule", ({ + enumerable: true, + get: function () { + return _ValuesOfCorrectTypeRule.ValuesOfCorrectTypeRule; + }, +})); +Object.defineProperty(exports, "VariablesAreInputTypesRule", ({ + enumerable: true, + get: function () { + return _VariablesAreInputTypesRule.VariablesAreInputTypesRule; + }, +})); +Object.defineProperty(exports, "VariablesInAllowedPositionRule", ({ + enumerable: true, + get: function () { + return _VariablesInAllowedPositionRule.VariablesInAllowedPositionRule; + }, +})); +Object.defineProperty(exports, "recommendedRules", ({ + enumerable: true, + get: function () { + return _specifiedRules.recommendedRules; + }, +})); +Object.defineProperty(exports, "specifiedRules", ({ + enumerable: true, + get: function () { + return _specifiedRules.specifiedRules; + }, +})); +Object.defineProperty(exports, "validate", ({ + enumerable: true, + get: function () { + return _validate.validate; + }, +})); - case 'input': - return this.parseInputObjectTypeDefinition(); +var _validate = __nccwpck_require__(14193); - case 'directive': - return this.parseDirectiveDefinition(); - } +var _ValidationContext = __nccwpck_require__(28263); - if (hasDescription) { - throw (0, _syntaxError.syntaxError)( - this._lexer.source, - this._lexer.token.start, - 'Unexpected description, descriptions are supported only on type definitions.', - ); - } +var _specifiedRules = __nccwpck_require__(61556); - switch (keywordToken.value) { - case 'query': - case 'mutation': - case 'subscription': - return this.parseOperationDefinition(); +var _ExecutableDefinitionsRule = __nccwpck_require__(89199); - case 'fragment': - return this.parseFragmentDefinition(); +var _FieldsOnCorrectTypeRule = __nccwpck_require__(63016); - case 'extend': - return this.parseTypeSystemExtension(); - } - } +var _FragmentsOnCompositeTypesRule = __nccwpck_require__(60381); - throw this.unexpected(keywordToken); - } // Implements the parsing rules in the Operations section. +var _KnownArgumentNamesRule = __nccwpck_require__(67147); - /** - * OperationDefinition : - * - SelectionSet - * - OperationType Name? VariableDefinitions? Directives? SelectionSet - */ +var _KnownDirectivesRule = __nccwpck_require__(85303); - parseOperationDefinition() { - const start = this._lexer.token; +var _KnownFragmentNamesRule = __nccwpck_require__(15166); - if (this.peek(_tokenKind.TokenKind.BRACE_L)) { - return this.node(start, { - kind: _kinds.Kind.OPERATION_DEFINITION, - operation: _ast.OperationTypeNode.QUERY, - name: undefined, - variableDefinitions: [], - directives: [], - selectionSet: this.parseSelectionSet(), - }); - } +var _KnownTypeNamesRule = __nccwpck_require__(42509); - const operation = this.parseOperationType(); - let name; +var _LoneAnonymousOperationRule = __nccwpck_require__(45726); - if (this.peek(_tokenKind.TokenKind.NAME)) { - name = this.parseName(); - } +var _NoFragmentCyclesRule = __nccwpck_require__(62564); - return this.node(start, { - kind: _kinds.Kind.OPERATION_DEFINITION, - operation, - name, - variableDefinitions: this.parseVariableDefinitions(), - directives: this.parseDirectives(false), - selectionSet: this.parseSelectionSet(), - }); - } - /** - * OperationType : one of query mutation subscription - */ +var _NoUndefinedVariablesRule = __nccwpck_require__(61671); - parseOperationType() { - const operationToken = this.expectToken(_tokenKind.TokenKind.NAME); +var _NoUnusedFragmentsRule = __nccwpck_require__(192); - switch (operationToken.value) { - case 'query': - return _ast.OperationTypeNode.QUERY; +var _NoUnusedVariablesRule = __nccwpck_require__(40242); - case 'mutation': - return _ast.OperationTypeNode.MUTATION; +var _OverlappingFieldsCanBeMergedRule = __nccwpck_require__(23577); - case 'subscription': - return _ast.OperationTypeNode.SUBSCRIPTION; - } +var _PossibleFragmentSpreadsRule = __nccwpck_require__(62450); - throw this.unexpected(operationToken); - } - /** - * VariableDefinitions : ( VariableDefinition+ ) - */ +var _ProvidedRequiredArgumentsRule = __nccwpck_require__(57669); - parseVariableDefinitions() { - return this.optionalMany( - _tokenKind.TokenKind.PAREN_L, - this.parseVariableDefinition, - _tokenKind.TokenKind.PAREN_R, - ); - } - /** - * VariableDefinition : Variable : Type DefaultValue? Directives[Const]? - */ +var _ScalarLeafsRule = __nccwpck_require__(16830); - parseVariableDefinition() { - return this.node(this._lexer.token, { - kind: _kinds.Kind.VARIABLE_DEFINITION, - variable: this.parseVariable(), - type: - (this.expectToken(_tokenKind.TokenKind.COLON), - this.parseTypeReference()), - defaultValue: this.expectOptionalToken(_tokenKind.TokenKind.EQUALS) - ? this.parseConstValueLiteral() - : undefined, - directives: this.parseConstDirectives(), - }); - } - /** - * Variable : $ Name - */ +var _SingleFieldSubscriptionsRule = __nccwpck_require__(4365); - parseVariable() { - const start = this._lexer.token; - this.expectToken(_tokenKind.TokenKind.DOLLAR); - return this.node(start, { - kind: _kinds.Kind.VARIABLE, - name: this.parseName(), - }); - } - /** - * ``` - * SelectionSet : { Selection+ } - * ``` - */ +var _UniqueArgumentNamesRule = __nccwpck_require__(45799); - parseSelectionSet() { - return this.node(this._lexer.token, { - kind: _kinds.Kind.SELECTION_SET, - selections: this.many( - _tokenKind.TokenKind.BRACE_L, - this.parseSelection, - _tokenKind.TokenKind.BRACE_R, - ), - }); - } - /** - * Selection : - * - Field - * - FragmentSpread - * - InlineFragment - */ +var _UniqueDirectivesPerLocationRule = __nccwpck_require__(61944); - parseSelection() { - return this.peek(_tokenKind.TokenKind.SPREAD) - ? this.parseFragment() - : this.parseField(); - } - /** - * Field : Alias? Name Arguments? Directives? SelectionSet? - * - * Alias : Name : - */ +var _UniqueFragmentNamesRule = __nccwpck_require__(79402); - parseField() { - const start = this._lexer.token; - const nameOrAlias = this.parseName(); - let alias; - let name; +var _UniqueInputFieldNamesRule = __nccwpck_require__(83552); - if (this.expectOptionalToken(_tokenKind.TokenKind.COLON)) { - alias = nameOrAlias; - name = this.parseName(); - } else { - name = nameOrAlias; - } +var _UniqueOperationNamesRule = __nccwpck_require__(94865); - return this.node(start, { - kind: _kinds.Kind.FIELD, - alias, - name, - arguments: this.parseArguments(false), - directives: this.parseDirectives(false), - selectionSet: this.peek(_tokenKind.TokenKind.BRACE_L) - ? this.parseSelectionSet() - : undefined, - }); - } - /** - * Arguments[Const] : ( Argument[?Const]+ ) - */ +var _UniqueVariableNamesRule = __nccwpck_require__(65931); - parseArguments(isConst) { - const item = isConst ? this.parseConstArgument : this.parseArgument; - return this.optionalMany( - _tokenKind.TokenKind.PAREN_L, - item, - _tokenKind.TokenKind.PAREN_R, - ); - } - /** - * Argument[Const] : Name : Value[?Const] - */ +var _ValuesOfCorrectTypeRule = __nccwpck_require__(85189); - parseArgument(isConst = false) { - const start = this._lexer.token; - const name = this.parseName(); - this.expectToken(_tokenKind.TokenKind.COLON); - return this.node(start, { - kind: _kinds.Kind.ARGUMENT, - name, - value: this.parseValueLiteral(isConst), - }); - } +var _VariablesAreInputTypesRule = __nccwpck_require__(99506); - parseConstArgument() { - return this.parseArgument(true); - } // Implements the parsing rules in the Fragments section. +var _VariablesInAllowedPositionRule = __nccwpck_require__(8815); - /** - * Corresponds to both FragmentSpread and InlineFragment in the spec. - * - * FragmentSpread : ... FragmentName Directives? - * - * InlineFragment : ... TypeCondition? Directives? SelectionSet - */ +var _MaxIntrospectionDepthRule = __nccwpck_require__(53318); - parseFragment() { - const start = this._lexer.token; - this.expectToken(_tokenKind.TokenKind.SPREAD); - const hasTypeCondition = this.expectOptionalKeyword('on'); +var _LoneSchemaDefinitionRule = __nccwpck_require__(48307); - if (!hasTypeCondition && this.peek(_tokenKind.TokenKind.NAME)) { - return this.node(start, { - kind: _kinds.Kind.FRAGMENT_SPREAD, - name: this.parseFragmentName(), - directives: this.parseDirectives(false), - }); - } +var _UniqueOperationTypesRule = __nccwpck_require__(31492); - return this.node(start, { - kind: _kinds.Kind.INLINE_FRAGMENT, - typeCondition: hasTypeCondition ? this.parseNamedType() : undefined, - directives: this.parseDirectives(false), - selectionSet: this.parseSelectionSet(), - }); - } - /** - * FragmentDefinition : - * - fragment FragmentName on TypeCondition Directives? SelectionSet - * - * TypeCondition : NamedType - */ +var _UniqueTypeNamesRule = __nccwpck_require__(24316); - parseFragmentDefinition() { - const start = this._lexer.token; - this.expectKeyword('fragment'); // Legacy support for defining variables within fragments changes - // the grammar of FragmentDefinition: - // - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet +var _UniqueEnumValueNamesRule = __nccwpck_require__(44437); - if (this._options.allowLegacyFragmentVariables === true) { - return this.node(start, { - kind: _kinds.Kind.FRAGMENT_DEFINITION, - name: this.parseFragmentName(), - variableDefinitions: this.parseVariableDefinitions(), - typeCondition: (this.expectKeyword('on'), this.parseNamedType()), - directives: this.parseDirectives(false), - selectionSet: this.parseSelectionSet(), - }); - } +var _UniqueFieldDefinitionNamesRule = __nccwpck_require__(9502); - return this.node(start, { - kind: _kinds.Kind.FRAGMENT_DEFINITION, - name: this.parseFragmentName(), - typeCondition: (this.expectKeyword('on'), this.parseNamedType()), - directives: this.parseDirectives(false), - selectionSet: this.parseSelectionSet(), - }); - } - /** - * FragmentName : Name but not `on` - */ +var _UniqueArgumentDefinitionNamesRule = __nccwpck_require__(55104); - parseFragmentName() { - if (this._lexer.token.value === 'on') { - throw this.unexpected(); - } +var _UniqueDirectiveNamesRule = __nccwpck_require__(17074); - return this.parseName(); - } // Implements the parsing rules in the Values section. +var _PossibleTypeExtensionsRule = __nccwpck_require__(70075); - /** - * Value[Const] : - * - [~Const] Variable - * - IntValue - * - FloatValue - * - StringValue - * - BooleanValue - * - NullValue - * - EnumValue - * - ListValue[?Const] - * - ObjectValue[?Const] - * - * BooleanValue : one of `true` `false` - * - * NullValue : `null` - * - * EnumValue : Name but not `true`, `false` or `null` - */ +var _NoDeprecatedCustomRule = __nccwpck_require__(33915); - parseValueLiteral(isConst) { - const token = this._lexer.token; +var _NoSchemaIntrospectionCustomRule = __nccwpck_require__(39478); - switch (token.kind) { - case _tokenKind.TokenKind.BRACKET_L: - return this.parseList(isConst); - case _tokenKind.TokenKind.BRACE_L: - return this.parseObject(isConst); +/***/ }), - case _tokenKind.TokenKind.INT: - this.advanceLexer(); - return this.node(token, { - kind: _kinds.Kind.INT, - value: token.value, - }); +/***/ 89199: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - case _tokenKind.TokenKind.FLOAT: - this.advanceLexer(); - return this.node(token, { - kind: _kinds.Kind.FLOAT, - value: token.value, - }); +"use strict"; - case _tokenKind.TokenKind.STRING: - case _tokenKind.TokenKind.BLOCK_STRING: - return this.parseStringLiteral(); - case _tokenKind.TokenKind.NAME: - this.advanceLexer(); +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.ExecutableDefinitionsRule = ExecutableDefinitionsRule; - switch (token.value) { - case 'true': - return this.node(token, { - kind: _kinds.Kind.BOOLEAN, - value: true, - }); +var _GraphQLError = __nccwpck_require__(4797); - case 'false': - return this.node(token, { - kind: _kinds.Kind.BOOLEAN, - value: false, - }); +var _kinds = __nccwpck_require__(11927); - case 'null': - return this.node(token, { - kind: _kinds.Kind.NULL, - }); +var _predicates = __nccwpck_require__(20535); - default: - return this.node(token, { - kind: _kinds.Kind.ENUM, - value: token.value, - }); +/** + * Executable definitions + * + * A GraphQL document is only valid for execution if all definitions are either + * operation or fragment definitions. + * + * See https://spec.graphql.org/draft/#sec-Executable-Definitions + */ +function ExecutableDefinitionsRule(context) { + return { + Document(node) { + for (const definition of node.definitions) { + if (!(0, _predicates.isExecutableDefinitionNode)(definition)) { + const defName = + definition.kind === _kinds.Kind.SCHEMA_DEFINITION || + definition.kind === _kinds.Kind.SCHEMA_EXTENSION + ? 'schema' + : '"' + definition.name.value + '"'; + context.reportError( + new _GraphQLError.GraphQLError( + `The ${defName} definition is not executable.`, + { + nodes: definition, + }, + ), + ); } + } - case _tokenKind.TokenKind.DOLLAR: - if (isConst) { - this.expectToken(_tokenKind.TokenKind.DOLLAR); + return false; + }, + }; +} - if (this._lexer.token.kind === _tokenKind.TokenKind.NAME) { - const varName = this._lexer.token.value; - throw (0, _syntaxError.syntaxError)( - this._lexer.source, - token.start, - `Unexpected variable "$${varName}" in constant value.`, - ); - } else { - throw this.unexpected(token); - } - } - return this.parseVariable(); +/***/ }), - default: - throw this.unexpected(); - } - } +/***/ 63016: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - parseConstValueLiteral() { - return this.parseValueLiteral(true); - } +"use strict"; - parseStringLiteral() { - const token = this._lexer.token; - this.advanceLexer(); - return this.node(token, { - kind: _kinds.Kind.STRING, - value: token.value, - block: token.kind === _tokenKind.TokenKind.BLOCK_STRING, - }); - } - /** - * ListValue[Const] : - * - [ ] - * - [ Value[?Const]+ ] - */ - parseList(isConst) { - const item = () => this.parseValueLiteral(isConst); +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.FieldsOnCorrectTypeRule = FieldsOnCorrectTypeRule; - return this.node(this._lexer.token, { - kind: _kinds.Kind.LIST, - values: this.any( - _tokenKind.TokenKind.BRACKET_L, - item, - _tokenKind.TokenKind.BRACKET_R, - ), - }); - } - /** - * ``` - * ObjectValue[Const] : - * - { } - * - { ObjectField[?Const]+ } - * ``` - */ +var _didYouMean = __nccwpck_require__(42878); - parseObject(isConst) { - const item = () => this.parseObjectField(isConst); +var _naturalCompare = __nccwpck_require__(20038); - return this.node(this._lexer.token, { - kind: _kinds.Kind.OBJECT, - fields: this.any( - _tokenKind.TokenKind.BRACE_L, - item, - _tokenKind.TokenKind.BRACE_R, - ), - }); - } - /** - * ObjectField[Const] : Name : Value[?Const] - */ +var _suggestionList = __nccwpck_require__(57704); - parseObjectField(isConst) { - const start = this._lexer.token; - const name = this.parseName(); - this.expectToken(_tokenKind.TokenKind.COLON); - return this.node(start, { - kind: _kinds.Kind.OBJECT_FIELD, - name, - value: this.parseValueLiteral(isConst), - }); - } // Implements the parsing rules in the Directives section. +var _GraphQLError = __nccwpck_require__(4797); - /** - * Directives[Const] : Directive[?Const]+ - */ +var _definition = __nccwpck_require__(32150); - parseDirectives(isConst) { - const directives = []; +/** + * Fields on correct type + * + * A GraphQL document is only valid if all fields selected are defined by the + * parent type, or are an allowed meta field such as __typename. + * + * See https://spec.graphql.org/draft/#sec-Field-Selections + */ +function FieldsOnCorrectTypeRule(context) { + return { + Field(node) { + const type = context.getParentType(); - while (this.peek(_tokenKind.TokenKind.AT)) { - directives.push(this.parseDirective(isConst)); - } + if (type) { + const fieldDef = context.getFieldDef(); - return directives; - } + if (!fieldDef) { + // This field doesn't exist, lets look for suggestions. + const schema = context.getSchema(); + const fieldName = node.name.value; // First determine if there are any suggested types to condition on. - parseConstDirectives() { - return this.parseDirectives(true); - } - /** - * ``` - * Directive[Const] : @ Name Arguments[?Const]? - * ``` - */ + let suggestion = (0, _didYouMean.didYouMean)( + 'to use an inline fragment on', + getSuggestedTypeNames(schema, type, fieldName), + ); // If there are no suggested types, then perhaps this was a typo? - parseDirective(isConst) { - const start = this._lexer.token; - this.expectToken(_tokenKind.TokenKind.AT); - return this.node(start, { - kind: _kinds.Kind.DIRECTIVE, - name: this.parseName(), - arguments: this.parseArguments(isConst), - }); - } // Implements the parsing rules in the Types section. + if (suggestion === '') { + suggestion = (0, _didYouMean.didYouMean)( + getSuggestedFieldNames(type, fieldName), + ); + } // Report an error, including helpful suggestions. - /** - * Type : - * - NamedType - * - ListType - * - NonNullType - */ + context.reportError( + new _GraphQLError.GraphQLError( + `Cannot query field "${fieldName}" on type "${type.name}".` + + suggestion, + { + nodes: node, + }, + ), + ); + } + } + }, + }; +} +/** + * Go through all of the implementations of type, as well as the interfaces that + * they implement. If any of those types include the provided field, suggest them, + * sorted by how often the type is referenced. + */ - parseTypeReference() { - const start = this._lexer.token; - let type; +function getSuggestedTypeNames(schema, type, fieldName) { + if (!(0, _definition.isAbstractType)(type)) { + // Must be an Object type, which does not have possible fields. + return []; + } - if (this.expectOptionalToken(_tokenKind.TokenKind.BRACKET_L)) { - const innerType = this.parseTypeReference(); - this.expectToken(_tokenKind.TokenKind.BRACKET_R); - type = this.node(start, { - kind: _kinds.Kind.LIST_TYPE, - type: innerType, - }); - } else { - type = this.parseNamedType(); - } + const suggestedTypes = new Set(); + const usageCount = Object.create(null); - if (this.expectOptionalToken(_tokenKind.TokenKind.BANG)) { - return this.node(start, { - kind: _kinds.Kind.NON_NULL_TYPE, - type, - }); - } + for (const possibleType of schema.getPossibleTypes(type)) { + if (!possibleType.getFields()[fieldName]) { + continue; + } // This object type defines this field. - return type; - } - /** - * NamedType : Name - */ + suggestedTypes.add(possibleType); + usageCount[possibleType.name] = 1; - parseNamedType() { - return this.node(this._lexer.token, { - kind: _kinds.Kind.NAMED_TYPE, - name: this.parseName(), - }); - } // Implements the parsing rules in the Type Definition section. + for (const possibleInterface of possibleType.getInterfaces()) { + var _usageCount$possibleI; - peekDescription() { - return ( - this.peek(_tokenKind.TokenKind.STRING) || - this.peek(_tokenKind.TokenKind.BLOCK_STRING) - ); - } - /** - * Description : StringValue - */ + if (!possibleInterface.getFields()[fieldName]) { + continue; + } // This interface type defines this field. - parseDescription() { - if (this.peekDescription()) { - return this.parseStringLiteral(); + suggestedTypes.add(possibleInterface); + usageCount[possibleInterface.name] = + ((_usageCount$possibleI = usageCount[possibleInterface.name]) !== + null && _usageCount$possibleI !== void 0 + ? _usageCount$possibleI + : 0) + 1; } } - /** - * ``` - * SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ } - * ``` - */ - - parseSchemaDefinition() { - const start = this._lexer.token; - const description = this.parseDescription(); - this.expectKeyword('schema'); - const directives = this.parseConstDirectives(); - const operationTypes = this.many( - _tokenKind.TokenKind.BRACE_L, - this.parseOperationTypeDefinition, - _tokenKind.TokenKind.BRACE_R, - ); - return this.node(start, { - kind: _kinds.Kind.SCHEMA_DEFINITION, - description, - directives, - operationTypes, - }); - } - /** - * OperationTypeDefinition : OperationType : NamedType - */ - parseOperationTypeDefinition() { - const start = this._lexer.token; - const operation = this.parseOperationType(); - this.expectToken(_tokenKind.TokenKind.COLON); - const type = this.parseNamedType(); - return this.node(start, { - kind: _kinds.Kind.OPERATION_TYPE_DEFINITION, - operation, - type, - }); - } - /** - * ScalarTypeDefinition : Description? scalar Name Directives[Const]? - */ + return [...suggestedTypes] + .sort((typeA, typeB) => { + // Suggest both interface and object types based on how common they are. + const usageCountDiff = usageCount[typeB.name] - usageCount[typeA.name]; - parseScalarTypeDefinition() { - const start = this._lexer.token; - const description = this.parseDescription(); - this.expectKeyword('scalar'); - const name = this.parseName(); - const directives = this.parseConstDirectives(); - return this.node(start, { - kind: _kinds.Kind.SCALAR_TYPE_DEFINITION, - description, - name, - directives, - }); - } - /** - * ObjectTypeDefinition : - * Description? - * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition? - */ + if (usageCountDiff !== 0) { + return usageCountDiff; + } // Suggest super types first followed by subtypes - parseObjectTypeDefinition() { - const start = this._lexer.token; - const description = this.parseDescription(); - this.expectKeyword('type'); - const name = this.parseName(); - const interfaces = this.parseImplementsInterfaces(); - const directives = this.parseConstDirectives(); - const fields = this.parseFieldsDefinition(); - return this.node(start, { - kind: _kinds.Kind.OBJECT_TYPE_DEFINITION, - description, - name, - interfaces, - directives, - fields, - }); - } - /** - * ImplementsInterfaces : - * - implements `&`? NamedType - * - ImplementsInterfaces & NamedType - */ + if ( + (0, _definition.isInterfaceType)(typeA) && + schema.isSubType(typeA, typeB) + ) { + return -1; + } - parseImplementsInterfaces() { - return this.expectOptionalKeyword('implements') - ? this.delimitedMany(_tokenKind.TokenKind.AMP, this.parseNamedType) - : []; - } - /** - * ``` - * FieldsDefinition : { FieldDefinition+ } - * ``` - */ + if ( + (0, _definition.isInterfaceType)(typeB) && + schema.isSubType(typeB, typeA) + ) { + return 1; + } - parseFieldsDefinition() { - return this.optionalMany( - _tokenKind.TokenKind.BRACE_L, - this.parseFieldDefinition, - _tokenKind.TokenKind.BRACE_R, - ); - } - /** - * FieldDefinition : - * - Description? Name ArgumentsDefinition? : Type Directives[Const]? - */ + return (0, _naturalCompare.naturalCompare)(typeA.name, typeB.name); + }) + .map((x) => x.name); +} +/** + * For the field name provided, determine if there are any similar field names + * that may be the result of a typo. + */ - parseFieldDefinition() { - const start = this._lexer.token; - const description = this.parseDescription(); - const name = this.parseName(); - const args = this.parseArgumentDefs(); - this.expectToken(_tokenKind.TokenKind.COLON); - const type = this.parseTypeReference(); - const directives = this.parseConstDirectives(); - return this.node(start, { - kind: _kinds.Kind.FIELD_DEFINITION, - description, - name, - arguments: args, - type, - directives, - }); - } - /** - * ArgumentsDefinition : ( InputValueDefinition+ ) - */ +function getSuggestedFieldNames(type, fieldName) { + if ( + (0, _definition.isObjectType)(type) || + (0, _definition.isInterfaceType)(type) + ) { + const possibleFieldNames = Object.keys(type.getFields()); + return (0, _suggestionList.suggestionList)(fieldName, possibleFieldNames); + } // Otherwise, must be a Union type, which does not define fields. - parseArgumentDefs() { - return this.optionalMany( - _tokenKind.TokenKind.PAREN_L, - this.parseInputValueDef, - _tokenKind.TokenKind.PAREN_R, - ); - } - /** - * InputValueDefinition : - * - Description? Name : Type DefaultValue? Directives[Const]? - */ + return []; +} - parseInputValueDef() { - const start = this._lexer.token; - const description = this.parseDescription(); - const name = this.parseName(); - this.expectToken(_tokenKind.TokenKind.COLON); - const type = this.parseTypeReference(); - let defaultValue; - if (this.expectOptionalToken(_tokenKind.TokenKind.EQUALS)) { - defaultValue = this.parseConstValueLiteral(); - } +/***/ }), - const directives = this.parseConstDirectives(); - return this.node(start, { - kind: _kinds.Kind.INPUT_VALUE_DEFINITION, - description, - name, - type, - defaultValue, - directives, - }); - } - /** - * InterfaceTypeDefinition : - * - Description? interface Name Directives[Const]? FieldsDefinition? - */ +/***/ 60381: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - parseInterfaceTypeDefinition() { - const start = this._lexer.token; - const description = this.parseDescription(); - this.expectKeyword('interface'); - const name = this.parseName(); - const interfaces = this.parseImplementsInterfaces(); - const directives = this.parseConstDirectives(); - const fields = this.parseFieldsDefinition(); - return this.node(start, { - kind: _kinds.Kind.INTERFACE_TYPE_DEFINITION, - description, - name, - interfaces, - directives, - fields, - }); - } - /** - * UnionTypeDefinition : - * - Description? union Name Directives[Const]? UnionMemberTypes? - */ +"use strict"; - parseUnionTypeDefinition() { - const start = this._lexer.token; - const description = this.parseDescription(); - this.expectKeyword('union'); - const name = this.parseName(); - const directives = this.parseConstDirectives(); - const types = this.parseUnionMemberTypes(); - return this.node(start, { - kind: _kinds.Kind.UNION_TYPE_DEFINITION, - description, - name, - directives, - types, - }); - } - /** - * UnionMemberTypes : - * - = `|`? NamedType - * - UnionMemberTypes | NamedType - */ - parseUnionMemberTypes() { - return this.expectOptionalToken(_tokenKind.TokenKind.EQUALS) - ? this.delimitedMany(_tokenKind.TokenKind.PIPE, this.parseNamedType) - : []; - } - /** - * EnumTypeDefinition : - * - Description? enum Name Directives[Const]? EnumValuesDefinition? - */ +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.FragmentsOnCompositeTypesRule = FragmentsOnCompositeTypesRule; - parseEnumTypeDefinition() { - const start = this._lexer.token; - const description = this.parseDescription(); - this.expectKeyword('enum'); - const name = this.parseName(); - const directives = this.parseConstDirectives(); - const values = this.parseEnumValuesDefinition(); - return this.node(start, { - kind: _kinds.Kind.ENUM_TYPE_DEFINITION, - description, - name, - directives, - values, - }); - } - /** - * ``` - * EnumValuesDefinition : { EnumValueDefinition+ } - * ``` - */ +var _GraphQLError = __nccwpck_require__(4797); - parseEnumValuesDefinition() { - return this.optionalMany( - _tokenKind.TokenKind.BRACE_L, - this.parseEnumValueDefinition, - _tokenKind.TokenKind.BRACE_R, - ); - } - /** - * EnumValueDefinition : Description? EnumValue Directives[Const]? - */ +var _printer = __nccwpck_require__(68203); - parseEnumValueDefinition() { - const start = this._lexer.token; - const description = this.parseDescription(); - const name = this.parseEnumValueName(); - const directives = this.parseConstDirectives(); - return this.node(start, { - kind: _kinds.Kind.ENUM_VALUE_DEFINITION, - description, - name, - directives, - }); - } - /** - * EnumValue : Name but not `true`, `false` or `null` - */ +var _definition = __nccwpck_require__(32150); - parseEnumValueName() { - if ( - this._lexer.token.value === 'true' || - this._lexer.token.value === 'false' || - this._lexer.token.value === 'null' - ) { - throw (0, _syntaxError.syntaxError)( - this._lexer.source, - this._lexer.token.start, - `${getTokenDesc( - this._lexer.token, - )} is reserved and cannot be used for an enum value.`, - ); - } +var _typeFromAST = __nccwpck_require__(27664); - return this.parseName(); - } - /** - * InputObjectTypeDefinition : - * - Description? input Name Directives[Const]? InputFieldsDefinition? - */ +/** + * Fragments on composite type + * + * Fragments use a type condition to determine if they apply, since fragments + * can only be spread into a composite type (object, interface, or union), the + * type condition must also be a composite type. + * + * See https://spec.graphql.org/draft/#sec-Fragments-On-Composite-Types + */ +function FragmentsOnCompositeTypesRule(context) { + return { + InlineFragment(node) { + const typeCondition = node.typeCondition; - parseInputObjectTypeDefinition() { - const start = this._lexer.token; - const description = this.parseDescription(); - this.expectKeyword('input'); - const name = this.parseName(); - const directives = this.parseConstDirectives(); - const fields = this.parseInputFieldsDefinition(); - return this.node(start, { - kind: _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION, - description, - name, - directives, - fields, - }); - } - /** - * ``` - * InputFieldsDefinition : { InputValueDefinition+ } - * ``` - */ + if (typeCondition) { + const type = (0, _typeFromAST.typeFromAST)( + context.getSchema(), + typeCondition, + ); - parseInputFieldsDefinition() { - return this.optionalMany( - _tokenKind.TokenKind.BRACE_L, - this.parseInputValueDef, - _tokenKind.TokenKind.BRACE_R, - ); - } - /** - * TypeSystemExtension : - * - SchemaExtension - * - TypeExtension - * - * TypeExtension : - * - ScalarTypeExtension - * - ObjectTypeExtension - * - InterfaceTypeExtension - * - UnionTypeExtension - * - EnumTypeExtension - * - InputObjectTypeDefinition - */ + if (type && !(0, _definition.isCompositeType)(type)) { + const typeStr = (0, _printer.print)(typeCondition); + context.reportError( + new _GraphQLError.GraphQLError( + `Fragment cannot condition on non composite type "${typeStr}".`, + { + nodes: typeCondition, + }, + ), + ); + } + } + }, - parseTypeSystemExtension() { - const keywordToken = this._lexer.lookahead(); + FragmentDefinition(node) { + const type = (0, _typeFromAST.typeFromAST)( + context.getSchema(), + node.typeCondition, + ); - if (keywordToken.kind === _tokenKind.TokenKind.NAME) { - switch (keywordToken.value) { - case 'schema': - return this.parseSchemaExtension(); + if (type && !(0, _definition.isCompositeType)(type)) { + const typeStr = (0, _printer.print)(node.typeCondition); + context.reportError( + new _GraphQLError.GraphQLError( + `Fragment "${node.name.value}" cannot condition on non composite type "${typeStr}".`, + { + nodes: node.typeCondition, + }, + ), + ); + } + }, + }; +} - case 'scalar': - return this.parseScalarTypeExtension(); - case 'type': - return this.parseObjectTypeExtension(); +/***/ }), - case 'interface': - return this.parseInterfaceTypeExtension(); +/***/ 67147: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - case 'union': - return this.parseUnionTypeExtension(); +"use strict"; - case 'enum': - return this.parseEnumTypeExtension(); - case 'input': - return this.parseInputObjectTypeExtension(); - } - } +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.KnownArgumentNamesOnDirectivesRule = KnownArgumentNamesOnDirectivesRule; +exports.KnownArgumentNamesRule = KnownArgumentNamesRule; - throw this.unexpected(keywordToken); - } - /** - * ``` - * SchemaExtension : - * - extend schema Directives[Const]? { OperationTypeDefinition+ } - * - extend schema Directives[Const] - * ``` - */ +var _didYouMean = __nccwpck_require__(42878); - parseSchemaExtension() { - const start = this._lexer.token; - this.expectKeyword('extend'); - this.expectKeyword('schema'); - const directives = this.parseConstDirectives(); - const operationTypes = this.optionalMany( - _tokenKind.TokenKind.BRACE_L, - this.parseOperationTypeDefinition, - _tokenKind.TokenKind.BRACE_R, - ); +var _suggestionList = __nccwpck_require__(57704); - if (directives.length === 0 && operationTypes.length === 0) { - throw this.unexpected(); - } +var _GraphQLError = __nccwpck_require__(4797); - return this.node(start, { - kind: _kinds.Kind.SCHEMA_EXTENSION, - directives, - operationTypes, - }); - } - /** - * ScalarTypeExtension : - * - extend scalar Name Directives[Const] - */ +var _kinds = __nccwpck_require__(11927); - parseScalarTypeExtension() { - const start = this._lexer.token; - this.expectKeyword('extend'); - this.expectKeyword('scalar'); - const name = this.parseName(); - const directives = this.parseConstDirectives(); +var _directives = __nccwpck_require__(83614); - if (directives.length === 0) { - throw this.unexpected(); - } +/** + * Known argument names + * + * A GraphQL field is only valid if all supplied arguments are defined by + * that field. + * + * See https://spec.graphql.org/draft/#sec-Argument-Names + * See https://spec.graphql.org/draft/#sec-Directives-Are-In-Valid-Locations + */ +function KnownArgumentNamesRule(context) { + return { + // eslint-disable-next-line new-cap + ...KnownArgumentNamesOnDirectivesRule(context), - return this.node(start, { - kind: _kinds.Kind.SCALAR_TYPE_EXTENSION, - name, - directives, - }); - } - /** - * ObjectTypeExtension : - * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition - * - extend type Name ImplementsInterfaces? Directives[Const] - * - extend type Name ImplementsInterfaces - */ + Argument(argNode) { + const argDef = context.getArgument(); + const fieldDef = context.getFieldDef(); + const parentType = context.getParentType(); - parseObjectTypeExtension() { - const start = this._lexer.token; - this.expectKeyword('extend'); - this.expectKeyword('type'); - const name = this.parseName(); - const interfaces = this.parseImplementsInterfaces(); - const directives = this.parseConstDirectives(); - const fields = this.parseFieldsDefinition(); + if (!argDef && fieldDef && parentType) { + const argName = argNode.name.value; + const knownArgsNames = fieldDef.args.map((arg) => arg.name); + const suggestions = (0, _suggestionList.suggestionList)( + argName, + knownArgsNames, + ); + context.reportError( + new _GraphQLError.GraphQLError( + `Unknown argument "${argName}" on field "${parentType.name}.${fieldDef.name}".` + + (0, _didYouMean.didYouMean)(suggestions), + { + nodes: argNode, + }, + ), + ); + } + }, + }; +} +/** + * @internal + */ - if ( - interfaces.length === 0 && - directives.length === 0 && - fields.length === 0 - ) { - throw this.unexpected(); - } +function KnownArgumentNamesOnDirectivesRule(context) { + const directiveArgs = Object.create(null); + const schema = context.getSchema(); + const definedDirectives = schema + ? schema.getDirectives() + : _directives.specifiedDirectives; - return this.node(start, { - kind: _kinds.Kind.OBJECT_TYPE_EXTENSION, - name, - interfaces, - directives, - fields, - }); + for (const directive of definedDirectives) { + directiveArgs[directive.name] = directive.args.map((arg) => arg.name); } - /** - * InterfaceTypeExtension : - * - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition - * - extend interface Name ImplementsInterfaces? Directives[Const] - * - extend interface Name ImplementsInterfaces - */ - parseInterfaceTypeExtension() { - const start = this._lexer.token; - this.expectKeyword('extend'); - this.expectKeyword('interface'); - const name = this.parseName(); - const interfaces = this.parseImplementsInterfaces(); - const directives = this.parseConstDirectives(); - const fields = this.parseFieldsDefinition(); + const astDefinitions = context.getDocument().definitions; - if ( - interfaces.length === 0 && - directives.length === 0 && - fields.length === 0 - ) { - throw this.unexpected(); - } + for (const def of astDefinitions) { + if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + var _def$arguments; - return this.node(start, { - kind: _kinds.Kind.INTERFACE_TYPE_EXTENSION, - name, - interfaces, - directives, - fields, - }); + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const argsNodes = + (_def$arguments = def.arguments) !== null && _def$arguments !== void 0 + ? _def$arguments + : []; + directiveArgs[def.name.value] = argsNodes.map((arg) => arg.name.value); + } } - /** - * UnionTypeExtension : - * - extend union Name Directives[Const]? UnionMemberTypes - * - extend union Name Directives[Const] - */ - parseUnionTypeExtension() { - const start = this._lexer.token; - this.expectKeyword('extend'); - this.expectKeyword('union'); - const name = this.parseName(); - const directives = this.parseConstDirectives(); - const types = this.parseUnionMemberTypes(); + return { + Directive(directiveNode) { + const directiveName = directiveNode.name.value; + const knownArgs = directiveArgs[directiveName]; - if (directives.length === 0 && types.length === 0) { - throw this.unexpected(); - } + if (directiveNode.arguments && knownArgs) { + for (const argNode of directiveNode.arguments) { + const argName = argNode.name.value; - return this.node(start, { - kind: _kinds.Kind.UNION_TYPE_EXTENSION, - name, - directives, - types, - }); - } - /** - * EnumTypeExtension : - * - extend enum Name Directives[Const]? EnumValuesDefinition - * - extend enum Name Directives[Const] - */ + if (!knownArgs.includes(argName)) { + const suggestions = (0, _suggestionList.suggestionList)( + argName, + knownArgs, + ); + context.reportError( + new _GraphQLError.GraphQLError( + `Unknown argument "${argName}" on directive "@${directiveName}".` + + (0, _didYouMean.didYouMean)(suggestions), + { + nodes: argNode, + }, + ), + ); + } + } + } - parseEnumTypeExtension() { - const start = this._lexer.token; - this.expectKeyword('extend'); - this.expectKeyword('enum'); - const name = this.parseName(); - const directives = this.parseConstDirectives(); - const values = this.parseEnumValuesDefinition(); + return false; + }, + }; +} - if (directives.length === 0 && values.length === 0) { - throw this.unexpected(); - } - return this.node(start, { - kind: _kinds.Kind.ENUM_TYPE_EXTENSION, - name, - directives, - values, - }); - } - /** - * InputObjectTypeExtension : - * - extend input Name Directives[Const]? InputFieldsDefinition - * - extend input Name Directives[Const] - */ +/***/ }), - parseInputObjectTypeExtension() { - const start = this._lexer.token; - this.expectKeyword('extend'); - this.expectKeyword('input'); - const name = this.parseName(); - const directives = this.parseConstDirectives(); - const fields = this.parseInputFieldsDefinition(); +/***/ 85303: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (directives.length === 0 && fields.length === 0) { - throw this.unexpected(); - } +"use strict"; - return this.node(start, { - kind: _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION, - name, - directives, - fields, - }); - } - /** - * ``` - * DirectiveDefinition : - * - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations - * ``` - */ - parseDirectiveDefinition() { - const start = this._lexer.token; - const description = this.parseDescription(); - this.expectKeyword('directive'); - this.expectToken(_tokenKind.TokenKind.AT); - const name = this.parseName(); - const args = this.parseArgumentDefs(); - const repeatable = this.expectOptionalKeyword('repeatable'); - this.expectKeyword('on'); - const locations = this.parseDirectiveLocations(); - return this.node(start, { - kind: _kinds.Kind.DIRECTIVE_DEFINITION, - description, - name, - arguments: args, - repeatable, - locations, - }); - } - /** - * DirectiveLocations : - * - `|`? DirectiveLocation - * - DirectiveLocations | DirectiveLocation - */ +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.KnownDirectivesRule = KnownDirectivesRule; - parseDirectiveLocations() { - return this.delimitedMany( - _tokenKind.TokenKind.PIPE, - this.parseDirectiveLocation, - ); - } - /* - * DirectiveLocation : - * - ExecutableDirectiveLocation - * - TypeSystemDirectiveLocation - * - * ExecutableDirectiveLocation : one of - * `QUERY` - * `MUTATION` - * `SUBSCRIPTION` - * `FIELD` - * `FRAGMENT_DEFINITION` - * `FRAGMENT_SPREAD` - * `INLINE_FRAGMENT` - * - * TypeSystemDirectiveLocation : one of - * `SCHEMA` - * `SCALAR` - * `OBJECT` - * `FIELD_DEFINITION` - * `ARGUMENT_DEFINITION` - * `INTERFACE` - * `UNION` - * `ENUM` - * `ENUM_VALUE` - * `INPUT_OBJECT` - * `INPUT_FIELD_DEFINITION` - */ +var _inspect = __nccwpck_require__(10102); - parseDirectiveLocation() { - const start = this._lexer.token; - const name = this.parseName(); +var _invariant = __nccwpck_require__(28847); - if ( - Object.prototype.hasOwnProperty.call( - _directiveLocation.DirectiveLocation, - name.value, - ) - ) { - return name; - } +var _GraphQLError = __nccwpck_require__(4797); - throw this.unexpected(start); - } // Core parsing utility functions +var _ast = __nccwpck_require__(45494); - /** - * Returns a node that, if configured to do so, sets a "loc" field as a - * location object, used to identify the place in the source that created a - * given parsed object. - */ +var _directiveLocation = __nccwpck_require__(71553); - node(startToken, node) { - if (this._options.noLocation !== true) { - node.loc = new _ast.Location( - startToken, - this._lexer.lastToken, - this._lexer.source, - ); - } +var _kinds = __nccwpck_require__(11927); - return node; - } - /** - * Determines if the next token is of a given kind - */ +var _directives = __nccwpck_require__(83614); - peek(kind) { - return this._lexer.token.kind === kind; +/** + * Known directives + * + * A GraphQL document is only valid if all `@directives` are known by the + * schema and legally positioned. + * + * See https://spec.graphql.org/draft/#sec-Directives-Are-Defined + */ +function KnownDirectivesRule(context) { + const locationsMap = Object.create(null); + const schema = context.getSchema(); + const definedDirectives = schema + ? schema.getDirectives() + : _directives.specifiedDirectives; + + for (const directive of definedDirectives) { + locationsMap[directive.name] = directive.locations; } - /** - * If the next token is of the given kind, return that token after advancing the lexer. - * Otherwise, do not change the parser state and throw an error. - */ - expectToken(kind) { - const token = this._lexer.token; + const astDefinitions = context.getDocument().definitions; - if (token.kind === kind) { - this.advanceLexer(); - return token; + for (const def of astDefinitions) { + if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + locationsMap[def.name.value] = def.locations.map((name) => name.value); } - - throw (0, _syntaxError.syntaxError)( - this._lexer.source, - token.start, - `Expected ${getTokenKindDesc(kind)}, found ${getTokenDesc(token)}.`, - ); } - /** - * If the next token is of the given kind, return "true" after advancing the lexer. - * Otherwise, do not change the parser state and return "false". - */ - expectOptionalToken(kind) { - const token = this._lexer.token; + return { + Directive(node, _key, _parent, _path, ancestors) { + const name = node.name.value; + const locations = locationsMap[name]; - if (token.kind === kind) { - this.advanceLexer(); - return true; - } + if (!locations) { + context.reportError( + new _GraphQLError.GraphQLError(`Unknown directive "@${name}".`, { + nodes: node, + }), + ); + return; + } - return false; - } - /** - * If the next token is a given keyword, advance the lexer. - * Otherwise, do not change the parser state and throw an error. - */ + const candidateLocation = getDirectiveLocationForASTPath(ancestors); - expectKeyword(value) { - const token = this._lexer.token; + if (candidateLocation && !locations.includes(candidateLocation)) { + context.reportError( + new _GraphQLError.GraphQLError( + `Directive "@${name}" may not be used on ${candidateLocation}.`, + { + nodes: node, + }, + ), + ); + } + }, + }; +} - if (token.kind === _tokenKind.TokenKind.NAME && token.value === value) { - this.advanceLexer(); - } else { - throw (0, _syntaxError.syntaxError)( - this._lexer.source, - token.start, - `Expected "${value}", found ${getTokenDesc(token)}.`, - ); - } - } - /** - * If the next token is a given keyword, return "true" after advancing the lexer. - * Otherwise, do not change the parser state and return "false". - */ +function getDirectiveLocationForASTPath(ancestors) { + const appliedTo = ancestors[ancestors.length - 1]; + 'kind' in appliedTo || (0, _invariant.invariant)(false); - expectOptionalKeyword(value) { - const token = this._lexer.token; + switch (appliedTo.kind) { + case _kinds.Kind.OPERATION_DEFINITION: + return getDirectiveLocationForOperation(appliedTo.operation); - if (token.kind === _tokenKind.TokenKind.NAME && token.value === value) { - this.advanceLexer(); - return true; - } + case _kinds.Kind.FIELD: + return _directiveLocation.DirectiveLocation.FIELD; - return false; - } - /** - * Helper function for creating an error when an unexpected lexed token is encountered. - */ + case _kinds.Kind.FRAGMENT_SPREAD: + return _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD; - unexpected(atToken) { - const token = - atToken !== null && atToken !== void 0 ? atToken : this._lexer.token; - return (0, _syntaxError.syntaxError)( - this._lexer.source, - token.start, - `Unexpected ${getTokenDesc(token)}.`, - ); - } - /** - * Returns a possibly empty list of parse nodes, determined by the parseFn. - * This list begins with a lex token of openKind and ends with a lex token of closeKind. - * Advances the parser to the next lex token after the closing token. - */ + case _kinds.Kind.INLINE_FRAGMENT: + return _directiveLocation.DirectiveLocation.INLINE_FRAGMENT; + + case _kinds.Kind.FRAGMENT_DEFINITION: + return _directiveLocation.DirectiveLocation.FRAGMENT_DEFINITION; + + case _kinds.Kind.VARIABLE_DEFINITION: + return _directiveLocation.DirectiveLocation.VARIABLE_DEFINITION; + + case _kinds.Kind.SCHEMA_DEFINITION: + case _kinds.Kind.SCHEMA_EXTENSION: + return _directiveLocation.DirectiveLocation.SCHEMA; + + case _kinds.Kind.SCALAR_TYPE_DEFINITION: + case _kinds.Kind.SCALAR_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.SCALAR; - any(openKind, parseFn, closeKind) { - this.expectToken(openKind); - const nodes = []; + case _kinds.Kind.OBJECT_TYPE_DEFINITION: + case _kinds.Kind.OBJECT_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.OBJECT; - while (!this.expectOptionalToken(closeKind)) { - nodes.push(parseFn.call(this)); - } + case _kinds.Kind.FIELD_DEFINITION: + return _directiveLocation.DirectiveLocation.FIELD_DEFINITION; - return nodes; - } - /** - * Returns a list of parse nodes, determined by the parseFn. - * It can be empty only if open token is missing otherwise it will always return non-empty list - * that begins with a lex token of openKind and ends with a lex token of closeKind. - * Advances the parser to the next lex token after the closing token. - */ + case _kinds.Kind.INTERFACE_TYPE_DEFINITION: + case _kinds.Kind.INTERFACE_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.INTERFACE; - optionalMany(openKind, parseFn, closeKind) { - if (this.expectOptionalToken(openKind)) { - const nodes = []; + case _kinds.Kind.UNION_TYPE_DEFINITION: + case _kinds.Kind.UNION_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.UNION; - do { - nodes.push(parseFn.call(this)); - } while (!this.expectOptionalToken(closeKind)); + case _kinds.Kind.ENUM_TYPE_DEFINITION: + case _kinds.Kind.ENUM_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.ENUM; - return nodes; - } + case _kinds.Kind.ENUM_VALUE_DEFINITION: + return _directiveLocation.DirectiveLocation.ENUM_VALUE; - return []; - } - /** - * Returns a non-empty list of parse nodes, determined by the parseFn. - * This list begins with a lex token of openKind and ends with a lex token of closeKind. - * Advances the parser to the next lex token after the closing token. - */ + case _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION: + case _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.INPUT_OBJECT; - many(openKind, parseFn, closeKind) { - this.expectToken(openKind); - const nodes = []; + case _kinds.Kind.INPUT_VALUE_DEFINITION: { + const parentNode = ancestors[ancestors.length - 3]; + 'kind' in parentNode || (0, _invariant.invariant)(false); + return parentNode.kind === _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION + ? _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION + : _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION; + } + // Not reachable, all possible types have been considered. - do { - nodes.push(parseFn.call(this)); - } while (!this.expectOptionalToken(closeKind)); + /* c8 ignore next */ - return nodes; + default: + false || + (0, _invariant.invariant)( + false, + 'Unexpected kind: ' + (0, _inspect.inspect)(appliedTo.kind), + ); } - /** - * Returns a non-empty list of parse nodes, determined by the parseFn. - * This list may begin with a lex token of delimiterKind followed by items separated by lex tokens of tokenKind. - * Advances the parser to the next lex token after last item in the list. - */ +} - delimitedMany(delimiterKind, parseFn) { - this.expectOptionalToken(delimiterKind); - const nodes = []; +function getDirectiveLocationForOperation(operation) { + switch (operation) { + case _ast.OperationTypeNode.QUERY: + return _directiveLocation.DirectiveLocation.QUERY; - do { - nodes.push(parseFn.call(this)); - } while (this.expectOptionalToken(delimiterKind)); + case _ast.OperationTypeNode.MUTATION: + return _directiveLocation.DirectiveLocation.MUTATION; - return nodes; + case _ast.OperationTypeNode.SUBSCRIPTION: + return _directiveLocation.DirectiveLocation.SUBSCRIPTION; } +} - advanceLexer() { - const { maxTokens } = this._options; - const token = this._lexer.advance(); +/***/ }), - if (token.kind !== _tokenKind.TokenKind.EOF) { - ++this._tokenCounter; +/***/ 15166: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (maxTokens !== undefined && this._tokenCounter > maxTokens) { - throw (0, _syntaxError.syntaxError)( - this._lexer.source, - token.start, - `Document contains more that ${maxTokens} tokens. Parsing aborted.`, - ); - } - } - } -} -/** - * A helper function to describe a token as a string for debugging. - */ +"use strict"; -exports.Parser = Parser; -function getTokenDesc(token) { - const value = token.value; - return getTokenKindDesc(token.kind) + (value != null ? ` "${value}"` : ''); -} +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.KnownFragmentNamesRule = KnownFragmentNamesRule; + +var _GraphQLError = __nccwpck_require__(4797); + /** - * A helper function to describe a token kind as a string for debugging. + * Known fragment names + * + * A GraphQL document is only valid if all `...Fragment` fragment spreads refer + * to fragments defined in the same document. + * + * See https://spec.graphql.org/draft/#sec-Fragment-spread-target-defined */ +function KnownFragmentNamesRule(context) { + return { + FragmentSpread(node) { + const fragmentName = node.name.value; + const fragment = context.getFragment(fragmentName); -function getTokenKindDesc(kind) { - return (0, _lexer.isPunctuatorTokenKind)(kind) ? `"${kind}"` : kind; + if (!fragment) { + context.reportError( + new _GraphQLError.GraphQLError( + `Unknown fragment "${fragmentName}".`, + { + nodes: node.name, + }, + ), + ); + } + }, + }; } /***/ }), -/***/ 20535: +/***/ 42509: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -284001,115 +286404,95 @@ function getTokenKindDesc(kind) { Object.defineProperty(exports, "__esModule", ({ value: true, })); -exports.isConstValueNode = isConstValueNode; -exports.isDefinitionNode = isDefinitionNode; -exports.isExecutableDefinitionNode = isExecutableDefinitionNode; -exports.isSelectionNode = isSelectionNode; -exports.isTypeDefinitionNode = isTypeDefinitionNode; -exports.isTypeExtensionNode = isTypeExtensionNode; -exports.isTypeNode = isTypeNode; -exports.isTypeSystemDefinitionNode = isTypeSystemDefinitionNode; -exports.isTypeSystemExtensionNode = isTypeSystemExtensionNode; -exports.isValueNode = isValueNode; +exports.KnownTypeNamesRule = KnownTypeNamesRule; -var _kinds = __nccwpck_require__(11927); +var _didYouMean = __nccwpck_require__(42878); -function isDefinitionNode(node) { - return ( - isExecutableDefinitionNode(node) || - isTypeSystemDefinitionNode(node) || - isTypeSystemExtensionNode(node) - ); -} +var _suggestionList = __nccwpck_require__(57704); -function isExecutableDefinitionNode(node) { - return ( - node.kind === _kinds.Kind.OPERATION_DEFINITION || - node.kind === _kinds.Kind.FRAGMENT_DEFINITION - ); -} +var _GraphQLError = __nccwpck_require__(4797); -function isSelectionNode(node) { - return ( - node.kind === _kinds.Kind.FIELD || - node.kind === _kinds.Kind.FRAGMENT_SPREAD || - node.kind === _kinds.Kind.INLINE_FRAGMENT - ); -} +var _predicates = __nccwpck_require__(20535); -function isValueNode(node) { - return ( - node.kind === _kinds.Kind.VARIABLE || - node.kind === _kinds.Kind.INT || - node.kind === _kinds.Kind.FLOAT || - node.kind === _kinds.Kind.STRING || - node.kind === _kinds.Kind.BOOLEAN || - node.kind === _kinds.Kind.NULL || - node.kind === _kinds.Kind.ENUM || - node.kind === _kinds.Kind.LIST || - node.kind === _kinds.Kind.OBJECT - ); -} +var _introspection = __nccwpck_require__(28344); -function isConstValueNode(node) { - return ( - isValueNode(node) && - (node.kind === _kinds.Kind.LIST - ? node.values.some(isConstValueNode) - : node.kind === _kinds.Kind.OBJECT - ? node.fields.some((field) => isConstValueNode(field.value)) - : node.kind !== _kinds.Kind.VARIABLE) - ); -} +var _scalars = __nccwpck_require__(93145); -function isTypeNode(node) { - return ( - node.kind === _kinds.Kind.NAMED_TYPE || - node.kind === _kinds.Kind.LIST_TYPE || - node.kind === _kinds.Kind.NON_NULL_TYPE - ); -} +/** + * Known type names + * + * A GraphQL document is only valid if referenced types (specifically + * variable definitions and fragment conditions) are defined by the type schema. + * + * See https://spec.graphql.org/draft/#sec-Fragment-Spread-Type-Existence + */ +function KnownTypeNamesRule(context) { + const schema = context.getSchema(); + const existingTypesMap = schema ? schema.getTypeMap() : Object.create(null); + const definedTypes = Object.create(null); -function isTypeSystemDefinitionNode(node) { - return ( - node.kind === _kinds.Kind.SCHEMA_DEFINITION || - isTypeDefinitionNode(node) || - node.kind === _kinds.Kind.DIRECTIVE_DEFINITION - ); -} + for (const def of context.getDocument().definitions) { + if ((0, _predicates.isTypeDefinitionNode)(def)) { + definedTypes[def.name.value] = true; + } + } -function isTypeDefinitionNode(node) { - return ( - node.kind === _kinds.Kind.SCALAR_TYPE_DEFINITION || - node.kind === _kinds.Kind.OBJECT_TYPE_DEFINITION || - node.kind === _kinds.Kind.INTERFACE_TYPE_DEFINITION || - node.kind === _kinds.Kind.UNION_TYPE_DEFINITION || - node.kind === _kinds.Kind.ENUM_TYPE_DEFINITION || - node.kind === _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION - ); -} + const typeNames = [ + ...Object.keys(existingTypesMap), + ...Object.keys(definedTypes), + ]; + return { + NamedType(node, _1, parent, _2, ancestors) { + const typeName = node.name.value; -function isTypeSystemExtensionNode(node) { - return ( - node.kind === _kinds.Kind.SCHEMA_EXTENSION || isTypeExtensionNode(node) - ); + if (!existingTypesMap[typeName] && !definedTypes[typeName]) { + var _ancestors$; + + const definitionNode = + (_ancestors$ = ancestors[2]) !== null && _ancestors$ !== void 0 + ? _ancestors$ + : parent; + const isSDL = definitionNode != null && isSDLNode(definitionNode); + + if (isSDL && standardTypeNames.includes(typeName)) { + return; + } + + const suggestedTypes = (0, _suggestionList.suggestionList)( + typeName, + isSDL ? standardTypeNames.concat(typeNames) : typeNames, + ); + context.reportError( + new _GraphQLError.GraphQLError( + `Unknown type "${typeName}".` + + (0, _didYouMean.didYouMean)(suggestedTypes), + { + nodes: node, + }, + ), + ); + } + }, + }; } -function isTypeExtensionNode(node) { +const standardTypeNames = [ + ..._scalars.specifiedScalarTypes, + ..._introspection.introspectionTypes, +].map((type) => type.name); + +function isSDLNode(value) { return ( - node.kind === _kinds.Kind.SCALAR_TYPE_EXTENSION || - node.kind === _kinds.Kind.OBJECT_TYPE_EXTENSION || - node.kind === _kinds.Kind.INTERFACE_TYPE_EXTENSION || - node.kind === _kinds.Kind.UNION_TYPE_EXTENSION || - node.kind === _kinds.Kind.ENUM_TYPE_EXTENSION || - node.kind === _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION + 'kind' in value && + ((0, _predicates.isTypeSystemDefinitionNode)(value) || + (0, _predicates.isTypeSystemExtensionNode)(value)) ); } /***/ }), -/***/ 35250: +/***/ 45726: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -284118,81 +286501,49 @@ function isTypeExtensionNode(node) { Object.defineProperty(exports, "__esModule", ({ value: true, })); -exports.printLocation = printLocation; -exports.printSourceLocation = printSourceLocation; +exports.LoneAnonymousOperationRule = LoneAnonymousOperationRule; -var _location = __nccwpck_require__(61922); +var _GraphQLError = __nccwpck_require__(4797); + +var _kinds = __nccwpck_require__(11927); /** - * Render a helpful description of the location in the GraphQL Source document. - */ -function printLocation(location) { - return printSourceLocation( - location.source, - (0, _location.getLocation)(location.source, location.start), - ); -} -/** - * Render a helpful description of the location in the GraphQL Source document. + * Lone anonymous operation + * + * A GraphQL document is only valid if when it contains an anonymous operation + * (the query short-hand) that it contains only that one operation definition. + * + * See https://spec.graphql.org/draft/#sec-Lone-Anonymous-Operation */ +function LoneAnonymousOperationRule(context) { + let operationCount = 0; + return { + Document(node) { + operationCount = node.definitions.filter( + (definition) => definition.kind === _kinds.Kind.OPERATION_DEFINITION, + ).length; + }, -function printSourceLocation(source, sourceLocation) { - const firstLineColumnOffset = source.locationOffset.column - 1; - const body = ''.padStart(firstLineColumnOffset) + source.body; - const lineIndex = sourceLocation.line - 1; - const lineOffset = source.locationOffset.line - 1; - const lineNum = sourceLocation.line + lineOffset; - const columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0; - const columnNum = sourceLocation.column + columnOffset; - const locationStr = `${source.name}:${lineNum}:${columnNum}\n`; - const lines = body.split(/\r\n|[\n\r]/g); - const locationLine = lines[lineIndex]; // Special case for minified documents - - if (locationLine.length > 120) { - const subLineIndex = Math.floor(columnNum / 80); - const subLineColumnNum = columnNum % 80; - const subLines = []; - - for (let i = 0; i < locationLine.length; i += 80) { - subLines.push(locationLine.slice(i, i + 80)); - } - - return ( - locationStr + - printPrefixedLines([ - [`${lineNum} |`, subLines[0]], - ...subLines.slice(1, subLineIndex + 1).map((subLine) => ['|', subLine]), - ['|', '^'.padStart(subLineColumnNum)], - ['|', subLines[subLineIndex + 1]], - ]) - ); - } - - return ( - locationStr + - printPrefixedLines([ - // Lines specified like this: ["prefix", "string"], - [`${lineNum - 1} |`, lines[lineIndex - 1]], - [`${lineNum} |`, locationLine], - ['|', '^'.padStart(columnNum)], - [`${lineNum + 1} |`, lines[lineIndex + 1]], - ]) - ); -} - -function printPrefixedLines(lines) { - const existingLines = lines.filter(([_, line]) => line !== undefined); - const padLen = Math.max(...existingLines.map(([prefix]) => prefix.length)); - return existingLines - .map(([prefix, line]) => prefix.padStart(padLen) + (line ? ' ' + line : '')) - .join('\n'); + OperationDefinition(node) { + if (!node.name && operationCount > 1) { + context.reportError( + new _GraphQLError.GraphQLError( + 'This anonymous operation must be the only defined operation.', + { + nodes: node, + }, + ), + ); + } + }, + }; } /***/ }), -/***/ 86011: -/***/ ((__unused_webpack_module, exports) => { +/***/ 48307: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -284200,189 +286551,73 @@ function printPrefixedLines(lines) { Object.defineProperty(exports, "__esModule", ({ value: true, })); -exports.printString = printString; +exports.LoneSchemaDefinitionRule = LoneSchemaDefinitionRule; + +var _GraphQLError = __nccwpck_require__(4797); /** - * Prints a string as a GraphQL StringValue literal. Replaces control characters - * and excluded characters (" U+0022 and \\ U+005C) with escape sequences. + * Lone Schema definition + * + * A GraphQL document is only valid if it contains only one schema definition. */ -function printString(str) { - return `"${str.replace(escapedRegExp, escapedReplacer)}"`; -} // eslint-disable-next-line no-control-regex +function LoneSchemaDefinitionRule(context) { + var _ref, _ref2, _oldSchema$astNode; -const escapedRegExp = /[\x00-\x1f\x22\x5c\x7f-\x9f]/g; + const oldSchema = context.getSchema(); + const alreadyDefined = + (_ref = + (_ref2 = + (_oldSchema$astNode = + oldSchema === null || oldSchema === void 0 + ? void 0 + : oldSchema.astNode) !== null && _oldSchema$astNode !== void 0 + ? _oldSchema$astNode + : oldSchema === null || oldSchema === void 0 + ? void 0 + : oldSchema.getQueryType()) !== null && _ref2 !== void 0 + ? _ref2 + : oldSchema === null || oldSchema === void 0 + ? void 0 + : oldSchema.getMutationType()) !== null && _ref !== void 0 + ? _ref + : oldSchema === null || oldSchema === void 0 + ? void 0 + : oldSchema.getSubscriptionType(); + let schemaDefinitionsCount = 0; + return { + SchemaDefinition(node) { + if (alreadyDefined) { + context.reportError( + new _GraphQLError.GraphQLError( + 'Cannot define a new schema within a schema extension.', + { + nodes: node, + }, + ), + ); + return; + } -function escapedReplacer(str) { - return escapeSequences[str.charCodeAt(0)]; -} // prettier-ignore + if (schemaDefinitionsCount > 0) { + context.reportError( + new _GraphQLError.GraphQLError( + 'Must provide only one schema definition.', + { + nodes: node, + }, + ), + ); + } -const escapeSequences = [ - '\\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', - '', - '', - '\\"', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', // 2F - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', // 3F - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', // 4F - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '\\\\', - '', - '', - '', // 5F - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', // 6F - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '', - '\\u007F', - '\\u0080', - '\\u0081', - '\\u0082', - '\\u0083', - '\\u0084', - '\\u0085', - '\\u0086', - '\\u0087', - '\\u0088', - '\\u0089', - '\\u008A', - '\\u008B', - '\\u008C', - '\\u008D', - '\\u008E', - '\\u008F', - '\\u0090', - '\\u0091', - '\\u0092', - '\\u0093', - '\\u0094', - '\\u0095', - '\\u0096', - '\\u0097', - '\\u0098', - '\\u0099', - '\\u009A', - '\\u009B', - '\\u009C', - '\\u009D', - '\\u009E', - '\\u009F', -]; + ++schemaDefinitionsCount; + }, + }; +} /***/ }), -/***/ 68203: +/***/ 53318: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -284391,357 +286626,189 @@ const escapeSequences = [ Object.defineProperty(exports, "__esModule", ({ value: true, })); -exports.print = print; +exports.MaxIntrospectionDepthRule = MaxIntrospectionDepthRule; -var _blockString = __nccwpck_require__(52671); +var _GraphQLError = __nccwpck_require__(4797); -var _printString = __nccwpck_require__(86011); +var _kinds = __nccwpck_require__(11927); -var _visitor = __nccwpck_require__(5678); +const MAX_LISTS_DEPTH = 3; -/** - * Converts an AST into a string, using one set of reasonable - * formatting rules. - */ -function print(ast) { - return (0, _visitor.visit)(ast, printDocASTReducer); -} +function MaxIntrospectionDepthRule(context) { + /** + * Counts the depth of list fields in "__Type" recursively and + * returns `true` if the limit has been reached. + */ + function checkDepth(node, visitedFragments = Object.create(null), depth = 0) { + if (node.kind === _kinds.Kind.FRAGMENT_SPREAD) { + const fragmentName = node.name.value; -const MAX_LINE_LENGTH = 80; -const printDocASTReducer = { - Name: { - leave: (node) => node.value, - }, - Variable: { - leave: (node) => '$' + node.name, - }, - // Document - Document: { - leave: (node) => join(node.definitions, '\n\n'), - }, - OperationDefinition: { - leave(node) { - const varDefs = wrap('(', join(node.variableDefinitions, ', '), ')'); - const prefix = join( - [ - node.operation, - join([node.name, varDefs]), - join(node.directives, ' '), - ], - ' ', - ); // Anonymous queries with no directives or variable definitions can use - // the query short form. + if (visitedFragments[fragmentName] === true) { + // Fragment cycles are handled by `NoFragmentCyclesRule`. + return false; + } - return (prefix === 'query' ? '' : prefix + ' ') + node.selectionSet; - }, - }, - VariableDefinition: { - leave: ({ variable, type, defaultValue, directives }) => - variable + - ': ' + - type + - wrap(' = ', defaultValue) + - wrap(' ', join(directives, ' ')), - }, - SelectionSet: { - leave: ({ selections }) => block(selections), - }, - Field: { - leave({ alias, name, arguments: args, directives, selectionSet }) { - const prefix = wrap('', alias, ': ') + name; - let argsLine = prefix + wrap('(', join(args, ', '), ')'); + const fragment = context.getFragment(fragmentName); - if (argsLine.length > MAX_LINE_LENGTH) { - argsLine = prefix + wrap('(\n', indent(join(args, '\n')), '\n)'); + if (!fragment) { + // Missing fragments checks are handled by `KnownFragmentNamesRule`. + return false; + } // Rather than following an immutable programming pattern which has + // significant memory and garbage collection overhead, we've opted to + // take a mutable approach for efficiency's sake. Importantly visiting a + // fragment twice is fine, so long as you don't do one visit inside the + // other. + + try { + visitedFragments[fragmentName] = true; + return checkDepth(fragment, visitedFragments, depth); + } finally { + visitedFragments[fragmentName] = undefined; } + } - return join([argsLine, join(directives, ' '), selectionSet], ' '); + if ( + node.kind === _kinds.Kind.FIELD && // check all introspection lists + (node.name.value === 'fields' || + node.name.value === 'interfaces' || + node.name.value === 'possibleTypes' || + node.name.value === 'inputFields') + ) { + // eslint-disable-next-line no-param-reassign + depth++; + + if (depth >= MAX_LISTS_DEPTH) { + return true; + } + } // handles fields and inline fragments + + if ('selectionSet' in node && node.selectionSet) { + for (const child of node.selectionSet.selections) { + if (checkDepth(child, visitedFragments, depth)) { + return true; + } + } + } + + return false; + } + + return { + Field(node) { + if (node.name.value === '__schema' || node.name.value === '__type') { + if (checkDepth(node)) { + context.reportError( + new _GraphQLError.GraphQLError( + 'Maximum introspection depth exceeded', + { + nodes: [node], + }, + ), + ); + return false; + } + } }, - }, - Argument: { - leave: ({ name, value }) => name + ': ' + value, - }, - // Fragments - FragmentSpread: { - leave: ({ name, directives }) => - '...' + name + wrap(' ', join(directives, ' ')), - }, - InlineFragment: { - leave: ({ typeCondition, directives, selectionSet }) => - join( - [ - '...', - wrap('on ', typeCondition), - join(directives, ' '), - selectionSet, - ], - ' ', - ), - }, - FragmentDefinition: { - leave: ( - { name, typeCondition, variableDefinitions, directives, selectionSet }, // Note: fragment variable definitions are experimental and may be changed - ) => - // or removed in the future. - `fragment ${name}${wrap('(', join(variableDefinitions, ', '), ')')} ` + - `on ${typeCondition} ${wrap('', join(directives, ' '), ' ')}` + - selectionSet, - }, - // Value - IntValue: { - leave: ({ value }) => value, - }, - FloatValue: { - leave: ({ value }) => value, - }, - StringValue: { - leave: ({ value, block: isBlockString }) => - isBlockString - ? (0, _blockString.printBlockString)(value) - : (0, _printString.printString)(value), - }, - BooleanValue: { - leave: ({ value }) => (value ? 'true' : 'false'), - }, - NullValue: { - leave: () => 'null', - }, - EnumValue: { - leave: ({ value }) => value, - }, - ListValue: { - leave: ({ values }) => '[' + join(values, ', ') + ']', - }, - ObjectValue: { - leave: ({ fields }) => '{' + join(fields, ', ') + '}', - }, - ObjectField: { - leave: ({ name, value }) => name + ': ' + value, - }, - // Directive - Directive: { - leave: ({ name, arguments: args }) => - '@' + name + wrap('(', join(args, ', '), ')'), - }, - // Type - NamedType: { - leave: ({ name }) => name, - }, - ListType: { - leave: ({ type }) => '[' + type + ']', - }, - NonNullType: { - leave: ({ type }) => type + '!', - }, - // Type System Definitions - SchemaDefinition: { - leave: ({ description, directives, operationTypes }) => - wrap('', description, '\n') + - join(['schema', join(directives, ' '), block(operationTypes)], ' '), - }, - OperationTypeDefinition: { - leave: ({ operation, type }) => operation + ': ' + type, - }, - ScalarTypeDefinition: { - leave: ({ description, name, directives }) => - wrap('', description, '\n') + - join(['scalar', name, join(directives, ' ')], ' '), - }, - ObjectTypeDefinition: { - leave: ({ description, name, interfaces, directives, fields }) => - wrap('', description, '\n') + - join( - [ - 'type', - name, - wrap('implements ', join(interfaces, ' & ')), - join(directives, ' '), - block(fields), - ], - ' ', - ), - }, - FieldDefinition: { - leave: ({ description, name, arguments: args, type, directives }) => - wrap('', description, '\n') + - name + - (hasMultilineItems(args) - ? wrap('(\n', indent(join(args, '\n')), '\n)') - : wrap('(', join(args, ', '), ')')) + - ': ' + - type + - wrap(' ', join(directives, ' ')), - }, - InputValueDefinition: { - leave: ({ description, name, type, defaultValue, directives }) => - wrap('', description, '\n') + - join( - [name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')], - ' ', - ), - }, - InterfaceTypeDefinition: { - leave: ({ description, name, interfaces, directives, fields }) => - wrap('', description, '\n') + - join( - [ - 'interface', - name, - wrap('implements ', join(interfaces, ' & ')), - join(directives, ' '), - block(fields), - ], - ' ', - ), - }, - UnionTypeDefinition: { - leave: ({ description, name, directives, types }) => - wrap('', description, '\n') + - join( - ['union', name, join(directives, ' '), wrap('= ', join(types, ' | '))], - ' ', - ), - }, - EnumTypeDefinition: { - leave: ({ description, name, directives, values }) => - wrap('', description, '\n') + - join(['enum', name, join(directives, ' '), block(values)], ' '), - }, - EnumValueDefinition: { - leave: ({ description, name, directives }) => - wrap('', description, '\n') + join([name, join(directives, ' ')], ' '), - }, - InputObjectTypeDefinition: { - leave: ({ description, name, directives, fields }) => - wrap('', description, '\n') + - join(['input', name, join(directives, ' '), block(fields)], ' '), - }, - DirectiveDefinition: { - leave: ({ description, name, arguments: args, repeatable, locations }) => - wrap('', description, '\n') + - 'directive @' + - name + - (hasMultilineItems(args) - ? wrap('(\n', indent(join(args, '\n')), '\n)') - : wrap('(', join(args, ', '), ')')) + - (repeatable ? ' repeatable' : '') + - ' on ' + - join(locations, ' | '), - }, - SchemaExtension: { - leave: ({ directives, operationTypes }) => - join( - ['extend schema', join(directives, ' '), block(operationTypes)], - ' ', - ), - }, - ScalarTypeExtension: { - leave: ({ name, directives }) => - join(['extend scalar', name, join(directives, ' ')], ' '), - }, - ObjectTypeExtension: { - leave: ({ name, interfaces, directives, fields }) => - join( - [ - 'extend type', - name, - wrap('implements ', join(interfaces, ' & ')), - join(directives, ' '), - block(fields), - ], - ' ', - ), - }, - InterfaceTypeExtension: { - leave: ({ name, interfaces, directives, fields }) => - join( - [ - 'extend interface', - name, - wrap('implements ', join(interfaces, ' & ')), - join(directives, ' '), - block(fields), - ], - ' ', - ), - }, - UnionTypeExtension: { - leave: ({ name, directives, types }) => - join( - [ - 'extend union', - name, - join(directives, ' '), - wrap('= ', join(types, ' | ')), - ], - ' ', - ), - }, - EnumTypeExtension: { - leave: ({ name, directives, values }) => - join(['extend enum', name, join(directives, ' '), block(values)], ' '), - }, - InputObjectTypeExtension: { - leave: ({ name, directives, fields }) => - join(['extend input', name, join(directives, ' '), block(fields)], ' '), - }, -}; -/** - * Given maybeArray, print an empty string if it is null or empty, otherwise - * print all items together separated by separator if provided - */ + }; +} -function join(maybeArray, separator = '') { - var _maybeArray$filter$jo; - return (_maybeArray$filter$jo = - maybeArray === null || maybeArray === void 0 - ? void 0 - : maybeArray.filter((x) => x).join(separator)) !== null && - _maybeArray$filter$jo !== void 0 - ? _maybeArray$filter$jo - : ''; -} +/***/ }), + +/***/ 62564: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.NoFragmentCyclesRule = NoFragmentCyclesRule; + +var _GraphQLError = __nccwpck_require__(4797); + /** - * Given array, print each item on its own line, wrapped in an indented `{ }` block. + * No fragment cycles + * + * The graph of fragment spreads must not form any cycles including spreading itself. + * Otherwise an operation could infinitely spread or infinitely execute on cycles in the underlying data. + * + * See https://spec.graphql.org/draft/#sec-Fragment-spreads-must-not-form-cycles */ +function NoFragmentCyclesRule(context) { + // Tracks already visited fragments to maintain O(N) and to ensure that cycles + // are not redundantly reported. + const visitedFrags = Object.create(null); // Array of AST nodes used to produce meaningful errors -function block(array) { - return wrap('{\n', indent(join(array, '\n')), '\n}'); -} -/** - * If maybeString is not null or empty, then wrap with start and end, otherwise print an empty string. - */ + const spreadPath = []; // Position in the spread path -function wrap(start, maybeString, end = '') { - return maybeString != null && maybeString !== '' - ? start + maybeString + end - : ''; -} + const spreadPathIndexByName = Object.create(null); + return { + OperationDefinition: () => false, -function indent(str) { - return wrap(' ', str.replace(/\n/g, '\n ')); -} + FragmentDefinition(node) { + detectCycleRecursive(node); + return false; + }, + }; // This does a straight-forward DFS to find cycles. + // It does not terminate when a cycle was found but continues to explore + // the graph to find all possible cycles. -function hasMultilineItems(maybeArray) { - var _maybeArray$some; + function detectCycleRecursive(fragment) { + if (visitedFrags[fragment.name.value]) { + return; + } - // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const fragmentName = fragment.name.value; + visitedFrags[fragmentName] = true; + const spreadNodes = context.getFragmentSpreads(fragment.selectionSet); - /* c8 ignore next */ - return (_maybeArray$some = - maybeArray === null || maybeArray === void 0 - ? void 0 - : maybeArray.some((str) => str.includes('\n'))) !== null && - _maybeArray$some !== void 0 - ? _maybeArray$some - : false; + if (spreadNodes.length === 0) { + return; + } + + spreadPathIndexByName[fragmentName] = spreadPath.length; + + for (const spreadNode of spreadNodes) { + const spreadName = spreadNode.name.value; + const cycleIndex = spreadPathIndexByName[spreadName]; + spreadPath.push(spreadNode); + + if (cycleIndex === undefined) { + const spreadFragment = context.getFragment(spreadName); + + if (spreadFragment) { + detectCycleRecursive(spreadFragment); + } + } else { + const cyclePath = spreadPath.slice(cycleIndex); + const viaPath = cyclePath + .slice(0, -1) + .map((s) => '"' + s.name.value + '"') + .join(', '); + context.reportError( + new _GraphQLError.GraphQLError( + `Cannot spread fragment "${spreadName}" within itself` + + (viaPath !== '' ? ` via ${viaPath}.` : '.'), + { + nodes: cyclePath, + }, + ), + ); + } + + spreadPath.pop(); + } + + spreadPathIndexByName[fragmentName] = undefined; + } } /***/ }), -/***/ 65521: +/***/ 61671: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -284750,72 +286817,59 @@ function hasMultilineItems(maybeArray) { Object.defineProperty(exports, "__esModule", ({ value: true, })); -exports.Source = void 0; -exports.isSource = isSource; - -var _devAssert = __nccwpck_require__(46514); - -var _inspect = __nccwpck_require__(10102); - -var _instanceOf = __nccwpck_require__(93481); +exports.NoUndefinedVariablesRule = NoUndefinedVariablesRule; -/** - * A representation of source input to GraphQL. The `name` and `locationOffset` parameters are - * optional, but they are useful for clients who store GraphQL documents in source files. - * For example, if the GraphQL input starts at line 40 in a file named `Foo.graphql`, it might - * be useful for `name` to be `"Foo.graphql"` and location to be `{ line: 40, column: 1 }`. - * The `line` and `column` properties in `locationOffset` are 1-indexed. - */ -class Source { - constructor( - body, - name = 'GraphQL request', - locationOffset = { - line: 1, - column: 1, - }, - ) { - typeof body === 'string' || - (0, _devAssert.devAssert)( - false, - `Body must be a string. Received: ${(0, _inspect.inspect)(body)}.`, - ); - this.body = body; - this.name = name; - this.locationOffset = locationOffset; - this.locationOffset.line > 0 || - (0, _devAssert.devAssert)( - false, - 'line in locationOffset is 1-indexed and must be positive.', - ); - this.locationOffset.column > 0 || - (0, _devAssert.devAssert)( - false, - 'column in locationOffset is 1-indexed and must be positive.', - ); - } +var _GraphQLError = __nccwpck_require__(4797); - get [Symbol.toStringTag]() { - return 'Source'; - } -} /** - * Test if the given value is a Source object. + * No undefined variables * - * @internal + * A GraphQL operation is only valid if all variables encountered, both directly + * and via fragment spreads, are defined by that operation. + * + * See https://spec.graphql.org/draft/#sec-All-Variable-Uses-Defined */ +function NoUndefinedVariablesRule(context) { + let variableNameDefined = Object.create(null); + return { + OperationDefinition: { + enter() { + variableNameDefined = Object.create(null); + }, -exports.Source = Source; + leave(operation) { + const usages = context.getRecursiveVariableUsages(operation); -function isSource(source) { - return (0, _instanceOf.instanceOf)(source, Source); + for (const { node } of usages) { + const varName = node.name.value; + + if (variableNameDefined[varName] !== true) { + context.reportError( + new _GraphQLError.GraphQLError( + operation.name + ? `Variable "$${varName}" is not defined by operation "${operation.name.value}".` + : `Variable "$${varName}" is not defined.`, + { + nodes: [node, operation], + }, + ), + ); + } + } + }, + }, + + VariableDefinition(node) { + variableNameDefined[node.variable.name.value] = true; + }, + }; } /***/ }), -/***/ 91565: -/***/ ((__unused_webpack_module, exports) => { +/***/ 192: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -284823,49 +286877,67 @@ function isSource(source) { Object.defineProperty(exports, "__esModule", ({ value: true, })); -exports.TokenKind = void 0; +exports.NoUnusedFragmentsRule = NoUnusedFragmentsRule; -/** - * An exported enum describing the different kinds of tokens that the - * lexer emits. - */ -var TokenKind; -exports.TokenKind = TokenKind; +var _GraphQLError = __nccwpck_require__(4797); -(function (TokenKind) { - TokenKind['SOF'] = ''; - TokenKind['EOF'] = ''; - TokenKind['BANG'] = '!'; - TokenKind['DOLLAR'] = '$'; - TokenKind['AMP'] = '&'; - TokenKind['PAREN_L'] = '('; - TokenKind['PAREN_R'] = ')'; - TokenKind['SPREAD'] = '...'; - TokenKind['COLON'] = ':'; - TokenKind['EQUALS'] = '='; - TokenKind['AT'] = '@'; - TokenKind['BRACKET_L'] = '['; - TokenKind['BRACKET_R'] = ']'; - TokenKind['BRACE_L'] = '{'; - TokenKind['PIPE'] = '|'; - TokenKind['BRACE_R'] = '}'; - TokenKind['NAME'] = 'Name'; - TokenKind['INT'] = 'Int'; - TokenKind['FLOAT'] = 'Float'; - TokenKind['STRING'] = 'String'; - TokenKind['BLOCK_STRING'] = 'BlockString'; - TokenKind['COMMENT'] = 'Comment'; -})(TokenKind || (exports.TokenKind = TokenKind = {})); /** - * The enum type representing the token kinds values. + * No unused fragments * - * @deprecated Please use `TokenKind`. Will be remove in v17. + * A GraphQL document is only valid if all fragment definitions are spread + * within operations, or spread within other fragments spread within operations. + * + * See https://spec.graphql.org/draft/#sec-Fragments-Must-Be-Used */ +function NoUnusedFragmentsRule(context) { + const operationDefs = []; + const fragmentDefs = []; + return { + OperationDefinition(node) { + operationDefs.push(node); + return false; + }, + + FragmentDefinition(node) { + fragmentDefs.push(node); + return false; + }, + + Document: { + leave() { + const fragmentNameUsed = Object.create(null); + + for (const operation of operationDefs) { + for (const fragment of context.getRecursivelyReferencedFragments( + operation, + )) { + fragmentNameUsed[fragment.name.value] = true; + } + } + + for (const fragmentDef of fragmentDefs) { + const fragName = fragmentDef.name.value; + + if (fragmentNameUsed[fragName] !== true) { + context.reportError( + new _GraphQLError.GraphQLError( + `Fragment "${fragName}" is never used.`, + { + nodes: fragmentDef, + }, + ), + ); + } + } + }, + }, + }; +} /***/ }), -/***/ 5678: +/***/ 40242: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -284874,1817 +286946,1659 @@ exports.TokenKind = TokenKind; Object.defineProperty(exports, "__esModule", ({ value: true, })); -exports.BREAK = void 0; -exports.getEnterLeaveForKind = getEnterLeaveForKind; -exports.getVisitFn = getVisitFn; -exports.visit = visit; -exports.visitInParallel = visitInParallel; - -var _devAssert = __nccwpck_require__(46514); - -var _inspect = __nccwpck_require__(10102); - -var _ast = __nccwpck_require__(45494); +exports.NoUnusedVariablesRule = NoUnusedVariablesRule; -var _kinds = __nccwpck_require__(11927); +var _GraphQLError = __nccwpck_require__(4797); -const BREAK = Object.freeze({}); /** - * visit() will walk through an AST using a depth-first traversal, calling - * the visitor's enter function at each node in the traversal, and calling the - * leave function after visiting that node and all of its child nodes. - * - * By returning different values from the enter and leave functions, the - * behavior of the visitor can be altered, including skipping over a sub-tree of - * the AST (by returning false), editing the AST by returning a value or null - * to remove the value, or to stop the whole traversal by returning BREAK. - * - * When using visit() to edit an AST, the original AST will not be modified, and - * a new version of the AST with the changes applied will be returned from the - * visit function. - * - * ```ts - * const editedAST = visit(ast, { - * enter(node, key, parent, path, ancestors) { - * // @return - * // undefined: no action - * // false: skip visiting this node - * // visitor.BREAK: stop visiting altogether - * // null: delete this node - * // any value: replace this node with the returned value - * }, - * leave(node, key, parent, path, ancestors) { - * // @return - * // undefined: no action - * // false: no action - * // visitor.BREAK: stop visiting altogether - * // null: delete this node - * // any value: replace this node with the returned value - * } - * }); - * ``` - * - * Alternatively to providing enter() and leave() functions, a visitor can - * instead provide functions named the same as the kinds of AST nodes, or - * enter/leave visitors at a named key, leading to three permutations of the - * visitor API: - * - * 1) Named visitors triggered when entering a node of a specific kind. - * - * ```ts - * visit(ast, { - * Kind(node) { - * // enter the "Kind" node - * } - * }) - * ``` - * - * 2) Named visitors that trigger upon entering and leaving a node of a specific kind. - * - * ```ts - * visit(ast, { - * Kind: { - * enter(node) { - * // enter the "Kind" node - * } - * leave(node) { - * // leave the "Kind" node - * } - * } - * }) - * ``` + * No unused variables * - * 3) Generic visitors that trigger upon entering and leaving any node. + * A GraphQL operation is only valid if all variables defined by an operation + * are used, either directly or within a spread fragment. * - * ```ts - * visit(ast, { - * enter(node) { - * // enter any node - * }, - * leave(node) { - * // leave any node - * } - * }) - * ``` + * See https://spec.graphql.org/draft/#sec-All-Variables-Used */ +function NoUnusedVariablesRule(context) { + let variableDefs = []; + return { + OperationDefinition: { + enter() { + variableDefs = []; + }, -exports.BREAK = BREAK; - -function visit(root, visitor, visitorKeys = _ast.QueryDocumentKeys) { - const enterLeaveMap = new Map(); - - for (const kind of Object.values(_kinds.Kind)) { - enterLeaveMap.set(kind, getEnterLeaveForKind(visitor, kind)); - } - /* eslint-disable no-undef-init */ - - let stack = undefined; - let inArray = Array.isArray(root); - let keys = [root]; - let index = -1; - let edits = []; - let node = root; - let key = undefined; - let parent = undefined; - const path = []; - const ancestors = []; - /* eslint-enable no-undef-init */ - - do { - index++; - const isLeaving = index === keys.length; - const isEdited = isLeaving && edits.length !== 0; - - if (isLeaving) { - key = ancestors.length === 0 ? undefined : path[path.length - 1]; - node = parent; - parent = ancestors.pop(); - - if (isEdited) { - if (inArray) { - node = node.slice(); - let editOffset = 0; + leave(operation) { + const variableNameUsed = Object.create(null); + const usages = context.getRecursiveVariableUsages(operation); - for (const [editKey, editValue] of edits) { - const arrayKey = editKey - editOffset; + for (const { node } of usages) { + variableNameUsed[node.name.value] = true; + } - if (editValue === null) { - node.splice(arrayKey, 1); - editOffset++; - } else { - node[arrayKey] = editValue; - } - } - } else { - node = { ...node }; + for (const variableDef of variableDefs) { + const variableName = variableDef.variable.name.value; - for (const [editKey, editValue] of edits) { - node[editKey] = editValue; + if (variableNameUsed[variableName] !== true) { + context.reportError( + new _GraphQLError.GraphQLError( + operation.name + ? `Variable "$${variableName}" is never used in operation "${operation.name.value}".` + : `Variable "$${variableName}" is never used.`, + { + nodes: variableDef, + }, + ), + ); } } - } + }, + }, - index = stack.index; - keys = stack.keys; - edits = stack.edits; - inArray = stack.inArray; - stack = stack.prev; - } else if (parent) { - key = inArray ? index : keys[index]; - node = parent[key]; + VariableDefinition(def) { + variableDefs.push(def); + }, + }; +} - if (node === null || node === undefined) { - continue; - } - path.push(key); - } +/***/ }), - let result; +/***/ 23577: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (!Array.isArray(node)) { - var _enterLeaveMap$get, _enterLeaveMap$get2; +"use strict"; - (0, _ast.isNode)(node) || - (0, _devAssert.devAssert)( - false, - `Invalid AST Node: ${(0, _inspect.inspect)(node)}.`, - ); - const visitFn = isLeaving - ? (_enterLeaveMap$get = enterLeaveMap.get(node.kind)) === null || - _enterLeaveMap$get === void 0 - ? void 0 - : _enterLeaveMap$get.leave - : (_enterLeaveMap$get2 = enterLeaveMap.get(node.kind)) === null || - _enterLeaveMap$get2 === void 0 - ? void 0 - : _enterLeaveMap$get2.enter; - result = - visitFn === null || visitFn === void 0 - ? void 0 - : visitFn.call(visitor, node, key, parent, path, ancestors); - if (result === BREAK) { - break; - } +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.OverlappingFieldsCanBeMergedRule = OverlappingFieldsCanBeMergedRule; - if (result === false) { - if (!isLeaving) { - path.pop(); - continue; - } - } else if (result !== undefined) { - edits.push([key, result]); +var _inspect = __nccwpck_require__(10102); - if (!isLeaving) { - if ((0, _ast.isNode)(result)) { - node = result; - } else { - path.pop(); - continue; - } - } - } - } +var _GraphQLError = __nccwpck_require__(4797); - if (result === undefined && isEdited) { - edits.push([key, node]); - } +var _kinds = __nccwpck_require__(11927); - if (isLeaving) { - path.pop(); - } else { - var _node$kind; +var _printer = __nccwpck_require__(68203); - stack = { - inArray, - index, - keys, - edits, - prev: stack, - }; - inArray = Array.isArray(node); - keys = inArray - ? node - : (_node$kind = visitorKeys[node.kind]) !== null && - _node$kind !== void 0 - ? _node$kind - : []; - index = -1; - edits = []; +var _definition = __nccwpck_require__(32150); - if (parent) { - ancestors.push(parent); - } +var _sortValueNode = __nccwpck_require__(82278); - parent = node; - } - } while (stack !== undefined); +var _typeFromAST = __nccwpck_require__(27664); - if (edits.length !== 0) { - // New root - return edits[edits.length - 1][1]; +function reasonMessage(reason) { + if (Array.isArray(reason)) { + return reason + .map( + ([responseName, subReason]) => + `subfields "${responseName}" conflict because ` + + reasonMessage(subReason), + ) + .join(' and '); } - return root; + return reason; } /** - * Creates a new visitor instance which delegates to many visitors to run in - * parallel. Each visitor will be visited for each node before moving on. + * Overlapping fields can be merged * - * If a prior visitor edits a node, no following visitors will see that node. + * A selection set is only valid if all fields (including spreading any + * fragments) either correspond to distinct response names or can be merged + * without ambiguity. + * + * See https://spec.graphql.org/draft/#sec-Field-Selection-Merging */ -function visitInParallel(visitors) { - const skipping = new Array(visitors.length).fill(null); - const mergedVisitor = Object.create(null); - - for (const kind of Object.values(_kinds.Kind)) { - let hasVisitor = false; - const enterList = new Array(visitors.length).fill(undefined); - const leaveList = new Array(visitors.length).fill(undefined); +function OverlappingFieldsCanBeMergedRule(context) { + // A memoization for when fields and a fragment or two fragments are compared + // "between" each other for conflicts. Comparisons made be made many times, + // so memoizing this can dramatically improve the performance of this validator. + const comparedFieldsAndFragmentPairs = new OrderedPairSet(); + const comparedFragmentPairs = new PairSet(); // A cache for the "field map" and list of fragment names found in any given + // selection set. Selection sets may be asked for this information multiple + // times, so this improves the performance of this validator. - for (let i = 0; i < visitors.length; ++i) { - const { enter, leave } = getEnterLeaveForKind(visitors[i], kind); - hasVisitor || (hasVisitor = enter != null || leave != null); - enterList[i] = enter; - leaveList[i] = leave; - } + const cachedFieldsAndFragmentNames = new Map(); + return { + SelectionSet(selectionSet) { + const conflicts = findConflictsWithinSelectionSet( + context, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + context.getParentType(), + selectionSet, + ); - if (!hasVisitor) { - continue; - } + for (const [[responseName, reason], fields1, fields2] of conflicts) { + const reasonMsg = reasonMessage(reason); + context.reportError( + new _GraphQLError.GraphQLError( + `Fields "${responseName}" conflict because ${reasonMsg}. Use different aliases on the fields to fetch both if this was intentional.`, + { + nodes: fields1.concat(fields2), + }, + ), + ); + } + }, + }; +} - const mergedEnterLeave = { - enter(...args) { - const node = args[0]; +/** + * Algorithm: + * + * Conflicts occur when two fields exist in a query which will produce the same + * response name, but represent differing values, thus creating a conflict. + * The algorithm below finds all conflicts via making a series of comparisons + * between fields. In order to compare as few fields as possible, this makes + * a series of comparisons "within" sets of fields and "between" sets of fields. + * + * Given any selection set, a collection produces both a set of fields by + * also including all inline fragments, as well as a list of fragments + * referenced by fragment spreads. + * + * A) Each selection set represented in the document first compares "within" its + * collected set of fields, finding any conflicts between every pair of + * overlapping fields. + * Note: This is the *only time* that a the fields "within" a set are compared + * to each other. After this only fields "between" sets are compared. + * + * B) Also, if any fragment is referenced in a selection set, then a + * comparison is made "between" the original set of fields and the + * referenced fragment. + * + * C) Also, if multiple fragments are referenced, then comparisons + * are made "between" each referenced fragment. + * + * D) When comparing "between" a set of fields and a referenced fragment, first + * a comparison is made between each field in the original set of fields and + * each field in the the referenced set of fields. + * + * E) Also, if any fragment is referenced in the referenced selection set, + * then a comparison is made "between" the original set of fields and the + * referenced fragment (recursively referring to step D). + * + * F) When comparing "between" two fragments, first a comparison is made between + * each field in the first referenced set of fields and each field in the the + * second referenced set of fields. + * + * G) Also, any fragments referenced by the first must be compared to the + * second, and any fragments referenced by the second must be compared to the + * first (recursively referring to step F). + * + * H) When comparing two fields, if both have selection sets, then a comparison + * is made "between" both selection sets, first comparing the set of fields in + * the first selection set with the set of fields in the second. + * + * I) Also, if any fragment is referenced in either selection set, then a + * comparison is made "between" the other set of fields and the + * referenced fragment. + * + * J) Also, if two fragments are referenced in both selection sets, then a + * comparison is made "between" the two fragments. + * + */ +// Find all conflicts found "within" a selection set, including those found +// via spreading in fragments. Called when visiting each SelectionSet in the +// GraphQL Document. +function findConflictsWithinSelectionSet( + context, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + parentType, + selectionSet, +) { + const conflicts = []; + const [fieldMap, fragmentNames] = getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + parentType, + selectionSet, + ); // (A) Find find all conflicts "within" the fields of this selection set. + // Note: this is the *only place* `collectConflictsWithin` is called. - for (let i = 0; i < visitors.length; i++) { - if (skipping[i] === null) { - var _enterList$i; + collectConflictsWithin( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + fieldMap, + ); - const result = - (_enterList$i = enterList[i]) === null || _enterList$i === void 0 - ? void 0 - : _enterList$i.apply(visitors[i], args); + if (fragmentNames.length !== 0) { + // (B) Then collect conflicts between these fields and those represented by + // each spread fragment name found. + for (let i = 0; i < fragmentNames.length; i++) { + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + false, + fieldMap, + fragmentNames[i], + ); // (C) Then compare this fragment with all other fragments found in this + // selection set to collect conflicts between fragments spread together. + // This compares each item in the list of fragment names to every other + // item in that same list (except for itself). - if (result === false) { - skipping[i] = node; - } else if (result === BREAK) { - skipping[i] = BREAK; - } else if (result !== undefined) { - return result; - } - } - } - }, + for (let j = i + 1; j < fragmentNames.length; j++) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + false, + fragmentNames[i], + fragmentNames[j], + ); + } + } + } - leave(...args) { - const node = args[0]; + return conflicts; +} // Collect all conflicts found between a set of fields and a fragment reference +// including via spreading in any nested fragments. - for (let i = 0; i < visitors.length; i++) { - if (skipping[i] === null) { - var _leaveList$i; +function collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap, + fragmentName, +) { + // Memoize so the fields and fragments are not compared for conflicts more + // than once. + if ( + comparedFieldsAndFragmentPairs.has( + fieldMap, + fragmentName, + areMutuallyExclusive, + ) + ) { + return; + } - const result = - (_leaveList$i = leaveList[i]) === null || _leaveList$i === void 0 - ? void 0 - : _leaveList$i.apply(visitors[i], args); + comparedFieldsAndFragmentPairs.add( + fieldMap, + fragmentName, + areMutuallyExclusive, + ); + const fragment = context.getFragment(fragmentName); - if (result === BREAK) { - skipping[i] = BREAK; - } else if (result !== undefined && result !== false) { - return result; - } - } else if (skipping[i] === node) { - skipping[i] = null; - } - } - }, - }; - mergedVisitor[kind] = mergedEnterLeave; + if (!fragment) { + return; } - return mergedVisitor; -} -/** - * Given a visitor instance and a node kind, return EnterLeaveVisitor for that kind. - */ - -function getEnterLeaveForKind(visitor, kind) { - const kindVisitor = visitor[kind]; + const [fieldMap2, referencedFragmentNames] = + getReferencedFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragment, + ); // Do not compare a fragment's fieldMap to itself. - if (typeof kindVisitor === 'object') { - // { Kind: { enter() {}, leave() {} } } - return kindVisitor; - } else if (typeof kindVisitor === 'function') { - // { Kind() {} } - return { - enter: kindVisitor, - leave: undefined, - }; - } // { enter() {}, leave() {} } + if (fieldMap === fieldMap2) { + return; + } // (D) First collect any conflicts between the provided collection of fields + // and the collection of fields represented by the given fragment. - return { - enter: visitor.enter, - leave: visitor.leave, - }; -} -/** - * Given a visitor instance, if it is leaving or not, and a node kind, return - * the function the visitor runtime should call. - * - * @deprecated Please use `getEnterLeaveForKind` instead. Will be removed in v17 - */ + collectConflictsBetween( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap, + fieldMap2, + ); // (E) Then collect any conflicts between the provided collection of fields + // and any fragment names found in the given fragment. -/* c8 ignore next 8 */ + for (const referencedFragmentName of referencedFragmentNames) { + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap, + referencedFragmentName, + ); + } +} // Collect all conflicts found between two fragments, including via spreading in +// any nested fragments. -function getVisitFn(visitor, kind, isLeaving) { - const { enter, leave } = getEnterLeaveForKind(visitor, kind); - return isLeaving ? leave : enter; -} +function collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + fragmentName1, + fragmentName2, +) { + // No need to compare a fragment to itself. + if (fragmentName1 === fragmentName2) { + return; + } // Memoize so two fragments are not compared for conflicts more than once. + if ( + comparedFragmentPairs.has( + fragmentName1, + fragmentName2, + areMutuallyExclusive, + ) + ) { + return; + } -/***/ }), + comparedFragmentPairs.add(fragmentName1, fragmentName2, areMutuallyExclusive); + const fragment1 = context.getFragment(fragmentName1); + const fragment2 = context.getFragment(fragmentName2); -/***/ 74947: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (!fragment1 || !fragment2) { + return; + } -"use strict"; + const [fieldMap1, referencedFragmentNames1] = + getReferencedFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragment1, + ); + const [fieldMap2, referencedFragmentNames2] = + getReferencedFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragment2, + ); // (F) First, collect all conflicts between these two collections of fields + // (not including any nested fragments). + collectConflictsBetween( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap1, + fieldMap2, + ); // (G) Then collect conflicts between the first fragment and any nested + // fragments spread in the second fragment. -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.assertEnumValueName = assertEnumValueName; -exports.assertName = assertName; + for (const referencedFragmentName2 of referencedFragmentNames2) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + fragmentName1, + referencedFragmentName2, + ); + } // (G) Then collect conflicts between the second fragment and any nested + // fragments spread in the first fragment. -var _devAssert = __nccwpck_require__(46514); + for (const referencedFragmentName1 of referencedFragmentNames1) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + referencedFragmentName1, + fragmentName2, + ); + } +} // Find all conflicts found between two selection sets, including those found +// via spreading in fragments. Called when determining if conflicts exist +// between the sub-fields of two overlapping fields. -var _GraphQLError = __nccwpck_require__(4797); +function findConflictsBetweenSubSelectionSets( + context, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + parentType1, + selectionSet1, + parentType2, + selectionSet2, +) { + const conflicts = []; + const [fieldMap1, fragmentNames1] = getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + parentType1, + selectionSet1, + ); + const [fieldMap2, fragmentNames2] = getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + parentType2, + selectionSet2, + ); // (H) First, collect all conflicts between these two collections of field. -var _characterClasses = __nccwpck_require__(7234); + collectConflictsBetween( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap1, + fieldMap2, + ); // (I) Then collect conflicts between the first collection of fields and + // those referenced by each fragment name associated with the second. -/** - * Upholds the spec rules about naming. - */ -function assertName(name) { - name != null || (0, _devAssert.devAssert)(false, 'Must provide name.'); - typeof name === 'string' || - (0, _devAssert.devAssert)(false, 'Expected name to be a string.'); + for (const fragmentName2 of fragmentNames2) { + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap1, + fragmentName2, + ); + } // (I) Then collect conflicts between the second collection of fields and + // those referenced by each fragment name associated with the first. - if (name.length === 0) { - throw new _GraphQLError.GraphQLError( - 'Expected name to be a non-empty string.', + for (const fragmentName1 of fragmentNames1) { + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap2, + fragmentName1, ); - } + } // (J) Also collect conflicts between any fragment names by the first and + // fragment names by the second. This compares each item in the first set of + // names to each item in the second set of names. - for (let i = 1; i < name.length; ++i) { - if (!(0, _characterClasses.isNameContinue)(name.charCodeAt(i))) { - throw new _GraphQLError.GraphQLError( - `Names must only contain [_a-zA-Z0-9] but "${name}" does not.`, + for (const fragmentName1 of fragmentNames1) { + for (const fragmentName2 of fragmentNames2) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + fragmentName1, + fragmentName2, ); } } - if (!(0, _characterClasses.isNameStart)(name.charCodeAt(0))) { - throw new _GraphQLError.GraphQLError( - `Names must start with [_a-zA-Z] but "${name}" does not.`, - ); - } + return conflicts; +} // Collect all Conflicts "within" one collection of fields. - return name; -} -/** - * Upholds the spec rules about naming enum values. - * - * @internal - */ +function collectConflictsWithin( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + fieldMap, +) { + // A field map is a keyed collection, where each key represents a response + // name and the value at that key is a list of all fields which provide that + // response name. For every response name, if there are multiple fields, they + // must be compared to find a potential conflict. + for (const [responseName, fields] of Object.entries(fieldMap)) { + // This compares every field in the list to every other field in this list + // (except to itself). If the list only has one item, nothing needs to + // be compared. + if (fields.length > 1) { + for (let i = 0; i < fields.length; i++) { + for (let j = i + 1; j < fields.length; j++) { + const conflict = findConflict( + context, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + false, // within one collection is never mutually exclusive + responseName, + fields[i], + fields[j], + ); -function assertEnumValueName(name) { - if (name === 'true' || name === 'false' || name === 'null') { - throw new _GraphQLError.GraphQLError( - `Enum values cannot be named: ${name}`, - ); + if (conflict) { + conflicts.push(conflict); + } + } + } + } } +} // Collect all Conflicts between two collections of fields. This is similar to, +// but different from the `collectConflictsWithin` function above. This check +// assumes that `collectConflictsWithin` has already been called on each +// provided collection of fields. This is true because this validator traverses +// each individual selection set. - return assertName(name); -} - - -/***/ }), - -/***/ 32150: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.GraphQLUnionType = - exports.GraphQLScalarType = - exports.GraphQLObjectType = - exports.GraphQLNonNull = - exports.GraphQLList = - exports.GraphQLInterfaceType = - exports.GraphQLInputObjectType = - exports.GraphQLEnumType = - void 0; -exports.argsToArgsConfig = argsToArgsConfig; -exports.assertAbstractType = assertAbstractType; -exports.assertCompositeType = assertCompositeType; -exports.assertEnumType = assertEnumType; -exports.assertInputObjectType = assertInputObjectType; -exports.assertInputType = assertInputType; -exports.assertInterfaceType = assertInterfaceType; -exports.assertLeafType = assertLeafType; -exports.assertListType = assertListType; -exports.assertNamedType = assertNamedType; -exports.assertNonNullType = assertNonNullType; -exports.assertNullableType = assertNullableType; -exports.assertObjectType = assertObjectType; -exports.assertOutputType = assertOutputType; -exports.assertScalarType = assertScalarType; -exports.assertType = assertType; -exports.assertUnionType = assertUnionType; -exports.assertWrappingType = assertWrappingType; -exports.defineArguments = defineArguments; -exports.getNamedType = getNamedType; -exports.getNullableType = getNullableType; -exports.isAbstractType = isAbstractType; -exports.isCompositeType = isCompositeType; -exports.isEnumType = isEnumType; -exports.isInputObjectType = isInputObjectType; -exports.isInputType = isInputType; -exports.isInterfaceType = isInterfaceType; -exports.isLeafType = isLeafType; -exports.isListType = isListType; -exports.isNamedType = isNamedType; -exports.isNonNullType = isNonNullType; -exports.isNullableType = isNullableType; -exports.isObjectType = isObjectType; -exports.isOutputType = isOutputType; -exports.isRequiredArgument = isRequiredArgument; -exports.isRequiredInputField = isRequiredInputField; -exports.isScalarType = isScalarType; -exports.isType = isType; -exports.isUnionType = isUnionType; -exports.isWrappingType = isWrappingType; -exports.resolveObjMapThunk = resolveObjMapThunk; -exports.resolveReadonlyArrayThunk = resolveReadonlyArrayThunk; - -var _devAssert = __nccwpck_require__(46514); - -var _didYouMean = __nccwpck_require__(42878); - -var _identityFunc = __nccwpck_require__(51188); - -var _inspect = __nccwpck_require__(10102); - -var _instanceOf = __nccwpck_require__(93481); - -var _isObjectLike = __nccwpck_require__(95865); - -var _keyMap = __nccwpck_require__(10711); +function collectConflictsBetween( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + parentFieldsAreMutuallyExclusive, + fieldMap1, + fieldMap2, +) { + // A field map is a keyed collection, where each key represents a response + // name and the value at that key is a list of all fields which provide that + // response name. For any response name which appears in both provided field + // maps, each field from the first field map must be compared to every field + // in the second field map to find potential conflicts. + for (const [responseName, fields1] of Object.entries(fieldMap1)) { + const fields2 = fieldMap2[responseName]; -var _keyValMap = __nccwpck_require__(49268); + if (fields2) { + for (const field1 of fields1) { + for (const field2 of fields2) { + const conflict = findConflict( + context, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + parentFieldsAreMutuallyExclusive, + responseName, + field1, + field2, + ); -var _mapValue = __nccwpck_require__(32223); + if (conflict) { + conflicts.push(conflict); + } + } + } + } + } +} // Determines if there is a conflict between two particular fields, including +// comparing their sub-fields. -var _suggestionList = __nccwpck_require__(57704); +function findConflict( + context, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + parentFieldsAreMutuallyExclusive, + responseName, + field1, + field2, +) { + const [parentType1, node1, def1] = field1; + const [parentType2, node2, def2] = field2; // If it is known that two fields could not possibly apply at the same + // time, due to the parent types, then it is safe to permit them to diverge + // in aliased field or arguments used as they will not present any ambiguity + // by differing. + // It is known that two parent types could never overlap if they are + // different Object types. Interface or Union types might overlap - if not + // in the current state of the schema, then perhaps in some future version, + // thus may not safely diverge. -var _toObjMap = __nccwpck_require__(74728); + const areMutuallyExclusive = + parentFieldsAreMutuallyExclusive || + (parentType1 !== parentType2 && + (0, _definition.isObjectType)(parentType1) && + (0, _definition.isObjectType)(parentType2)); -var _GraphQLError = __nccwpck_require__(4797); + if (!areMutuallyExclusive) { + // Two aliases must refer to the same field. + const name1 = node1.name.value; + const name2 = node2.name.value; -var _kinds = __nccwpck_require__(11927); + if (name1 !== name2) { + return [ + [responseName, `"${name1}" and "${name2}" are different fields`], + [node1], + [node2], + ]; + } // Two field calls must have the same arguments. -var _printer = __nccwpck_require__(68203); + if (!sameArguments(node1, node2)) { + return [ + [responseName, 'they have differing arguments'], + [node1], + [node2], + ]; + } + } // The return type for each field. -var _valueFromASTUntyped = __nccwpck_require__(86699); + const type1 = def1 === null || def1 === void 0 ? void 0 : def1.type; + const type2 = def2 === null || def2 === void 0 ? void 0 : def2.type; -var _assertName = __nccwpck_require__(74947); + if (type1 && type2 && doTypesConflict(type1, type2)) { + return [ + [ + responseName, + `they return conflicting types "${(0, _inspect.inspect)( + type1, + )}" and "${(0, _inspect.inspect)(type2)}"`, + ], + [node1], + [node2], + ]; + } // Collect and compare sub-fields. Use the same "visited fragment names" list + // for both collections so fields in a fragment reference are never + // compared to themselves. -function isType(type) { - return ( - isScalarType(type) || - isObjectType(type) || - isInterfaceType(type) || - isUnionType(type) || - isEnumType(type) || - isInputObjectType(type) || - isListType(type) || - isNonNullType(type) - ); -} + const selectionSet1 = node1.selectionSet; + const selectionSet2 = node2.selectionSet; -function assertType(type) { - if (!isType(type)) { - throw new Error( - `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL type.`, + if (selectionSet1 && selectionSet2) { + const conflicts = findConflictsBetweenSubSelectionSets( + context, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + (0, _definition.getNamedType)(type1), + selectionSet1, + (0, _definition.getNamedType)(type2), + selectionSet2, ); + return subfieldConflicts(conflicts, responseName, node1, node2); } - - return type; } -/** - * There are predicates for each kind of GraphQL type. - */ -function isScalarType(type) { - return (0, _instanceOf.instanceOf)(type, GraphQLScalarType); -} +function sameArguments(node1, node2) { + const args1 = node1.arguments; + const args2 = node2.arguments; -function assertScalarType(type) { - if (!isScalarType(type)) { - throw new Error( - `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Scalar type.`, - ); + if (args1 === undefined || args1.length === 0) { + return args2 === undefined || args2.length === 0; } - return type; -} - -function isObjectType(type) { - return (0, _instanceOf.instanceOf)(type, GraphQLObjectType); -} - -function assertObjectType(type) { - if (!isObjectType(type)) { - throw new Error( - `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Object type.`, - ); + if (args2 === undefined || args2.length === 0) { + return false; } + /* c8 ignore next */ - return type; -} - -function isInterfaceType(type) { - return (0, _instanceOf.instanceOf)(type, GraphQLInterfaceType); -} - -function assertInterfaceType(type) { - if (!isInterfaceType(type)) { - throw new Error( - `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Interface type.`, - ); + if (args1.length !== args2.length) { + /* c8 ignore next */ + return false; + /* c8 ignore next */ } - return type; -} - -function isUnionType(type) { - return (0, _instanceOf.instanceOf)(type, GraphQLUnionType); -} + const values2 = new Map(args2.map(({ name, value }) => [name.value, value])); + return args1.every((arg1) => { + const value1 = arg1.value; + const value2 = values2.get(arg1.name.value); -function assertUnionType(type) { - if (!isUnionType(type)) { - throw new Error( - `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Union type.`, - ); - } + if (value2 === undefined) { + return false; + } - return type; + return stringifyValue(value1) === stringifyValue(value2); + }); } -function isEnumType(type) { - return (0, _instanceOf.instanceOf)(type, GraphQLEnumType); -} +function stringifyValue(value) { + return (0, _printer.print)((0, _sortValueNode.sortValueNode)(value)); +} // Two types conflict if both types could not apply to a value simultaneously. +// Composite types are ignored as their individual field types will be compared +// later recursively. However List and Non-Null types must match. -function assertEnumType(type) { - if (!isEnumType(type)) { - throw new Error( - `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Enum type.`, - ); +function doTypesConflict(type1, type2) { + if ((0, _definition.isListType)(type1)) { + return (0, _definition.isListType)(type2) + ? doTypesConflict(type1.ofType, type2.ofType) + : true; } - return type; -} - -function isInputObjectType(type) { - return (0, _instanceOf.instanceOf)(type, GraphQLInputObjectType); -} - -function assertInputObjectType(type) { - if (!isInputObjectType(type)) { - throw new Error( - `Expected ${(0, _inspect.inspect)( - type, - )} to be a GraphQL Input Object type.`, - ); + if ((0, _definition.isListType)(type2)) { + return true; } - return type; -} + if ((0, _definition.isNonNullType)(type1)) { + return (0, _definition.isNonNullType)(type2) + ? doTypesConflict(type1.ofType, type2.ofType) + : true; + } -function isListType(type) { - return (0, _instanceOf.instanceOf)(type, GraphQLList); -} + if ((0, _definition.isNonNullType)(type2)) { + return true; + } -function assertListType(type) { - if (!isListType(type)) { - throw new Error( - `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL List type.`, - ); + if ( + (0, _definition.isLeafType)(type1) || + (0, _definition.isLeafType)(type2) + ) { + return type1 !== type2; } - return type; -} + return false; +} // Given a selection set, return the collection of fields (a mapping of response +// name to field nodes and definitions) as well as a list of fragment names +// referenced via fragment spreads. -function isNonNullType(type) { - return (0, _instanceOf.instanceOf)(type, GraphQLNonNull); -} +function getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + parentType, + selectionSet, +) { + const cached = cachedFieldsAndFragmentNames.get(selectionSet); -function assertNonNullType(type) { - if (!isNonNullType(type)) { - throw new Error( - `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Non-Null type.`, - ); + if (cached) { + return cached; } - return type; -} -/** - * These types may be used as input types for arguments and directives. - */ + const nodeAndDefs = Object.create(null); + const fragmentNames = Object.create(null); -function isInputType(type) { - return ( - isScalarType(type) || - isEnumType(type) || - isInputObjectType(type) || - (isWrappingType(type) && isInputType(type.ofType)) + _collectFieldsAndFragmentNames( + context, + parentType, + selectionSet, + nodeAndDefs, + fragmentNames, ); -} -function assertInputType(type) { - if (!isInputType(type)) { - throw new Error( - `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL input type.`, - ); - } - - return type; -} -/** - * These types may be used as output types as the result of fields. - */ + const result = [nodeAndDefs, Object.keys(fragmentNames)]; + cachedFieldsAndFragmentNames.set(selectionSet, result); + return result; +} // Given a reference to a fragment, return the represented collection of fields +// as well as a list of nested fragment names referenced via fragment spreads. -function isOutputType(type) { - return ( - isScalarType(type) || - isObjectType(type) || - isInterfaceType(type) || - isUnionType(type) || - isEnumType(type) || - (isWrappingType(type) && isOutputType(type.ofType)) - ); -} +function getReferencedFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragment, +) { + // Short-circuit building a type from the node if possible. + const cached = cachedFieldsAndFragmentNames.get(fragment.selectionSet); -function assertOutputType(type) { - if (!isOutputType(type)) { - throw new Error( - `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL output type.`, - ); + if (cached) { + return cached; } - return type; + const fragmentType = (0, _typeFromAST.typeFromAST)( + context.getSchema(), + fragment.typeCondition, + ); + return getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragmentType, + fragment.selectionSet, + ); } -/** - * These types may describe types which may be leaf values. - */ -function isLeafType(type) { - return isScalarType(type) || isEnumType(type); -} +function _collectFieldsAndFragmentNames( + context, + parentType, + selectionSet, + nodeAndDefs, + fragmentNames, +) { + for (const selection of selectionSet.selections) { + switch (selection.kind) { + case _kinds.Kind.FIELD: { + const fieldName = selection.name.value; + let fieldDef; -function assertLeafType(type) { - if (!isLeafType(type)) { - throw new Error( - `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL leaf type.`, - ); - } + if ( + (0, _definition.isObjectType)(parentType) || + (0, _definition.isInterfaceType)(parentType) + ) { + fieldDef = parentType.getFields()[fieldName]; + } - return type; -} -/** - * These types may describe the parent context of a selection set. - */ + const responseName = selection.alias + ? selection.alias.value + : fieldName; -function isCompositeType(type) { - return isObjectType(type) || isInterfaceType(type) || isUnionType(type); -} + if (!nodeAndDefs[responseName]) { + nodeAndDefs[responseName] = []; + } -function assertCompositeType(type) { - if (!isCompositeType(type)) { - throw new Error( - `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL composite type.`, - ); - } + nodeAndDefs[responseName].push([parentType, selection, fieldDef]); + break; + } - return type; -} -/** - * These types may describe the parent context of a selection set. - */ + case _kinds.Kind.FRAGMENT_SPREAD: + fragmentNames[selection.name.value] = true; + break; -function isAbstractType(type) { - return isInterfaceType(type) || isUnionType(type); -} + case _kinds.Kind.INLINE_FRAGMENT: { + const typeCondition = selection.typeCondition; + const inlineFragmentType = typeCondition + ? (0, _typeFromAST.typeFromAST)(context.getSchema(), typeCondition) + : parentType; -function assertAbstractType(type) { - if (!isAbstractType(type)) { - throw new Error( - `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL abstract type.`, - ); + _collectFieldsAndFragmentNames( + context, + inlineFragmentType, + selection.selectionSet, + nodeAndDefs, + fragmentNames, + ); + + break; + } + } } +} // Given a series of Conflicts which occurred between two sub-fields, generate +// a single Conflict. - return type; +function subfieldConflicts(conflicts, responseName, node1, node2) { + if (conflicts.length > 0) { + return [ + [responseName, conflicts.map(([reason]) => reason)], + [node1, ...conflicts.map(([, fields1]) => fields1).flat()], + [node2, ...conflicts.map(([, , fields2]) => fields2).flat()], + ]; + } } /** - * List Type Wrapper - * - * A list is a wrapping type which points to another type. - * Lists are often created within the context of defining the fields of - * an object type. - * - * Example: + * A way to keep track of pairs of things where the ordering of the pair + * matters. * - * ```ts - * const PersonType = new GraphQLObjectType({ - * name: 'Person', - * fields: () => ({ - * parents: { type: new GraphQLList(PersonType) }, - * children: { type: new GraphQLList(PersonType) }, - * }) - * }) - * ``` + * Provides a third argument for has/set to allow flagging the pair as + * weakly or strongly present within the collection. */ -class GraphQLList { - constructor(ofType) { - isType(ofType) || - (0, _devAssert.devAssert)( - false, - `Expected ${(0, _inspect.inspect)(ofType)} to be a GraphQL type.`, - ); - this.ofType = ofType; +class OrderedPairSet { + constructor() { + this._data = new Map(); } - get [Symbol.toStringTag]() { - return 'GraphQLList'; - } + has(a, b, weaklyPresent) { + var _this$_data$get; - toString() { - return '[' + String(this.ofType) + ']'; + const result = + (_this$_data$get = this._data.get(a)) === null || + _this$_data$get === void 0 + ? void 0 + : _this$_data$get.get(b); + + if (result === undefined) { + return false; + } + + return weaklyPresent ? true : weaklyPresent === result; } - toJSON() { - return this.toString(); + add(a, b, weaklyPresent) { + const map = this._data.get(a); + + if (map === undefined) { + this._data.set(a, new Map([[b, weaklyPresent]])); + } else { + map.set(b, weaklyPresent); + } } } /** - * Non-Null Type Wrapper - * - * A non-null is a wrapping type which points to another type. - * Non-null types enforce that their values are never null and can ensure - * an error is raised if this ever occurs during a request. It is useful for - * fields which you can make a strong guarantee on non-nullability, for example - * usually the id field of a database row will never be null. - * - * Example: - * - * ```ts - * const RowType = new GraphQLObjectType({ - * name: 'Row', - * fields: () => ({ - * id: { type: new GraphQLNonNull(GraphQLString) }, - * }) - * }) - * ``` - * Note: the enforcement of non-nullability occurs within the executor. + * A way to keep track of pairs of similar things when the ordering of the pair + * does not matter. */ -exports.GraphQLList = GraphQLList; - -class GraphQLNonNull { - constructor(ofType) { - isNullableType(ofType) || - (0, _devAssert.devAssert)( - false, - `Expected ${(0, _inspect.inspect)( - ofType, - )} to be a GraphQL nullable type.`, - ); - this.ofType = ofType; - } - - get [Symbol.toStringTag]() { - return 'GraphQLNonNull'; +class PairSet { + constructor() { + this._orderedPairSet = new OrderedPairSet(); } - toString() { - return String(this.ofType) + '!'; + has(a, b, weaklyPresent) { + return a < b + ? this._orderedPairSet.has(a, b, weaklyPresent) + : this._orderedPairSet.has(b, a, weaklyPresent); } - toJSON() { - return this.toString(); + add(a, b, weaklyPresent) { + if (a < b) { + this._orderedPairSet.add(a, b, weaklyPresent); + } else { + this._orderedPairSet.add(b, a, weaklyPresent); + } } } -/** - * These types wrap and modify other types - */ -exports.GraphQLNonNull = GraphQLNonNull; -function isWrappingType(type) { - return isListType(type) || isNonNullType(type); -} +/***/ }), -function assertWrappingType(type) { - if (!isWrappingType(type)) { - throw new Error( - `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL wrapping type.`, - ); - } +/***/ 62450: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return type; -} -/** - * These types can all accept null as a value. - */ +"use strict"; -function isNullableType(type) { - return isType(type) && !isNonNullType(type); -} -function assertNullableType(type) { - if (!isNullableType(type)) { - throw new Error( - `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL nullable type.`, - ); - } +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.PossibleFragmentSpreadsRule = PossibleFragmentSpreadsRule; - return type; -} +var _inspect = __nccwpck_require__(10102); + +var _GraphQLError = __nccwpck_require__(4797); + +var _definition = __nccwpck_require__(32150); + +var _typeComparators = __nccwpck_require__(10333); + +var _typeFromAST = __nccwpck_require__(27664); -function getNullableType(type) { - if (type) { - return isNonNullType(type) ? type.ofType : type; - } -} /** - * These named types do not include modifiers like List or NonNull. + * Possible fragment spread + * + * A fragment spread is only valid if the type condition could ever possibly + * be true: if there is a non-empty intersection of the possible parent types, + * and possible types which pass the type condition. */ +function PossibleFragmentSpreadsRule(context) { + return { + InlineFragment(node) { + const fragType = context.getType(); + const parentType = context.getParentType(); -function isNamedType(type) { - return ( - isScalarType(type) || - isObjectType(type) || - isInterfaceType(type) || - isUnionType(type) || - isEnumType(type) || - isInputObjectType(type) - ); -} + if ( + (0, _definition.isCompositeType)(fragType) && + (0, _definition.isCompositeType)(parentType) && + !(0, _typeComparators.doTypesOverlap)( + context.getSchema(), + fragType, + parentType, + ) + ) { + const parentTypeStr = (0, _inspect.inspect)(parentType); + const fragTypeStr = (0, _inspect.inspect)(fragType); + context.reportError( + new _GraphQLError.GraphQLError( + `Fragment cannot be spread here as objects of type "${parentTypeStr}" can never be of type "${fragTypeStr}".`, + { + nodes: node, + }, + ), + ); + } + }, -function assertNamedType(type) { - if (!isNamedType(type)) { - throw new Error( - `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL named type.`, - ); - } + FragmentSpread(node) { + const fragName = node.name.value; + const fragType = getFragmentType(context, fragName); + const parentType = context.getParentType(); - return type; + if ( + fragType && + parentType && + !(0, _typeComparators.doTypesOverlap)( + context.getSchema(), + fragType, + parentType, + ) + ) { + const parentTypeStr = (0, _inspect.inspect)(parentType); + const fragTypeStr = (0, _inspect.inspect)(fragType); + context.reportError( + new _GraphQLError.GraphQLError( + `Fragment "${fragName}" cannot be spread here as objects of type "${parentTypeStr}" can never be of type "${fragTypeStr}".`, + { + nodes: node, + }, + ), + ); + } + }, + }; } -function getNamedType(type) { - if (type) { - let unwrappedType = type; +function getFragmentType(context, name) { + const frag = context.getFragment(name); - while (isWrappingType(unwrappedType)) { - unwrappedType = unwrappedType.ofType; - } + if (frag) { + const type = (0, _typeFromAST.typeFromAST)( + context.getSchema(), + frag.typeCondition, + ); - return unwrappedType; + if ((0, _definition.isCompositeType)(type)) { + return type; + } } } -/** - * Used while defining GraphQL types to allow for circular references in - * otherwise immutable type definitions. - */ - -function resolveReadonlyArrayThunk(thunk) { - return typeof thunk === 'function' ? thunk() : thunk; -} -function resolveObjMapThunk(thunk) { - return typeof thunk === 'function' ? thunk() : thunk; -} -/** - * Custom extensions - * - * @remarks - * Use a unique identifier name for your extension, for example the name of - * your library or project. Do not use a shortened identifier as this increases - * the risk of conflicts. We recommend you add at most one extension field, - * an object which can contain all the values you need. - */ -/** - * Scalar Type Definition - * - * The leaf values of any request and input values to arguments are - * Scalars (or Enums) and are defined with a name and a series of functions - * used to parse input from ast or variables and to ensure validity. - * - * If a type's serialize function returns `null` or does not return a value - * (i.e. it returns `undefined`) then an error will be raised and a `null` - * value will be returned in the response. It is always better to validate - * - * Example: - * - * ```ts - * const OddType = new GraphQLScalarType({ - * name: 'Odd', - * serialize(value) { - * if (!Number.isFinite(value)) { - * throw new Error( - * `Scalar "Odd" cannot represent "${value}" since it is not a finite number.`, - * ); - * } - * - * if (value % 2 === 0) { - * throw new Error(`Scalar "Odd" cannot represent "${value}" since it is even.`); - * } - * return value; - * } - * }); - * ``` - */ -class GraphQLScalarType { - constructor(config) { - var _config$parseValue, - _config$serialize, - _config$parseLiteral, - _config$extensionASTN; +/***/ }), - const parseValue = - (_config$parseValue = config.parseValue) !== null && - _config$parseValue !== void 0 - ? _config$parseValue - : _identityFunc.identityFunc; - this.name = (0, _assertName.assertName)(config.name); - this.description = config.description; - this.specifiedByURL = config.specifiedByURL; - this.serialize = - (_config$serialize = config.serialize) !== null && - _config$serialize !== void 0 - ? _config$serialize - : _identityFunc.identityFunc; - this.parseValue = parseValue; - this.parseLiteral = - (_config$parseLiteral = config.parseLiteral) !== null && - _config$parseLiteral !== void 0 - ? _config$parseLiteral - : (node, variables) => - parseValue( - (0, _valueFromASTUntyped.valueFromASTUntyped)(node, variables), - ); - this.extensions = (0, _toObjMap.toObjMap)(config.extensions); - this.astNode = config.astNode; - this.extensionASTNodes = - (_config$extensionASTN = config.extensionASTNodes) !== null && - _config$extensionASTN !== void 0 - ? _config$extensionASTN - : []; - config.specifiedByURL == null || - typeof config.specifiedByURL === 'string' || - (0, _devAssert.devAssert)( - false, - `${this.name} must provide "specifiedByURL" as a string, ` + - `but got: ${(0, _inspect.inspect)(config.specifiedByURL)}.`, - ); - config.serialize == null || - typeof config.serialize === 'function' || - (0, _devAssert.devAssert)( - false, - `${this.name} must provide "serialize" function. If this custom Scalar is also used as an input type, ensure "parseValue" and "parseLiteral" functions are also provided.`, - ); +/***/ 70075: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (config.parseLiteral) { - (typeof config.parseValue === 'function' && - typeof config.parseLiteral === 'function') || - (0, _devAssert.devAssert)( - false, - `${this.name} must provide both "parseValue" and "parseLiteral" functions.`, - ); - } - } +"use strict"; - get [Symbol.toStringTag]() { - return 'GraphQLScalarType'; - } - toConfig() { - return { - name: this.name, - description: this.description, - specifiedByURL: this.specifiedByURL, - serialize: this.serialize, - parseValue: this.parseValue, - parseLiteral: this.parseLiteral, - extensions: this.extensions, - astNode: this.astNode, - extensionASTNodes: this.extensionASTNodes, - }; - } +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.PossibleTypeExtensionsRule = PossibleTypeExtensionsRule; - toString() { - return this.name; - } +var _didYouMean = __nccwpck_require__(42878); - toJSON() { - return this.toString(); - } -} +var _inspect = __nccwpck_require__(10102); -exports.GraphQLScalarType = GraphQLScalarType; +var _invariant = __nccwpck_require__(28847); -/** - * Object Type Definition - * - * Almost all of the GraphQL types you define will be object types. Object types - * have a name, but most importantly describe their fields. - * - * Example: - * - * ```ts - * const AddressType = new GraphQLObjectType({ - * name: 'Address', - * fields: { - * street: { type: GraphQLString }, - * number: { type: GraphQLInt }, - * formatted: { - * type: GraphQLString, - * resolve(obj) { - * return obj.number + ' ' + obj.street - * } - * } - * } - * }); - * ``` - * - * When two types need to refer to each other, or a type needs to refer to - * itself in a field, you can use a function expression (aka a closure or a - * thunk) to supply the fields lazily. - * - * Example: - * - * ```ts - * const PersonType = new GraphQLObjectType({ - * name: 'Person', - * fields: () => ({ - * name: { type: GraphQLString }, - * bestFriend: { type: PersonType }, - * }) - * }); - * ``` - */ -class GraphQLObjectType { - constructor(config) { - var _config$extensionASTN2; +var _suggestionList = __nccwpck_require__(57704); - this.name = (0, _assertName.assertName)(config.name); - this.description = config.description; - this.isTypeOf = config.isTypeOf; - this.extensions = (0, _toObjMap.toObjMap)(config.extensions); - this.astNode = config.astNode; - this.extensionASTNodes = - (_config$extensionASTN2 = config.extensionASTNodes) !== null && - _config$extensionASTN2 !== void 0 - ? _config$extensionASTN2 - : []; +var _GraphQLError = __nccwpck_require__(4797); - this._fields = () => defineFieldMap(config); +var _kinds = __nccwpck_require__(11927); - this._interfaces = () => defineInterfaces(config); +var _predicates = __nccwpck_require__(20535); - config.isTypeOf == null || - typeof config.isTypeOf === 'function' || - (0, _devAssert.devAssert)( - false, - `${this.name} must provide "isTypeOf" as a function, ` + - `but got: ${(0, _inspect.inspect)(config.isTypeOf)}.`, - ); - } +var _definition = __nccwpck_require__(32150); - get [Symbol.toStringTag]() { - return 'GraphQLObjectType'; +/** + * Possible type extension + * + * A type extension is only valid if the type is defined and has the same kind. + */ +function PossibleTypeExtensionsRule(context) { + const schema = context.getSchema(); + const definedTypes = Object.create(null); + + for (const def of context.getDocument().definitions) { + if ((0, _predicates.isTypeDefinitionNode)(def)) { + definedTypes[def.name.value] = def; + } } - getFields() { - if (typeof this._fields === 'function') { - this._fields = this._fields(); + return { + ScalarTypeExtension: checkExtension, + ObjectTypeExtension: checkExtension, + InterfaceTypeExtension: checkExtension, + UnionTypeExtension: checkExtension, + EnumTypeExtension: checkExtension, + InputObjectTypeExtension: checkExtension, + }; + + function checkExtension(node) { + const typeName = node.name.value; + const defNode = definedTypes[typeName]; + const existingType = + schema === null || schema === void 0 ? void 0 : schema.getType(typeName); + let expectedKind; + + if (defNode) { + expectedKind = defKindToExtKind[defNode.kind]; + } else if (existingType) { + expectedKind = typeToExtKind(existingType); } - return this._fields; + if (expectedKind) { + if (expectedKind !== node.kind) { + const kindStr = extensionKindToTypeName(node.kind); + context.reportError( + new _GraphQLError.GraphQLError( + `Cannot extend non-${kindStr} type "${typeName}".`, + { + nodes: defNode ? [defNode, node] : node, + }, + ), + ); + } + } else { + const allTypeNames = Object.keys({ + ...definedTypes, + ...(schema === null || schema === void 0 + ? void 0 + : schema.getTypeMap()), + }); + const suggestedTypes = (0, _suggestionList.suggestionList)( + typeName, + allTypeNames, + ); + context.reportError( + new _GraphQLError.GraphQLError( + `Cannot extend type "${typeName}" because it is not defined.` + + (0, _didYouMean.didYouMean)(suggestedTypes), + { + nodes: node.name, + }, + ), + ); + } } +} - getInterfaces() { - if (typeof this._interfaces === 'function') { - this._interfaces = this._interfaces(); - } +const defKindToExtKind = { + [_kinds.Kind.SCALAR_TYPE_DEFINITION]: _kinds.Kind.SCALAR_TYPE_EXTENSION, + [_kinds.Kind.OBJECT_TYPE_DEFINITION]: _kinds.Kind.OBJECT_TYPE_EXTENSION, + [_kinds.Kind.INTERFACE_TYPE_DEFINITION]: _kinds.Kind.INTERFACE_TYPE_EXTENSION, + [_kinds.Kind.UNION_TYPE_DEFINITION]: _kinds.Kind.UNION_TYPE_EXTENSION, + [_kinds.Kind.ENUM_TYPE_DEFINITION]: _kinds.Kind.ENUM_TYPE_EXTENSION, + [_kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION]: + _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION, +}; - return this._interfaces; +function typeToExtKind(type) { + if ((0, _definition.isScalarType)(type)) { + return _kinds.Kind.SCALAR_TYPE_EXTENSION; } - toConfig() { - return { - name: this.name, - description: this.description, - interfaces: this.getInterfaces(), - fields: fieldsToFieldsConfig(this.getFields()), - isTypeOf: this.isTypeOf, - extensions: this.extensions, - astNode: this.astNode, - extensionASTNodes: this.extensionASTNodes, - }; + if ((0, _definition.isObjectType)(type)) { + return _kinds.Kind.OBJECT_TYPE_EXTENSION; } - toString() { - return this.name; + if ((0, _definition.isInterfaceType)(type)) { + return _kinds.Kind.INTERFACE_TYPE_EXTENSION; } - toJSON() { - return this.toString(); + if ((0, _definition.isUnionType)(type)) { + return _kinds.Kind.UNION_TYPE_EXTENSION; } -} -exports.GraphQLObjectType = GraphQLObjectType; + if ((0, _definition.isEnumType)(type)) { + return _kinds.Kind.ENUM_TYPE_EXTENSION; + } -function defineInterfaces(config) { - var _config$interfaces; + if ((0, _definition.isInputObjectType)(type)) { + return _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION; + } + /* c8 ignore next 3 */ + // Not reachable. All possible types have been considered - const interfaces = resolveReadonlyArrayThunk( - (_config$interfaces = config.interfaces) !== null && - _config$interfaces !== void 0 - ? _config$interfaces - : [], - ); - Array.isArray(interfaces) || - (0, _devAssert.devAssert)( + false || + (0, _invariant.invariant)( false, - `${config.name} interfaces must be an Array or a function which returns an Array.`, + 'Unexpected type: ' + (0, _inspect.inspect)(type), ); - return interfaces; } -function defineFieldMap(config) { - const fieldMap = resolveObjMapThunk(config.fields); - isPlainObj(fieldMap) || - (0, _devAssert.devAssert)( - false, - `${config.name} fields must be an object with field names as keys or a function which returns such an object.`, - ); - return (0, _mapValue.mapValue)(fieldMap, (fieldConfig, fieldName) => { - var _fieldConfig$args; +function extensionKindToTypeName(kind) { + switch (kind) { + case _kinds.Kind.SCALAR_TYPE_EXTENSION: + return 'scalar'; - isPlainObj(fieldConfig) || - (0, _devAssert.devAssert)( - false, - `${config.name}.${fieldName} field config must be an object.`, - ); - fieldConfig.resolve == null || - typeof fieldConfig.resolve === 'function' || - (0, _devAssert.devAssert)( - false, - `${config.name}.${fieldName} field resolver must be a function if ` + - `provided, but got: ${(0, _inspect.inspect)(fieldConfig.resolve)}.`, - ); - const argsConfig = - (_fieldConfig$args = fieldConfig.args) !== null && - _fieldConfig$args !== void 0 - ? _fieldConfig$args - : {}; - isPlainObj(argsConfig) || - (0, _devAssert.devAssert)( - false, - `${config.name}.${fieldName} args must be an object with argument names as keys.`, - ); - return { - name: (0, _assertName.assertName)(fieldName), - description: fieldConfig.description, - type: fieldConfig.type, - args: defineArguments(argsConfig), - resolve: fieldConfig.resolve, - subscribe: fieldConfig.subscribe, - deprecationReason: fieldConfig.deprecationReason, - extensions: (0, _toObjMap.toObjMap)(fieldConfig.extensions), - astNode: fieldConfig.astNode, - }; - }); -} + case _kinds.Kind.OBJECT_TYPE_EXTENSION: + return 'object'; -function defineArguments(config) { - return Object.entries(config).map(([argName, argConfig]) => ({ - name: (0, _assertName.assertName)(argName), - description: argConfig.description, - type: argConfig.type, - defaultValue: argConfig.defaultValue, - deprecationReason: argConfig.deprecationReason, - extensions: (0, _toObjMap.toObjMap)(argConfig.extensions), - astNode: argConfig.astNode, - })); -} + case _kinds.Kind.INTERFACE_TYPE_EXTENSION: + return 'interface'; -function isPlainObj(obj) { - return (0, _isObjectLike.isObjectLike)(obj) && !Array.isArray(obj); -} + case _kinds.Kind.UNION_TYPE_EXTENSION: + return 'union'; -function fieldsToFieldsConfig(fields) { - return (0, _mapValue.mapValue)(fields, (field) => ({ - description: field.description, - type: field.type, - args: argsToArgsConfig(field.args), - resolve: field.resolve, - subscribe: field.subscribe, - deprecationReason: field.deprecationReason, - extensions: field.extensions, - astNode: field.astNode, - })); -} -/** - * @internal - */ + case _kinds.Kind.ENUM_TYPE_EXTENSION: + return 'enum'; -function argsToArgsConfig(args) { - return (0, _keyValMap.keyValMap)( - args, - (arg) => arg.name, - (arg) => ({ - description: arg.description, - type: arg.type, - defaultValue: arg.defaultValue, - deprecationReason: arg.deprecationReason, - extensions: arg.extensions, - astNode: arg.astNode, - }), - ); -} + case _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION: + return 'input object'; + // Not reachable. All possible types have been considered -function isRequiredArgument(arg) { - return isNonNullType(arg.type) && arg.defaultValue === undefined; + /* c8 ignore next */ + + default: + false || + (0, _invariant.invariant)( + false, + 'Unexpected kind: ' + (0, _inspect.inspect)(kind), + ); + } } -/** - * Interface Type Definition - * - * When a field can return one of a heterogeneous set of types, a Interface type - * is used to describe what types are possible, what fields are in common across - * all types, as well as a function to determine which type is actually used - * when the field is resolved. - * - * Example: - * - * ```ts - * const EntityType = new GraphQLInterfaceType({ - * name: 'Entity', - * fields: { - * name: { type: GraphQLString } - * } - * }); - * ``` - */ -class GraphQLInterfaceType { - constructor(config) { - var _config$extensionASTN3; - this.name = (0, _assertName.assertName)(config.name); - this.description = config.description; - this.resolveType = config.resolveType; - this.extensions = (0, _toObjMap.toObjMap)(config.extensions); - this.astNode = config.astNode; - this.extensionASTNodes = - (_config$extensionASTN3 = config.extensionASTNodes) !== null && - _config$extensionASTN3 !== void 0 - ? _config$extensionASTN3 - : []; - this._fields = defineFieldMap.bind(undefined, config); - this._interfaces = defineInterfaces.bind(undefined, config); - config.resolveType == null || - typeof config.resolveType === 'function' || - (0, _devAssert.devAssert)( - false, - `${this.name} must provide "resolveType" as a function, ` + - `but got: ${(0, _inspect.inspect)(config.resolveType)}.`, - ); - } +/***/ }), - get [Symbol.toStringTag]() { - return 'GraphQLInterfaceType'; - } +/***/ 57669: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - getFields() { - if (typeof this._fields === 'function') { - this._fields = this._fields(); - } +"use strict"; - return this._fields; - } - getInterfaces() { - if (typeof this._interfaces === 'function') { - this._interfaces = this._interfaces(); - } +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.ProvidedRequiredArgumentsOnDirectivesRule = + ProvidedRequiredArgumentsOnDirectivesRule; +exports.ProvidedRequiredArgumentsRule = ProvidedRequiredArgumentsRule; - return this._interfaces; - } +var _inspect = __nccwpck_require__(10102); - toConfig() { - return { - name: this.name, - description: this.description, - interfaces: this.getInterfaces(), - fields: fieldsToFieldsConfig(this.getFields()), - resolveType: this.resolveType, - extensions: this.extensions, - astNode: this.astNode, - extensionASTNodes: this.extensionASTNodes, - }; - } +var _keyMap = __nccwpck_require__(10711); - toString() { - return this.name; - } +var _GraphQLError = __nccwpck_require__(4797); - toJSON() { - return this.toString(); - } -} +var _kinds = __nccwpck_require__(11927); -exports.GraphQLInterfaceType = GraphQLInterfaceType; +var _printer = __nccwpck_require__(68203); + +var _definition = __nccwpck_require__(32150); + +var _directives = __nccwpck_require__(83614); /** - * Union Type Definition - * - * When a field can return one of a heterogeneous set of types, a Union type - * is used to describe what types are possible as well as providing a function - * to determine which type is actually used when the field is resolved. - * - * Example: + * Provided required arguments * - * ```ts - * const PetType = new GraphQLUnionType({ - * name: 'Pet', - * types: [ DogType, CatType ], - * resolveType(value) { - * if (value instanceof Dog) { - * return DogType; - * } - * if (value instanceof Cat) { - * return CatType; - * } - * } - * }); - * ``` + * A field or directive is only valid if all required (non-null without a + * default value) field arguments have been provided. */ -class GraphQLUnionType { - constructor(config) { - var _config$extensionASTN4; +function ProvidedRequiredArgumentsRule(context) { + return { + // eslint-disable-next-line new-cap + ...ProvidedRequiredArgumentsOnDirectivesRule(context), + Field: { + // Validate on leave to allow for deeper errors to appear first. + leave(fieldNode) { + var _fieldNode$arguments; - this.name = (0, _assertName.assertName)(config.name); - this.description = config.description; - this.resolveType = config.resolveType; - this.extensions = (0, _toObjMap.toObjMap)(config.extensions); - this.astNode = config.astNode; - this.extensionASTNodes = - (_config$extensionASTN4 = config.extensionASTNodes) !== null && - _config$extensionASTN4 !== void 0 - ? _config$extensionASTN4 - : []; - this._types = defineTypes.bind(undefined, config); - config.resolveType == null || - typeof config.resolveType === 'function' || - (0, _devAssert.devAssert)( - false, - `${this.name} must provide "resolveType" as a function, ` + - `but got: ${(0, _inspect.inspect)(config.resolveType)}.`, - ); - } + const fieldDef = context.getFieldDef(); - get [Symbol.toStringTag]() { - return 'GraphQLUnionType'; - } + if (!fieldDef) { + return false; + } - getTypes() { - if (typeof this._types === 'function') { - this._types = this._types(); - } + const providedArgs = new Set( // FIXME: https://github.com/graphql/graphql-js/issues/2203 + /* c8 ignore next */ + (_fieldNode$arguments = fieldNode.arguments) === null || + _fieldNode$arguments === void 0 + ? void 0 + : _fieldNode$arguments.map((arg) => arg.name.value), + ); - return this._types; - } + for (const argDef of fieldDef.args) { + if ( + !providedArgs.has(argDef.name) && + (0, _definition.isRequiredArgument)(argDef) + ) { + const argTypeStr = (0, _inspect.inspect)(argDef.type); + context.reportError( + new _GraphQLError.GraphQLError( + `Field "${fieldDef.name}" argument "${argDef.name}" of type "${argTypeStr}" is required, but it was not provided.`, + { + nodes: fieldNode, + }, + ), + ); + } + } + }, + }, + }; +} +/** + * @internal + */ - toConfig() { - return { - name: this.name, - description: this.description, - types: this.getTypes(), - resolveType: this.resolveType, - extensions: this.extensions, - astNode: this.astNode, - extensionASTNodes: this.extensionASTNodes, - }; - } +function ProvidedRequiredArgumentsOnDirectivesRule(context) { + var _schema$getDirectives; - toString() { - return this.name; + const requiredArgsMap = Object.create(null); + const schema = context.getSchema(); + const definedDirectives = + (_schema$getDirectives = + schema === null || schema === void 0 + ? void 0 + : schema.getDirectives()) !== null && _schema$getDirectives !== void 0 + ? _schema$getDirectives + : _directives.specifiedDirectives; + + for (const directive of definedDirectives) { + requiredArgsMap[directive.name] = (0, _keyMap.keyMap)( + directive.args.filter(_definition.isRequiredArgument), + (arg) => arg.name, + ); } - toJSON() { - return this.toString(); + const astDefinitions = context.getDocument().definitions; + + for (const def of astDefinitions) { + if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + var _def$arguments; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const argNodes = + (_def$arguments = def.arguments) !== null && _def$arguments !== void 0 + ? _def$arguments + : []; + requiredArgsMap[def.name.value] = (0, _keyMap.keyMap)( + argNodes.filter(isRequiredArgumentNode), + (arg) => arg.name.value, + ); + } } -} -exports.GraphQLUnionType = GraphQLUnionType; + return { + Directive: { + // Validate on leave to allow for deeper errors to appear first. + leave(directiveNode) { + const directiveName = directiveNode.name.value; + const requiredArgs = requiredArgsMap[directiveName]; -function defineTypes(config) { - const types = resolveReadonlyArrayThunk(config.types); - Array.isArray(types) || - (0, _devAssert.devAssert)( - false, - `Must provide Array of types or a function which returns such an array for Union ${config.name}.`, - ); - return types; + if (requiredArgs) { + var _directiveNode$argume; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const argNodes = + (_directiveNode$argume = directiveNode.arguments) !== null && + _directiveNode$argume !== void 0 + ? _directiveNode$argume + : []; + const argNodeMap = new Set(argNodes.map((arg) => arg.name.value)); + + for (const [argName, argDef] of Object.entries(requiredArgs)) { + if (!argNodeMap.has(argName)) { + const argType = (0, _definition.isType)(argDef.type) + ? (0, _inspect.inspect)(argDef.type) + : (0, _printer.print)(argDef.type); + context.reportError( + new _GraphQLError.GraphQLError( + `Directive "@${directiveName}" argument "${argName}" of type "${argType}" is required, but it was not provided.`, + { + nodes: directiveNode, + }, + ), + ); + } + } + } + }, + }, + }; +} + +function isRequiredArgumentNode(arg) { + return ( + arg.type.kind === _kinds.Kind.NON_NULL_TYPE && arg.defaultValue == null + ); } + +/***/ }), + +/***/ 16830: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.ScalarLeafsRule = ScalarLeafsRule; + +var _inspect = __nccwpck_require__(10102); + +var _GraphQLError = __nccwpck_require__(4797); + +var _definition = __nccwpck_require__(32150); + /** - * Enum Type Definition - * - * Some leaf values of requests and input values are Enums. GraphQL serializes - * Enum values as strings, however internally Enums can be represented by any - * kind of type, often integers. - * - * Example: - * - * ```ts - * const RGBType = new GraphQLEnumType({ - * name: 'RGB', - * values: { - * RED: { value: 0 }, - * GREEN: { value: 1 }, - * BLUE: { value: 2 } - * } - * }); - * ``` + * Scalar leafs * - * Note: If a value is not provided in a definition, the name of the enum value - * will be used as its internal value. + * A GraphQL document is valid only if all leaf fields (fields without + * sub selections) are of scalar or enum types. */ -class GraphQLEnumType { - /* */ - constructor(config) { - var _config$extensionASTN5; +function ScalarLeafsRule(context) { + return { + Field(node) { + const type = context.getType(); + const selectionSet = node.selectionSet; - this.name = (0, _assertName.assertName)(config.name); - this.description = config.description; - this.extensions = (0, _toObjMap.toObjMap)(config.extensions); - this.astNode = config.astNode; - this.extensionASTNodes = - (_config$extensionASTN5 = config.extensionASTNodes) !== null && - _config$extensionASTN5 !== void 0 - ? _config$extensionASTN5 - : []; - this._values = - typeof config.values === 'function' - ? config.values - : defineEnumValues(this.name, config.values); - this._valueLookup = null; - this._nameLookup = null; - } + if (type) { + if ((0, _definition.isLeafType)((0, _definition.getNamedType)(type))) { + if (selectionSet) { + const fieldName = node.name.value; + const typeStr = (0, _inspect.inspect)(type); + context.reportError( + new _GraphQLError.GraphQLError( + `Field "${fieldName}" must not have a selection since type "${typeStr}" has no subfields.`, + { + nodes: selectionSet, + }, + ), + ); + } + } else if (!selectionSet) { + const fieldName = node.name.value; + const typeStr = (0, _inspect.inspect)(type); + context.reportError( + new _GraphQLError.GraphQLError( + `Field "${fieldName}" of type "${typeStr}" must have a selection of subfields. Did you mean "${fieldName} { ... }"?`, + { + nodes: node, + }, + ), + ); + } else if (selectionSet.selections.length === 0) { + const fieldName = node.name.value; + const typeStr = (0, _inspect.inspect)(type); + context.reportError( + new _GraphQLError.GraphQLError( + `Field "${fieldName}" of type "${typeStr}" must have at least one field selected.`, + { + nodes: node, + }, + ), + ); + } + } + }, + }; +} - get [Symbol.toStringTag]() { - return 'GraphQLEnumType'; - } - getValues() { - if (typeof this._values === 'function') { - this._values = defineEnumValues(this.name, this._values()); - } +/***/ }), - return this._values; - } +/***/ 4365: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - getValue(name) { - if (this._nameLookup === null) { - this._nameLookup = (0, _keyMap.keyMap)( - this.getValues(), - (value) => value.name, - ); - } +"use strict"; - return this._nameLookup[name]; - } - serialize(outputValue) { - if (this._valueLookup === null) { - this._valueLookup = new Map( - this.getValues().map((enumValue) => [enumValue.value, enumValue]), - ); - } +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.SingleFieldSubscriptionsRule = SingleFieldSubscriptionsRule; - const enumValue = this._valueLookup.get(outputValue); +var _GraphQLError = __nccwpck_require__(4797); - if (enumValue === undefined) { - throw new _GraphQLError.GraphQLError( - `Enum "${this.name}" cannot represent value: ${(0, _inspect.inspect)( - outputValue, - )}`, - ); - } +var _kinds = __nccwpck_require__(11927); - return enumValue.name; - } +var _collectFields = __nccwpck_require__(49942); - parseValue(inputValue) /* T */ - { - if (typeof inputValue !== 'string') { - const valueStr = (0, _inspect.inspect)(inputValue); - throw new _GraphQLError.GraphQLError( - `Enum "${this.name}" cannot represent non-string value: ${valueStr}.` + - didYouMeanEnumValue(this, valueStr), - ); - } +/** + * Subscriptions must only include a non-introspection field. + * + * A GraphQL subscription is valid only if it contains a single root field and + * that root field is not an introspection field. + * + * See https://spec.graphql.org/draft/#sec-Single-root-field + */ +function SingleFieldSubscriptionsRule(context) { + return { + OperationDefinition(node) { + if (node.operation === 'subscription') { + const schema = context.getSchema(); + const subscriptionType = schema.getSubscriptionType(); - const enumValue = this.getValue(inputValue); + if (subscriptionType) { + const operationName = node.name ? node.name.value : null; + const variableValues = Object.create(null); + const document = context.getDocument(); + const fragments = Object.create(null); - if (enumValue == null) { - throw new _GraphQLError.GraphQLError( - `Value "${inputValue}" does not exist in "${this.name}" enum.` + - didYouMeanEnumValue(this, inputValue), - ); - } + for (const definition of document.definitions) { + if (definition.kind === _kinds.Kind.FRAGMENT_DEFINITION) { + fragments[definition.name.value] = definition; + } + } - return enumValue.value; - } + const fields = (0, _collectFields.collectFields)( + schema, + fragments, + variableValues, + subscriptionType, + node.selectionSet, + ); - parseLiteral(valueNode, _variables) /* T */ - { - // Note: variables will be resolved to a value before calling this function. - if (valueNode.kind !== _kinds.Kind.ENUM) { - const valueStr = (0, _printer.print)(valueNode); - throw new _GraphQLError.GraphQLError( - `Enum "${this.name}" cannot represent non-enum value: ${valueStr}.` + - didYouMeanEnumValue(this, valueStr), - { - nodes: valueNode, - }, - ); - } + if (fields.size > 1) { + const fieldSelectionLists = [...fields.values()]; + const extraFieldSelectionLists = fieldSelectionLists.slice(1); + const extraFieldSelections = extraFieldSelectionLists.flat(); + context.reportError( + new _GraphQLError.GraphQLError( + operationName != null + ? `Subscription "${operationName}" must select only one top level field.` + : 'Anonymous Subscription must select only one top level field.', + { + nodes: extraFieldSelections, + }, + ), + ); + } - const enumValue = this.getValue(valueNode.value); + for (const fieldNodes of fields.values()) { + const field = fieldNodes[0]; + const fieldName = field.name.value; - if (enumValue == null) { - const valueStr = (0, _printer.print)(valueNode); - throw new _GraphQLError.GraphQLError( - `Value "${valueStr}" does not exist in "${this.name}" enum.` + - didYouMeanEnumValue(this, valueStr), - { - nodes: valueNode, - }, - ); - } + if (fieldName.startsWith('__')) { + context.reportError( + new _GraphQLError.GraphQLError( + operationName != null + ? `Subscription "${operationName}" must not select an introspection top level field.` + : 'Anonymous Subscription must not select an introspection top level field.', + { + nodes: fieldNodes, + }, + ), + ); + } + } + } + } + }, + }; +} - return enumValue.value; - } - toConfig() { - const values = (0, _keyValMap.keyValMap)( - this.getValues(), - (value) => value.name, - (value) => ({ - description: value.description, - value: value.value, - deprecationReason: value.deprecationReason, - extensions: value.extensions, - astNode: value.astNode, - }), - ); - return { - name: this.name, - description: this.description, - values, - extensions: this.extensions, - astNode: this.astNode, - extensionASTNodes: this.extensionASTNodes, - }; - } +/***/ }), - toString() { - return this.name; - } +/***/ 55104: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - toJSON() { - return this.toString(); - } -} +"use strict"; -exports.GraphQLEnumType = GraphQLEnumType; -function didYouMeanEnumValue(enumType, unknownValueStr) { - const allNames = enumType.getValues().map((value) => value.name); - const suggestedValues = (0, _suggestionList.suggestionList)( - unknownValueStr, - allNames, - ); - return (0, _didYouMean.didYouMean)('the enum value', suggestedValues); -} +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.UniqueArgumentDefinitionNamesRule = UniqueArgumentDefinitionNamesRule; -function defineEnumValues(typeName, valueMap) { - isPlainObj(valueMap) || - (0, _devAssert.devAssert)( - false, - `${typeName} values must be an object with value names as keys.`, - ); - return Object.entries(valueMap).map(([valueName, valueConfig]) => { - isPlainObj(valueConfig) || - (0, _devAssert.devAssert)( - false, - `${typeName}.${valueName} must refer to an object with a "value" key ` + - `representing an internal value but got: ${(0, _inspect.inspect)( - valueConfig, - )}.`, - ); - return { - name: (0, _assertName.assertEnumValueName)(valueName), - description: valueConfig.description, - value: valueConfig.value !== undefined ? valueConfig.value : valueName, - deprecationReason: valueConfig.deprecationReason, - extensions: (0, _toObjMap.toObjMap)(valueConfig.extensions), - astNode: valueConfig.astNode, - }; - }); -} +var _groupBy = __nccwpck_require__(93173); + +var _GraphQLError = __nccwpck_require__(4797); /** - * Input Object Type Definition - * - * An input object defines a structured collection of fields which may be - * supplied to a field argument. - * - * Using `NonNull` will ensure that a value must be provided by the query - * - * Example: + * Unique argument definition names * - * ```ts - * const GeoPoint = new GraphQLInputObjectType({ - * name: 'GeoPoint', - * fields: { - * lat: { type: new GraphQLNonNull(GraphQLFloat) }, - * lon: { type: new GraphQLNonNull(GraphQLFloat) }, - * alt: { type: GraphQLFloat, defaultValue: 0 }, - * } - * }); - * ``` + * A GraphQL Object or Interface type is only valid if all its fields have uniquely named arguments. + * A GraphQL Directive is only valid if all its arguments are uniquely named. */ -class GraphQLInputObjectType { - constructor(config) { - var _config$extensionASTN6, _config$isOneOf; +function UniqueArgumentDefinitionNamesRule(context) { + return { + DirectiveDefinition(directiveNode) { + var _directiveNode$argume; - this.name = (0, _assertName.assertName)(config.name); - this.description = config.description; - this.extensions = (0, _toObjMap.toObjMap)(config.extensions); - this.astNode = config.astNode; - this.extensionASTNodes = - (_config$extensionASTN6 = config.extensionASTNodes) !== null && - _config$extensionASTN6 !== void 0 - ? _config$extensionASTN6 - : []; - this.isOneOf = - (_config$isOneOf = config.isOneOf) !== null && _config$isOneOf !== void 0 - ? _config$isOneOf - : false; - this._fields = defineInputFieldMap.bind(undefined, config); - } + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const argumentNodes = + (_directiveNode$argume = directiveNode.arguments) !== null && + _directiveNode$argume !== void 0 + ? _directiveNode$argume + : []; + return checkArgUniqueness(`@${directiveNode.name.value}`, argumentNodes); + }, + + InterfaceTypeDefinition: checkArgUniquenessPerField, + InterfaceTypeExtension: checkArgUniquenessPerField, + ObjectTypeDefinition: checkArgUniquenessPerField, + ObjectTypeExtension: checkArgUniquenessPerField, + }; + + function checkArgUniquenessPerField(typeNode) { + var _typeNode$fields; - get [Symbol.toStringTag]() { - return 'GraphQLInputObjectType'; - } + const typeName = typeNode.name.value; // FIXME: https://github.com/graphql/graphql-js/issues/2203 - getFields() { - if (typeof this._fields === 'function') { - this._fields = this._fields(); - } + /* c8 ignore next */ - return this._fields; - } + const fieldNodes = + (_typeNode$fields = typeNode.fields) !== null && + _typeNode$fields !== void 0 + ? _typeNode$fields + : []; - toConfig() { - const fields = (0, _mapValue.mapValue)(this.getFields(), (field) => ({ - description: field.description, - type: field.type, - defaultValue: field.defaultValue, - deprecationReason: field.deprecationReason, - extensions: field.extensions, - astNode: field.astNode, - })); - return { - name: this.name, - description: this.description, - fields, - extensions: this.extensions, - astNode: this.astNode, - extensionASTNodes: this.extensionASTNodes, - isOneOf: this.isOneOf, - }; - } + for (const fieldDef of fieldNodes) { + var _fieldDef$arguments; - toString() { - return this.name; - } + const fieldName = fieldDef.name.value; // FIXME: https://github.com/graphql/graphql-js/issues/2203 - toJSON() { - return this.toString(); - } -} + /* c8 ignore next */ -exports.GraphQLInputObjectType = GraphQLInputObjectType; + const argumentNodes = + (_fieldDef$arguments = fieldDef.arguments) !== null && + _fieldDef$arguments !== void 0 + ? _fieldDef$arguments + : []; + checkArgUniqueness(`${typeName}.${fieldName}`, argumentNodes); + } -function defineInputFieldMap(config) { - const fieldMap = resolveObjMapThunk(config.fields); - isPlainObj(fieldMap) || - (0, _devAssert.devAssert)( - false, - `${config.name} fields must be an object with field names as keys or a function which returns such an object.`, + return false; + } + + function checkArgUniqueness(parentName, argumentNodes) { + const seenArgs = (0, _groupBy.groupBy)( + argumentNodes, + (arg) => arg.name.value, ); - return (0, _mapValue.mapValue)(fieldMap, (fieldConfig, fieldName) => { - !('resolve' in fieldConfig) || - (0, _devAssert.devAssert)( - false, - `${config.name}.${fieldName} field has a resolve property, but Input Types cannot define resolvers.`, - ); - return { - name: (0, _assertName.assertName)(fieldName), - description: fieldConfig.description, - type: fieldConfig.type, - defaultValue: fieldConfig.defaultValue, - deprecationReason: fieldConfig.deprecationReason, - extensions: (0, _toObjMap.toObjMap)(fieldConfig.extensions), - astNode: fieldConfig.astNode, - }; - }); -} -function isRequiredInputField(field) { - return isNonNullType(field.type) && field.defaultValue === undefined; + for (const [argName, argNodes] of seenArgs) { + if (argNodes.length > 1) { + context.reportError( + new _GraphQLError.GraphQLError( + `Argument "${parentName}(${argName}:)" can only be defined once.`, + { + nodes: argNodes.map((node) => node.name), + }, + ), + ); + } + } + + return false; + } } /***/ }), -/***/ 83614: +/***/ 45799: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -286693,244 +288607,226 @@ function isRequiredInputField(field) { Object.defineProperty(exports, "__esModule", ({ value: true, })); -exports.GraphQLSpecifiedByDirective = - exports.GraphQLSkipDirective = - exports.GraphQLOneOfDirective = - exports.GraphQLIncludeDirective = - exports.GraphQLDirective = - exports.GraphQLDeprecatedDirective = - exports.DEFAULT_DEPRECATION_REASON = - void 0; -exports.assertDirective = assertDirective; -exports.isDirective = isDirective; -exports.isSpecifiedDirective = isSpecifiedDirective; -exports.specifiedDirectives = void 0; +exports.UniqueArgumentNamesRule = UniqueArgumentNamesRule; -var _devAssert = __nccwpck_require__(46514); +var _groupBy = __nccwpck_require__(93173); -var _inspect = __nccwpck_require__(10102); +var _GraphQLError = __nccwpck_require__(4797); -var _instanceOf = __nccwpck_require__(93481); +/** + * Unique argument names + * + * A GraphQL field or directive is only valid if all supplied arguments are + * uniquely named. + * + * See https://spec.graphql.org/draft/#sec-Argument-Names + */ +function UniqueArgumentNamesRule(context) { + return { + Field: checkArgUniqueness, + Directive: checkArgUniqueness, + }; -var _isObjectLike = __nccwpck_require__(95865); + function checkArgUniqueness(parentNode) { + var _parentNode$arguments; -var _toObjMap = __nccwpck_require__(74728); + // FIXME: https://github.com/graphql/graphql-js/issues/2203 -var _directiveLocation = __nccwpck_require__(71553); + /* c8 ignore next */ + const argumentNodes = + (_parentNode$arguments = parentNode.arguments) !== null && + _parentNode$arguments !== void 0 + ? _parentNode$arguments + : []; + const seenArgs = (0, _groupBy.groupBy)( + argumentNodes, + (arg) => arg.name.value, + ); -var _assertName = __nccwpck_require__(74947); + for (const [argName, argNodes] of seenArgs) { + if (argNodes.length > 1) { + context.reportError( + new _GraphQLError.GraphQLError( + `There can be only one argument named "${argName}".`, + { + nodes: argNodes.map((node) => node.name), + }, + ), + ); + } + } + } +} -var _definition = __nccwpck_require__(32150); -var _scalars = __nccwpck_require__(93145); +/***/ }), -/** - * Test if the given value is a GraphQL directive. - */ -function isDirective(directive) { - return (0, _instanceOf.instanceOf)(directive, GraphQLDirective); -} +/***/ 17074: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function assertDirective(directive) { - if (!isDirective(directive)) { - throw new Error( - `Expected ${(0, _inspect.inspect)(directive)} to be a GraphQL directive.`, - ); - } +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.UniqueDirectiveNamesRule = UniqueDirectiveNamesRule; + +var _GraphQLError = __nccwpck_require__(4797); - return directive; -} /** - * Custom extensions + * Unique directive names * - * @remarks - * Use a unique identifier name for your extension, for example the name of - * your library or project. Do not use a shortened identifier as this increases - * the risk of conflicts. We recommend you add at most one extension field, - * an object which can contain all the values you need. + * A GraphQL document is only valid if all defined directives have unique names. */ +function UniqueDirectiveNamesRule(context) { + const knownDirectiveNames = Object.create(null); + const schema = context.getSchema(); + return { + DirectiveDefinition(node) { + const directiveName = node.name.value; -/** - * Directives are used by the GraphQL runtime as a way of modifying execution - * behavior. Type system creators will usually not create these directly. - */ -class GraphQLDirective { - constructor(config) { - var _config$isRepeatable, _config$args; + if ( + schema !== null && + schema !== void 0 && + schema.getDirective(directiveName) + ) { + context.reportError( + new _GraphQLError.GraphQLError( + `Directive "@${directiveName}" already exists in the schema. It cannot be redefined.`, + { + nodes: node.name, + }, + ), + ); + return; + } - this.name = (0, _assertName.assertName)(config.name); - this.description = config.description; - this.locations = config.locations; - this.isRepeatable = - (_config$isRepeatable = config.isRepeatable) !== null && - _config$isRepeatable !== void 0 - ? _config$isRepeatable - : false; - this.extensions = (0, _toObjMap.toObjMap)(config.extensions); - this.astNode = config.astNode; - Array.isArray(config.locations) || - (0, _devAssert.devAssert)( - false, - `@${config.name} locations must be an Array.`, - ); - const args = - (_config$args = config.args) !== null && _config$args !== void 0 - ? _config$args - : {}; - ((0, _isObjectLike.isObjectLike)(args) && !Array.isArray(args)) || - (0, _devAssert.devAssert)( - false, - `@${config.name} args must be an object with argument names as keys.`, - ); - this.args = (0, _definition.defineArguments)(args); - } + if (knownDirectiveNames[directiveName]) { + context.reportError( + new _GraphQLError.GraphQLError( + `There can be only one directive named "@${directiveName}".`, + { + nodes: [knownDirectiveNames[directiveName], node.name], + }, + ), + ); + } else { + knownDirectiveNames[directiveName] = node.name; + } - get [Symbol.toStringTag]() { - return 'GraphQLDirective'; - } + return false; + }, + }; +} - toConfig() { - return { - name: this.name, - description: this.description, - locations: this.locations, - args: (0, _definition.argsToArgsConfig)(this.args), - isRepeatable: this.isRepeatable, - extensions: this.extensions, - astNode: this.astNode, - }; - } - toString() { - return '@' + this.name; - } +/***/ }), - toJSON() { - return this.toString(); - } -} +/***/ 61944: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -exports.GraphQLDirective = GraphQLDirective; +"use strict"; -/** - * Used to conditionally include fields or fragments. - */ -const GraphQLIncludeDirective = new GraphQLDirective({ - name: 'include', - description: - 'Directs the executor to include this field or fragment only when the `if` argument is true.', - locations: [ - _directiveLocation.DirectiveLocation.FIELD, - _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, - _directiveLocation.DirectiveLocation.INLINE_FRAGMENT, - ], - args: { - if: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), - description: 'Included when true.', - }, - }, -}); -/** - * Used to conditionally skip (exclude) fields or fragments. - */ -exports.GraphQLIncludeDirective = GraphQLIncludeDirective; -const GraphQLSkipDirective = new GraphQLDirective({ - name: 'skip', - description: - 'Directs the executor to skip this field or fragment when the `if` argument is true.', - locations: [ - _directiveLocation.DirectiveLocation.FIELD, - _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, - _directiveLocation.DirectiveLocation.INLINE_FRAGMENT, - ], - args: { - if: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), - description: 'Skipped when true.', - }, - }, -}); -/** - * Constant string used for default reason for a deprecation. - */ +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.UniqueDirectivesPerLocationRule = UniqueDirectivesPerLocationRule; -exports.GraphQLSkipDirective = GraphQLSkipDirective; -const DEFAULT_DEPRECATION_REASON = 'No longer supported'; -/** - * Used to declare element of a GraphQL schema as deprecated. - */ +var _GraphQLError = __nccwpck_require__(4797); -exports.DEFAULT_DEPRECATION_REASON = DEFAULT_DEPRECATION_REASON; -const GraphQLDeprecatedDirective = new GraphQLDirective({ - name: 'deprecated', - description: 'Marks an element of a GraphQL schema as no longer supported.', - locations: [ - _directiveLocation.DirectiveLocation.FIELD_DEFINITION, - _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION, - _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION, - _directiveLocation.DirectiveLocation.ENUM_VALUE, - ], - args: { - reason: { - type: _scalars.GraphQLString, - description: - 'Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted using the Markdown syntax, as specified by [CommonMark](https://commonmark.org/).', - defaultValue: DEFAULT_DEPRECATION_REASON, - }, - }, -}); -/** - * Used to provide a URL for specifying the behavior of custom scalar definitions. - */ +var _kinds = __nccwpck_require__(11927); -exports.GraphQLDeprecatedDirective = GraphQLDeprecatedDirective; -const GraphQLSpecifiedByDirective = new GraphQLDirective({ - name: 'specifiedBy', - description: 'Exposes a URL that specifies the behavior of this scalar.', - locations: [_directiveLocation.DirectiveLocation.SCALAR], - args: { - url: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLString), - description: 'The URL that specifies the behavior of this scalar.', - }, - }, -}); -/** - * Used to indicate an Input Object is a OneOf Input Object. - */ +var _predicates = __nccwpck_require__(20535); + +var _directives = __nccwpck_require__(83614); -exports.GraphQLSpecifiedByDirective = GraphQLSpecifiedByDirective; -const GraphQLOneOfDirective = new GraphQLDirective({ - name: 'oneOf', - description: - 'Indicates exactly one field must be supplied and this field must not be `null`.', - locations: [_directiveLocation.DirectiveLocation.INPUT_OBJECT], - args: {}, -}); /** - * The full list of specified directives. + * Unique directive names per location + * + * A GraphQL document is only valid if all non-repeatable directives at + * a given location are uniquely named. + * + * See https://spec.graphql.org/draft/#sec-Directives-Are-Unique-Per-Location */ +function UniqueDirectivesPerLocationRule(context) { + const uniqueDirectiveMap = Object.create(null); + const schema = context.getSchema(); + const definedDirectives = schema + ? schema.getDirectives() + : _directives.specifiedDirectives; -exports.GraphQLOneOfDirective = GraphQLOneOfDirective; -const specifiedDirectives = Object.freeze([ - GraphQLIncludeDirective, - GraphQLSkipDirective, - GraphQLDeprecatedDirective, - GraphQLSpecifiedByDirective, - GraphQLOneOfDirective, -]); -exports.specifiedDirectives = specifiedDirectives; + for (const directive of definedDirectives) { + uniqueDirectiveMap[directive.name] = !directive.isRepeatable; + } -function isSpecifiedDirective(directive) { - return specifiedDirectives.some(({ name }) => name === directive.name); + const astDefinitions = context.getDocument().definitions; + + for (const def of astDefinitions) { + if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + uniqueDirectiveMap[def.name.value] = !def.repeatable; + } + } + + const schemaDirectives = Object.create(null); + const typeDirectivesMap = Object.create(null); + return { + // Many different AST nodes may contain directives. Rather than listing + // them all, just listen for entering any node, and check to see if it + // defines any directives. + enter(node) { + if (!('directives' in node) || !node.directives) { + return; + } + + let seenDirectives; + + if ( + node.kind === _kinds.Kind.SCHEMA_DEFINITION || + node.kind === _kinds.Kind.SCHEMA_EXTENSION + ) { + seenDirectives = schemaDirectives; + } else if ( + (0, _predicates.isTypeDefinitionNode)(node) || + (0, _predicates.isTypeExtensionNode)(node) + ) { + const typeName = node.name.value; + seenDirectives = typeDirectivesMap[typeName]; + + if (seenDirectives === undefined) { + typeDirectivesMap[typeName] = seenDirectives = Object.create(null); + } + } else { + seenDirectives = Object.create(null); + } + + for (const directive of node.directives) { + const directiveName = directive.name.value; + + if (uniqueDirectiveMap[directiveName]) { + if (seenDirectives[directiveName]) { + context.reportError( + new _GraphQLError.GraphQLError( + `The directive "@${directiveName}" can only be used once at this location.`, + { + nodes: [seenDirectives[directiveName], directive], + }, + ), + ); + } else { + seenDirectives[directiveName] = directive; + } + } + } + }, + }; } /***/ }), -/***/ 63280: +/***/ 44437: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -286939,559 +288835,176 @@ function isSpecifiedDirective(directive) { Object.defineProperty(exports, "__esModule", ({ value: true, })); -Object.defineProperty(exports, "DEFAULT_DEPRECATION_REASON", ({ - enumerable: true, - get: function () { - return _directives.DEFAULT_DEPRECATION_REASON; - }, -})); -Object.defineProperty(exports, "GRAPHQL_MAX_INT", ({ - enumerable: true, - get: function () { - return _scalars.GRAPHQL_MAX_INT; - }, -})); -Object.defineProperty(exports, "GRAPHQL_MIN_INT", ({ - enumerable: true, - get: function () { - return _scalars.GRAPHQL_MIN_INT; - }, -})); -Object.defineProperty(exports, "GraphQLBoolean", ({ - enumerable: true, - get: function () { - return _scalars.GraphQLBoolean; - }, -})); -Object.defineProperty(exports, "GraphQLDeprecatedDirective", ({ - enumerable: true, - get: function () { - return _directives.GraphQLDeprecatedDirective; - }, -})); -Object.defineProperty(exports, "GraphQLDirective", ({ - enumerable: true, - get: function () { - return _directives.GraphQLDirective; - }, -})); -Object.defineProperty(exports, "GraphQLEnumType", ({ - enumerable: true, - get: function () { - return _definition.GraphQLEnumType; - }, -})); -Object.defineProperty(exports, "GraphQLFloat", ({ - enumerable: true, - get: function () { - return _scalars.GraphQLFloat; - }, -})); -Object.defineProperty(exports, "GraphQLID", ({ - enumerable: true, - get: function () { - return _scalars.GraphQLID; - }, -})); -Object.defineProperty(exports, "GraphQLIncludeDirective", ({ - enumerable: true, - get: function () { - return _directives.GraphQLIncludeDirective; - }, -})); -Object.defineProperty(exports, "GraphQLInputObjectType", ({ - enumerable: true, - get: function () { - return _definition.GraphQLInputObjectType; - }, -})); -Object.defineProperty(exports, "GraphQLInt", ({ - enumerable: true, - get: function () { - return _scalars.GraphQLInt; - }, -})); -Object.defineProperty(exports, "GraphQLInterfaceType", ({ - enumerable: true, - get: function () { - return _definition.GraphQLInterfaceType; - }, -})); -Object.defineProperty(exports, "GraphQLList", ({ - enumerable: true, - get: function () { - return _definition.GraphQLList; - }, -})); -Object.defineProperty(exports, "GraphQLNonNull", ({ - enumerable: true, - get: function () { - return _definition.GraphQLNonNull; - }, -})); -Object.defineProperty(exports, "GraphQLObjectType", ({ - enumerable: true, - get: function () { - return _definition.GraphQLObjectType; - }, -})); -Object.defineProperty(exports, "GraphQLOneOfDirective", ({ - enumerable: true, - get: function () { - return _directives.GraphQLOneOfDirective; - }, -})); -Object.defineProperty(exports, "GraphQLScalarType", ({ - enumerable: true, - get: function () { - return _definition.GraphQLScalarType; - }, -})); -Object.defineProperty(exports, "GraphQLSchema", ({ - enumerable: true, - get: function () { - return _schema.GraphQLSchema; - }, -})); -Object.defineProperty(exports, "GraphQLSkipDirective", ({ - enumerable: true, - get: function () { - return _directives.GraphQLSkipDirective; - }, -})); -Object.defineProperty(exports, "GraphQLSpecifiedByDirective", ({ - enumerable: true, - get: function () { - return _directives.GraphQLSpecifiedByDirective; - }, -})); -Object.defineProperty(exports, "GraphQLString", ({ - enumerable: true, - get: function () { - return _scalars.GraphQLString; - }, -})); -Object.defineProperty(exports, "GraphQLUnionType", ({ - enumerable: true, - get: function () { - return _definition.GraphQLUnionType; - }, -})); -Object.defineProperty(exports, "SchemaMetaFieldDef", ({ - enumerable: true, - get: function () { - return _introspection.SchemaMetaFieldDef; - }, -})); -Object.defineProperty(exports, "TypeKind", ({ - enumerable: true, - get: function () { - return _introspection.TypeKind; - }, -})); -Object.defineProperty(exports, "TypeMetaFieldDef", ({ - enumerable: true, - get: function () { - return _introspection.TypeMetaFieldDef; - }, -})); -Object.defineProperty(exports, "TypeNameMetaFieldDef", ({ - enumerable: true, - get: function () { - return _introspection.TypeNameMetaFieldDef; - }, -})); -Object.defineProperty(exports, "__Directive", ({ - enumerable: true, - get: function () { - return _introspection.__Directive; - }, -})); -Object.defineProperty(exports, "__DirectiveLocation", ({ - enumerable: true, - get: function () { - return _introspection.__DirectiveLocation; - }, -})); -Object.defineProperty(exports, "__EnumValue", ({ - enumerable: true, - get: function () { - return _introspection.__EnumValue; - }, -})); -Object.defineProperty(exports, "__Field", ({ - enumerable: true, - get: function () { - return _introspection.__Field; - }, -})); -Object.defineProperty(exports, "__InputValue", ({ - enumerable: true, - get: function () { - return _introspection.__InputValue; - }, -})); -Object.defineProperty(exports, "__Schema", ({ - enumerable: true, - get: function () { - return _introspection.__Schema; - }, -})); -Object.defineProperty(exports, "__Type", ({ - enumerable: true, - get: function () { - return _introspection.__Type; - }, -})); -Object.defineProperty(exports, "__TypeKind", ({ - enumerable: true, - get: function () { - return _introspection.__TypeKind; - }, -})); -Object.defineProperty(exports, "assertAbstractType", ({ - enumerable: true, - get: function () { - return _definition.assertAbstractType; - }, -})); -Object.defineProperty(exports, "assertCompositeType", ({ - enumerable: true, - get: function () { - return _definition.assertCompositeType; - }, -})); -Object.defineProperty(exports, "assertDirective", ({ - enumerable: true, - get: function () { - return _directives.assertDirective; - }, -})); -Object.defineProperty(exports, "assertEnumType", ({ - enumerable: true, - get: function () { - return _definition.assertEnumType; - }, -})); -Object.defineProperty(exports, "assertEnumValueName", ({ - enumerable: true, - get: function () { - return _assertName.assertEnumValueName; - }, -})); -Object.defineProperty(exports, "assertInputObjectType", ({ - enumerable: true, - get: function () { - return _definition.assertInputObjectType; - }, -})); -Object.defineProperty(exports, "assertInputType", ({ - enumerable: true, - get: function () { - return _definition.assertInputType; - }, -})); -Object.defineProperty(exports, "assertInterfaceType", ({ - enumerable: true, - get: function () { - return _definition.assertInterfaceType; - }, -})); -Object.defineProperty(exports, "assertLeafType", ({ - enumerable: true, - get: function () { - return _definition.assertLeafType; - }, -})); -Object.defineProperty(exports, "assertListType", ({ - enumerable: true, - get: function () { - return _definition.assertListType; - }, -})); -Object.defineProperty(exports, "assertName", ({ - enumerable: true, - get: function () { - return _assertName.assertName; - }, -})); -Object.defineProperty(exports, "assertNamedType", ({ - enumerable: true, - get: function () { - return _definition.assertNamedType; - }, -})); -Object.defineProperty(exports, "assertNonNullType", ({ - enumerable: true, - get: function () { - return _definition.assertNonNullType; - }, -})); -Object.defineProperty(exports, "assertNullableType", ({ - enumerable: true, - get: function () { - return _definition.assertNullableType; - }, -})); -Object.defineProperty(exports, "assertObjectType", ({ - enumerable: true, - get: function () { - return _definition.assertObjectType; - }, -})); -Object.defineProperty(exports, "assertOutputType", ({ - enumerable: true, - get: function () { - return _definition.assertOutputType; - }, -})); -Object.defineProperty(exports, "assertScalarType", ({ - enumerable: true, - get: function () { - return _definition.assertScalarType; - }, -})); -Object.defineProperty(exports, "assertSchema", ({ - enumerable: true, - get: function () { - return _schema.assertSchema; - }, -})); -Object.defineProperty(exports, "assertType", ({ - enumerable: true, - get: function () { - return _definition.assertType; - }, -})); -Object.defineProperty(exports, "assertUnionType", ({ - enumerable: true, - get: function () { - return _definition.assertUnionType; - }, -})); -Object.defineProperty(exports, "assertValidSchema", ({ - enumerable: true, - get: function () { - return _validate.assertValidSchema; - }, -})); -Object.defineProperty(exports, "assertWrappingType", ({ - enumerable: true, - get: function () { - return _definition.assertWrappingType; - }, -})); -Object.defineProperty(exports, "getNamedType", ({ - enumerable: true, - get: function () { - return _definition.getNamedType; - }, -})); -Object.defineProperty(exports, "getNullableType", ({ - enumerable: true, - get: function () { - return _definition.getNullableType; - }, -})); -Object.defineProperty(exports, "introspectionTypes", ({ - enumerable: true, - get: function () { - return _introspection.introspectionTypes; - }, -})); -Object.defineProperty(exports, "isAbstractType", ({ - enumerable: true, - get: function () { - return _definition.isAbstractType; - }, -})); -Object.defineProperty(exports, "isCompositeType", ({ - enumerable: true, - get: function () { - return _definition.isCompositeType; - }, -})); -Object.defineProperty(exports, "isDirective", ({ - enumerable: true, - get: function () { - return _directives.isDirective; - }, -})); -Object.defineProperty(exports, "isEnumType", ({ - enumerable: true, - get: function () { - return _definition.isEnumType; - }, -})); -Object.defineProperty(exports, "isInputObjectType", ({ - enumerable: true, - get: function () { - return _definition.isInputObjectType; - }, -})); -Object.defineProperty(exports, "isInputType", ({ - enumerable: true, - get: function () { - return _definition.isInputType; - }, -})); -Object.defineProperty(exports, "isInterfaceType", ({ - enumerable: true, - get: function () { - return _definition.isInterfaceType; - }, -})); -Object.defineProperty(exports, "isIntrospectionType", ({ - enumerable: true, - get: function () { - return _introspection.isIntrospectionType; - }, -})); -Object.defineProperty(exports, "isLeafType", ({ - enumerable: true, - get: function () { - return _definition.isLeafType; - }, -})); -Object.defineProperty(exports, "isListType", ({ - enumerable: true, - get: function () { - return _definition.isListType; - }, -})); -Object.defineProperty(exports, "isNamedType", ({ - enumerable: true, - get: function () { - return _definition.isNamedType; - }, -})); -Object.defineProperty(exports, "isNonNullType", ({ - enumerable: true, - get: function () { - return _definition.isNonNullType; - }, -})); -Object.defineProperty(exports, "isNullableType", ({ - enumerable: true, - get: function () { - return _definition.isNullableType; - }, -})); -Object.defineProperty(exports, "isObjectType", ({ - enumerable: true, - get: function () { - return _definition.isObjectType; - }, -})); -Object.defineProperty(exports, "isOutputType", ({ - enumerable: true, - get: function () { - return _definition.isOutputType; - }, -})); -Object.defineProperty(exports, "isRequiredArgument", ({ - enumerable: true, - get: function () { - return _definition.isRequiredArgument; - }, -})); -Object.defineProperty(exports, "isRequiredInputField", ({ - enumerable: true, - get: function () { - return _definition.isRequiredInputField; - }, -})); -Object.defineProperty(exports, "isScalarType", ({ - enumerable: true, - get: function () { - return _definition.isScalarType; - }, -})); -Object.defineProperty(exports, "isSchema", ({ - enumerable: true, - get: function () { - return _schema.isSchema; - }, -})); -Object.defineProperty(exports, "isSpecifiedDirective", ({ - enumerable: true, - get: function () { - return _directives.isSpecifiedDirective; - }, -})); -Object.defineProperty(exports, "isSpecifiedScalarType", ({ - enumerable: true, - get: function () { - return _scalars.isSpecifiedScalarType; - }, -})); -Object.defineProperty(exports, "isType", ({ - enumerable: true, - get: function () { - return _definition.isType; - }, -})); -Object.defineProperty(exports, "isUnionType", ({ - enumerable: true, - get: function () { - return _definition.isUnionType; - }, -})); -Object.defineProperty(exports, "isWrappingType", ({ - enumerable: true, - get: function () { - return _definition.isWrappingType; - }, -})); -Object.defineProperty(exports, "resolveObjMapThunk", ({ - enumerable: true, - get: function () { - return _definition.resolveObjMapThunk; - }, -})); -Object.defineProperty(exports, "resolveReadonlyArrayThunk", ({ - enumerable: true, - get: function () { - return _definition.resolveReadonlyArrayThunk; - }, -})); -Object.defineProperty(exports, "specifiedDirectives", ({ - enumerable: true, - get: function () { - return _directives.specifiedDirectives; - }, -})); -Object.defineProperty(exports, "specifiedScalarTypes", ({ - enumerable: true, - get: function () { - return _scalars.specifiedScalarTypes; - }, -})); -Object.defineProperty(exports, "validateSchema", ({ - enumerable: true, - get: function () { - return _validate.validateSchema; - }, +exports.UniqueEnumValueNamesRule = UniqueEnumValueNamesRule; + +var _GraphQLError = __nccwpck_require__(4797); + +var _definition = __nccwpck_require__(32150); + +/** + * Unique enum value names + * + * A GraphQL enum type is only valid if all its values are uniquely named. + */ +function UniqueEnumValueNamesRule(context) { + const schema = context.getSchema(); + const existingTypeMap = schema ? schema.getTypeMap() : Object.create(null); + const knownValueNames = Object.create(null); + return { + EnumTypeDefinition: checkValueUniqueness, + EnumTypeExtension: checkValueUniqueness, + }; + + function checkValueUniqueness(node) { + var _node$values; + + const typeName = node.name.value; + + if (!knownValueNames[typeName]) { + knownValueNames[typeName] = Object.create(null); + } // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + + const valueNodes = + (_node$values = node.values) !== null && _node$values !== void 0 + ? _node$values + : []; + const valueNames = knownValueNames[typeName]; + + for (const valueDef of valueNodes) { + const valueName = valueDef.name.value; + const existingType = existingTypeMap[typeName]; + + if ( + (0, _definition.isEnumType)(existingType) && + existingType.getValue(valueName) + ) { + context.reportError( + new _GraphQLError.GraphQLError( + `Enum value "${typeName}.${valueName}" already exists in the schema. It cannot also be defined in this type extension.`, + { + nodes: valueDef.name, + }, + ), + ); + } else if (valueNames[valueName]) { + context.reportError( + new _GraphQLError.GraphQLError( + `Enum value "${typeName}.${valueName}" can only be defined once.`, + { + nodes: [valueNames[valueName], valueDef.name], + }, + ), + ); + } else { + valueNames[valueName] = valueDef.name; + } + } + + return false; + } +} + + +/***/ }), + +/***/ 9502: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, })); +exports.UniqueFieldDefinitionNamesRule = UniqueFieldDefinitionNamesRule; -var _schema = __nccwpck_require__(8505); +var _GraphQLError = __nccwpck_require__(4797); var _definition = __nccwpck_require__(32150); -var _directives = __nccwpck_require__(83614); +/** + * Unique field definition names + * + * A GraphQL complex type is only valid if all its fields are uniquely named. + */ +function UniqueFieldDefinitionNamesRule(context) { + const schema = context.getSchema(); + const existingTypeMap = schema ? schema.getTypeMap() : Object.create(null); + const knownFieldNames = Object.create(null); + return { + InputObjectTypeDefinition: checkFieldUniqueness, + InputObjectTypeExtension: checkFieldUniqueness, + InterfaceTypeDefinition: checkFieldUniqueness, + InterfaceTypeExtension: checkFieldUniqueness, + ObjectTypeDefinition: checkFieldUniqueness, + ObjectTypeExtension: checkFieldUniqueness, + }; -var _scalars = __nccwpck_require__(93145); + function checkFieldUniqueness(node) { + var _node$fields; -var _introspection = __nccwpck_require__(28344); + const typeName = node.name.value; -var _validate = __nccwpck_require__(22430); + if (!knownFieldNames[typeName]) { + knownFieldNames[typeName] = Object.create(null); + } // FIXME: https://github.com/graphql/graphql-js/issues/2203 -var _assertName = __nccwpck_require__(74947); + /* c8 ignore next */ + + const fieldNodes = + (_node$fields = node.fields) !== null && _node$fields !== void 0 + ? _node$fields + : []; + const fieldNames = knownFieldNames[typeName]; + + for (const fieldDef of fieldNodes) { + const fieldName = fieldDef.name.value; + + if (hasField(existingTypeMap[typeName], fieldName)) { + context.reportError( + new _GraphQLError.GraphQLError( + `Field "${typeName}.${fieldName}" already exists in the schema. It cannot also be defined in this type extension.`, + { + nodes: fieldDef.name, + }, + ), + ); + } else if (fieldNames[fieldName]) { + context.reportError( + new _GraphQLError.GraphQLError( + `Field "${typeName}.${fieldName}" can only be defined once.`, + { + nodes: [fieldNames[fieldName], fieldDef.name], + }, + ), + ); + } else { + fieldNames[fieldName] = fieldDef.name; + } + } + + return false; + } +} + +function hasField(type, fieldName) { + if ( + (0, _definition.isObjectType)(type) || + (0, _definition.isInterfaceType)(type) || + (0, _definition.isInputObjectType)(type) + ) { + return type.getFields()[fieldName] != null; + } + + return false; +} /***/ }), -/***/ 28344: +/***/ 79402: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -287500,631 +289013,307 @@ var _assertName = __nccwpck_require__(74947); Object.defineProperty(exports, "__esModule", ({ value: true, })); -exports.introspectionTypes = - exports.__TypeKind = - exports.__Type = - exports.__Schema = - exports.__InputValue = - exports.__Field = - exports.__EnumValue = - exports.__DirectiveLocation = - exports.__Directive = - exports.TypeNameMetaFieldDef = - exports.TypeMetaFieldDef = - exports.TypeKind = - exports.SchemaMetaFieldDef = - void 0; -exports.isIntrospectionType = isIntrospectionType; +exports.UniqueFragmentNamesRule = UniqueFragmentNamesRule; -var _inspect = __nccwpck_require__(10102); +var _GraphQLError = __nccwpck_require__(4797); -var _invariant = __nccwpck_require__(28847); +/** + * Unique fragment names + * + * A GraphQL document is only valid if all defined fragments have unique names. + * + * See https://spec.graphql.org/draft/#sec-Fragment-Name-Uniqueness + */ +function UniqueFragmentNamesRule(context) { + const knownFragmentNames = Object.create(null); + return { + OperationDefinition: () => false, -var _directiveLocation = __nccwpck_require__(71553); + FragmentDefinition(node) { + const fragmentName = node.name.value; -var _printer = __nccwpck_require__(68203); + if (knownFragmentNames[fragmentName]) { + context.reportError( + new _GraphQLError.GraphQLError( + `There can be only one fragment named "${fragmentName}".`, + { + nodes: [knownFragmentNames[fragmentName], node.name], + }, + ), + ); + } else { + knownFragmentNames[fragmentName] = node.name; + } -var _astFromValue = __nccwpck_require__(12653); + return false; + }, + }; +} -var _definition = __nccwpck_require__(32150); -var _scalars = __nccwpck_require__(93145); +/***/ }), -const __Schema = new _definition.GraphQLObjectType({ - name: '__Schema', - description: - 'A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations.', - fields: () => ({ - description: { - type: _scalars.GraphQLString, - resolve: (schema) => schema.description, - }, - types: { - description: 'A list of all types supported by this server.', - type: new _definition.GraphQLNonNull( - new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type)), - ), +/***/ 83552: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - resolve(schema) { - return Object.values(schema.getTypeMap()); - }, - }, - queryType: { - description: 'The type that query operations will be rooted at.', - type: new _definition.GraphQLNonNull(__Type), - resolve: (schema) => schema.getQueryType(), - }, - mutationType: { - description: - 'If this server supports mutation, the type that mutation operations will be rooted at.', - type: __Type, - resolve: (schema) => schema.getMutationType(), - }, - subscriptionType: { - description: - 'If this server support subscription, the type that subscription operations will be rooted at.', - type: __Type, - resolve: (schema) => schema.getSubscriptionType(), - }, - directives: { - description: 'A list of all directives supported by this server.', - type: new _definition.GraphQLNonNull( - new _definition.GraphQLList( - new _definition.GraphQLNonNull(__Directive), - ), - ), - resolve: (schema) => schema.getDirectives(), - }, - }), -}); +"use strict"; -exports.__Schema = __Schema; -const __Directive = new _definition.GraphQLObjectType({ - name: '__Directive', - description: - "A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.\n\nIn some cases, you need to provide options to alter GraphQL's execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor.", - fields: () => ({ - name: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLString), - resolve: (directive) => directive.name, - }, - description: { - type: _scalars.GraphQLString, - resolve: (directive) => directive.description, - }, - isRepeatable: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), - resolve: (directive) => directive.isRepeatable, - }, - locations: { - type: new _definition.GraphQLNonNull( - new _definition.GraphQLList( - new _definition.GraphQLNonNull(__DirectiveLocation), - ), - ), - resolve: (directive) => directive.locations, - }, - args: { - type: new _definition.GraphQLNonNull( - new _definition.GraphQLList( - new _definition.GraphQLNonNull(__InputValue), - ), - ), - args: { - includeDeprecated: { - type: _scalars.GraphQLBoolean, - defaultValue: false, - }, +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.UniqueInputFieldNamesRule = UniqueInputFieldNamesRule; + +var _invariant = __nccwpck_require__(28847); + +var _GraphQLError = __nccwpck_require__(4797); + +/** + * Unique input field names + * + * A GraphQL input object value is only valid if all supplied fields are + * uniquely named. + * + * See https://spec.graphql.org/draft/#sec-Input-Object-Field-Uniqueness + */ +function UniqueInputFieldNamesRule(context) { + const knownNameStack = []; + let knownNames = Object.create(null); + return { + ObjectValue: { + enter() { + knownNameStack.push(knownNames); + knownNames = Object.create(null); }, - resolve(field, { includeDeprecated }) { - return includeDeprecated - ? field.args - : field.args.filter((arg) => arg.deprecationReason == null); + leave() { + const prevKnownNames = knownNameStack.pop(); + prevKnownNames || (0, _invariant.invariant)(false); + knownNames = prevKnownNames; }, }, - }), -}); -exports.__Directive = __Directive; + ObjectField(node) { + const fieldName = node.name.value; -const __DirectiveLocation = new _definition.GraphQLEnumType({ - name: '__DirectiveLocation', - description: - 'A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies.', - values: { - QUERY: { - value: _directiveLocation.DirectiveLocation.QUERY, - description: 'Location adjacent to a query operation.', - }, - MUTATION: { - value: _directiveLocation.DirectiveLocation.MUTATION, - description: 'Location adjacent to a mutation operation.', - }, - SUBSCRIPTION: { - value: _directiveLocation.DirectiveLocation.SUBSCRIPTION, - description: 'Location adjacent to a subscription operation.', - }, - FIELD: { - value: _directiveLocation.DirectiveLocation.FIELD, - description: 'Location adjacent to a field.', - }, - FRAGMENT_DEFINITION: { - value: _directiveLocation.DirectiveLocation.FRAGMENT_DEFINITION, - description: 'Location adjacent to a fragment definition.', - }, - FRAGMENT_SPREAD: { - value: _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, - description: 'Location adjacent to a fragment spread.', - }, - INLINE_FRAGMENT: { - value: _directiveLocation.DirectiveLocation.INLINE_FRAGMENT, - description: 'Location adjacent to an inline fragment.', - }, - VARIABLE_DEFINITION: { - value: _directiveLocation.DirectiveLocation.VARIABLE_DEFINITION, - description: 'Location adjacent to a variable definition.', - }, - SCHEMA: { - value: _directiveLocation.DirectiveLocation.SCHEMA, - description: 'Location adjacent to a schema definition.', - }, - SCALAR: { - value: _directiveLocation.DirectiveLocation.SCALAR, - description: 'Location adjacent to a scalar definition.', - }, - OBJECT: { - value: _directiveLocation.DirectiveLocation.OBJECT, - description: 'Location adjacent to an object type definition.', - }, - FIELD_DEFINITION: { - value: _directiveLocation.DirectiveLocation.FIELD_DEFINITION, - description: 'Location adjacent to a field definition.', - }, - ARGUMENT_DEFINITION: { - value: _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION, - description: 'Location adjacent to an argument definition.', - }, - INTERFACE: { - value: _directiveLocation.DirectiveLocation.INTERFACE, - description: 'Location adjacent to an interface definition.', - }, - UNION: { - value: _directiveLocation.DirectiveLocation.UNION, - description: 'Location adjacent to a union definition.', - }, - ENUM: { - value: _directiveLocation.DirectiveLocation.ENUM, - description: 'Location adjacent to an enum definition.', - }, - ENUM_VALUE: { - value: _directiveLocation.DirectiveLocation.ENUM_VALUE, - description: 'Location adjacent to an enum value definition.', - }, - INPUT_OBJECT: { - value: _directiveLocation.DirectiveLocation.INPUT_OBJECT, - description: 'Location adjacent to an input object type definition.', - }, - INPUT_FIELD_DEFINITION: { - value: _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION, - description: 'Location adjacent to an input object field definition.', + if (knownNames[fieldName]) { + context.reportError( + new _GraphQLError.GraphQLError( + `There can be only one input field named "${fieldName}".`, + { + nodes: [knownNames[fieldName], node.name], + }, + ), + ); + } else { + knownNames[fieldName] = node.name; + } }, - }, -}); - -exports.__DirectiveLocation = __DirectiveLocation; + }; +} -const __Type = new _definition.GraphQLObjectType({ - name: '__Type', - description: - 'The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in GraphQL as represented by the `__TypeKind` enum.\n\nDepending on the kind of a type, certain fields describe information about that type. Scalar types provide no information beyond a name, description and optional `specifiedByURL`, while Enum types provide their values. Object and Interface types provide the fields they describe. Abstract types, Union and Interface, provide the Object types possible at runtime. List and NonNull types compose other types.', - fields: () => ({ - kind: { - type: new _definition.GraphQLNonNull(__TypeKind), - resolve(type) { - if ((0, _definition.isScalarType)(type)) { - return TypeKind.SCALAR; - } +/***/ }), - if ((0, _definition.isObjectType)(type)) { - return TypeKind.OBJECT; - } +/***/ 94865: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if ((0, _definition.isInterfaceType)(type)) { - return TypeKind.INTERFACE; - } +"use strict"; - if ((0, _definition.isUnionType)(type)) { - return TypeKind.UNION; - } - if ((0, _definition.isEnumType)(type)) { - return TypeKind.ENUM; - } +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.UniqueOperationNamesRule = UniqueOperationNamesRule; - if ((0, _definition.isInputObjectType)(type)) { - return TypeKind.INPUT_OBJECT; - } +var _GraphQLError = __nccwpck_require__(4797); - if ((0, _definition.isListType)(type)) { - return TypeKind.LIST; - } +/** + * Unique operation names + * + * A GraphQL document is only valid if all defined operations have unique names. + * + * See https://spec.graphql.org/draft/#sec-Operation-Name-Uniqueness + */ +function UniqueOperationNamesRule(context) { + const knownOperationNames = Object.create(null); + return { + OperationDefinition(node) { + const operationName = node.name; - if ((0, _definition.isNonNullType)(type)) { - return TypeKind.NON_NULL; + if (operationName) { + if (knownOperationNames[operationName.value]) { + context.reportError( + new _GraphQLError.GraphQLError( + `There can be only one operation named "${operationName.value}".`, + { + nodes: [ + knownOperationNames[operationName.value], + operationName, + ], + }, + ), + ); + } else { + knownOperationNames[operationName.value] = operationName; } - /* c8 ignore next 3 */ - // Not reachable, all possible types have been considered) + } - false || - (0, _invariant.invariant)( - false, - `Unexpected type: "${(0, _inspect.inspect)(type)}".`, - ); - }, - }, - name: { - type: _scalars.GraphQLString, - resolve: (type) => ('name' in type ? type.name : undefined), - }, - description: { - type: _scalars.GraphQLString, - resolve: ( - type, // FIXME: add test case - ) => - /* c8 ignore next */ - 'description' in type ? type.description : undefined, - }, - specifiedByURL: { - type: _scalars.GraphQLString, - resolve: (obj) => - 'specifiedByURL' in obj ? obj.specifiedByURL : undefined, + return false; }, - fields: { - type: new _definition.GraphQLList( - new _definition.GraphQLNonNull(__Field), - ), - args: { - includeDeprecated: { - type: _scalars.GraphQLBoolean, - defaultValue: false, - }, - }, - resolve(type, { includeDeprecated }) { - if ( - (0, _definition.isObjectType)(type) || - (0, _definition.isInterfaceType)(type) - ) { - const fields = Object.values(type.getFields()); - return includeDeprecated - ? fields - : fields.filter((field) => field.deprecationReason == null); - } - }, - }, - interfaces: { - type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type)), + FragmentDefinition: () => false, + }; +} - resolve(type) { - if ( - (0, _definition.isObjectType)(type) || - (0, _definition.isInterfaceType)(type) - ) { - return type.getInterfaces(); - } - }, - }, - possibleTypes: { - type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type)), - resolve(type, _args, _context, { schema }) { - if ((0, _definition.isAbstractType)(type)) { - return schema.getPossibleTypes(type); - } - }, - }, - enumValues: { - type: new _definition.GraphQLList( - new _definition.GraphQLNonNull(__EnumValue), - ), - args: { - includeDeprecated: { - type: _scalars.GraphQLBoolean, - defaultValue: false, - }, - }, +/***/ }), - resolve(type, { includeDeprecated }) { - if ((0, _definition.isEnumType)(type)) { - const values = type.getValues(); - return includeDeprecated - ? values - : values.filter((field) => field.deprecationReason == null); - } - }, - }, - inputFields: { - type: new _definition.GraphQLList( - new _definition.GraphQLNonNull(__InputValue), - ), - args: { - includeDeprecated: { - type: _scalars.GraphQLBoolean, - defaultValue: false, - }, - }, +/***/ 31492: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - resolve(type, { includeDeprecated }) { - if ((0, _definition.isInputObjectType)(type)) { - const values = Object.values(type.getFields()); - return includeDeprecated - ? values - : values.filter((field) => field.deprecationReason == null); - } - }, - }, - ofType: { - type: __Type, - resolve: (type) => ('ofType' in type ? type.ofType : undefined), - }, - isOneOf: { - type: _scalars.GraphQLBoolean, - resolve: (type) => { - if ((0, _definition.isInputObjectType)(type)) { - return type.isOneOf; - } - }, - }, - }), -}); +"use strict"; -exports.__Type = __Type; -const __Field = new _definition.GraphQLObjectType({ - name: '__Field', - description: - 'Object and Interface types are described by a list of Fields, each of which has a name, potentially a list of arguments, and a return type.', - fields: () => ({ - name: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLString), - resolve: (field) => field.name, - }, - description: { - type: _scalars.GraphQLString, - resolve: (field) => field.description, - }, - args: { - type: new _definition.GraphQLNonNull( - new _definition.GraphQLList( - new _definition.GraphQLNonNull(__InputValue), - ), - ), - args: { - includeDeprecated: { - type: _scalars.GraphQLBoolean, - defaultValue: false, - }, - }, +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.UniqueOperationTypesRule = UniqueOperationTypesRule; - resolve(field, { includeDeprecated }) { - return includeDeprecated - ? field.args - : field.args.filter((arg) => arg.deprecationReason == null); - }, - }, - type: { - type: new _definition.GraphQLNonNull(__Type), - resolve: (field) => field.type, - }, - isDeprecated: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), - resolve: (field) => field.deprecationReason != null, - }, - deprecationReason: { - type: _scalars.GraphQLString, - resolve: (field) => field.deprecationReason, - }, - }), -}); +var _GraphQLError = __nccwpck_require__(4797); -exports.__Field = __Field; +/** + * Unique operation types + * + * A GraphQL document is only valid if it has only one type per operation. + */ +function UniqueOperationTypesRule(context) { + const schema = context.getSchema(); + const definedOperationTypes = Object.create(null); + const existingOperationTypes = schema + ? { + query: schema.getQueryType(), + mutation: schema.getMutationType(), + subscription: schema.getSubscriptionType(), + } + : {}; + return { + SchemaDefinition: checkOperationTypes, + SchemaExtension: checkOperationTypes, + }; -const __InputValue = new _definition.GraphQLObjectType({ - name: '__InputValue', - description: - 'Arguments provided to Fields or Directives and the input fields of an InputObject are represented as Input Values which describe their type and optionally a default value.', - fields: () => ({ - name: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLString), - resolve: (inputValue) => inputValue.name, - }, - description: { - type: _scalars.GraphQLString, - resolve: (inputValue) => inputValue.description, - }, - type: { - type: new _definition.GraphQLNonNull(__Type), - resolve: (inputValue) => inputValue.type, - }, - defaultValue: { - type: _scalars.GraphQLString, - description: - 'A GraphQL-formatted string representing the default value for this input value.', + function checkOperationTypes(node) { + var _node$operationTypes; - resolve(inputValue) { - const { type, defaultValue } = inputValue; - const valueAST = (0, _astFromValue.astFromValue)(defaultValue, type); - return valueAST ? (0, _printer.print)(valueAST) : null; - }, - }, - isDeprecated: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), - resolve: (field) => field.deprecationReason != null, - }, - deprecationReason: { - type: _scalars.GraphQLString, - resolve: (obj) => obj.deprecationReason, - }, - }), -}); + // See: https://github.com/graphql/graphql-js/issues/2203 -exports.__InputValue = __InputValue; + /* c8 ignore next */ + const operationTypesNodes = + (_node$operationTypes = node.operationTypes) !== null && + _node$operationTypes !== void 0 + ? _node$operationTypes + : []; -const __EnumValue = new _definition.GraphQLObjectType({ - name: '__EnumValue', - description: - 'One possible value for a given Enum. Enum values are unique values, not a placeholder for a string or numeric value. However an Enum value is returned in a JSON response as a string.', - fields: () => ({ - name: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLString), - resolve: (enumValue) => enumValue.name, - }, - description: { - type: _scalars.GraphQLString, - resolve: (enumValue) => enumValue.description, - }, - isDeprecated: { - type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), - resolve: (enumValue) => enumValue.deprecationReason != null, - }, - deprecationReason: { - type: _scalars.GraphQLString, - resolve: (enumValue) => enumValue.deprecationReason, - }, - }), -}); + for (const operationType of operationTypesNodes) { + const operation = operationType.operation; + const alreadyDefinedOperationType = definedOperationTypes[operation]; -exports.__EnumValue = __EnumValue; -var TypeKind; -exports.TypeKind = TypeKind; + if (existingOperationTypes[operation]) { + context.reportError( + new _GraphQLError.GraphQLError( + `Type for ${operation} already defined in the schema. It cannot be redefined.`, + { + nodes: operationType, + }, + ), + ); + } else if (alreadyDefinedOperationType) { + context.reportError( + new _GraphQLError.GraphQLError( + `There can be only one ${operation} type in schema.`, + { + nodes: [alreadyDefinedOperationType, operationType], + }, + ), + ); + } else { + definedOperationTypes[operation] = operationType; + } + } -(function (TypeKind) { - TypeKind['SCALAR'] = 'SCALAR'; - TypeKind['OBJECT'] = 'OBJECT'; - TypeKind['INTERFACE'] = 'INTERFACE'; - TypeKind['UNION'] = 'UNION'; - TypeKind['ENUM'] = 'ENUM'; - TypeKind['INPUT_OBJECT'] = 'INPUT_OBJECT'; - TypeKind['LIST'] = 'LIST'; - TypeKind['NON_NULL'] = 'NON_NULL'; -})(TypeKind || (exports.TypeKind = TypeKind = {})); + return false; + } +} + + +/***/ }), + +/***/ 24316: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.UniqueTypeNamesRule = UniqueTypeNamesRule; + +var _GraphQLError = __nccwpck_require__(4797); -const __TypeKind = new _definition.GraphQLEnumType({ - name: '__TypeKind', - description: 'An enum describing what kind of type a given `__Type` is.', - values: { - SCALAR: { - value: TypeKind.SCALAR, - description: 'Indicates this type is a scalar.', - }, - OBJECT: { - value: TypeKind.OBJECT, - description: - 'Indicates this type is an object. `fields` and `interfaces` are valid fields.', - }, - INTERFACE: { - value: TypeKind.INTERFACE, - description: - 'Indicates this type is an interface. `fields`, `interfaces`, and `possibleTypes` are valid fields.', - }, - UNION: { - value: TypeKind.UNION, - description: - 'Indicates this type is a union. `possibleTypes` is a valid field.', - }, - ENUM: { - value: TypeKind.ENUM, - description: - 'Indicates this type is an enum. `enumValues` is a valid field.', - }, - INPUT_OBJECT: { - value: TypeKind.INPUT_OBJECT, - description: - 'Indicates this type is an input object. `inputFields` is a valid field.', - }, - LIST: { - value: TypeKind.LIST, - description: 'Indicates this type is a list. `ofType` is a valid field.', - }, - NON_NULL: { - value: TypeKind.NON_NULL, - description: - 'Indicates this type is a non-null. `ofType` is a valid field.', - }, - }, -}); /** - * Note that these are GraphQLField and not GraphQLFieldConfig, - * so the format for args is different. + * Unique type names + * + * A GraphQL document is only valid if all defined types have unique names. */ +function UniqueTypeNamesRule(context) { + const knownTypeNames = Object.create(null); + const schema = context.getSchema(); + return { + ScalarTypeDefinition: checkTypeName, + ObjectTypeDefinition: checkTypeName, + InterfaceTypeDefinition: checkTypeName, + UnionTypeDefinition: checkTypeName, + EnumTypeDefinition: checkTypeName, + InputObjectTypeDefinition: checkTypeName, + }; -exports.__TypeKind = __TypeKind; -const SchemaMetaFieldDef = { - name: '__schema', - type: new _definition.GraphQLNonNull(__Schema), - description: 'Access the current type schema of this server.', - args: [], - resolve: (_source, _args, _context, { schema }) => schema, - deprecationReason: undefined, - extensions: Object.create(null), - astNode: undefined, -}; -exports.SchemaMetaFieldDef = SchemaMetaFieldDef; -const TypeMetaFieldDef = { - name: '__type', - type: __Type, - description: 'Request the type information of a single type.', - args: [ - { - name: 'name', - description: undefined, - type: new _definition.GraphQLNonNull(_scalars.GraphQLString), - defaultValue: undefined, - deprecationReason: undefined, - extensions: Object.create(null), - astNode: undefined, - }, - ], - resolve: (_source, { name }, _context, { schema }) => schema.getType(name), - deprecationReason: undefined, - extensions: Object.create(null), - astNode: undefined, -}; -exports.TypeMetaFieldDef = TypeMetaFieldDef; -const TypeNameMetaFieldDef = { - name: '__typename', - type: new _definition.GraphQLNonNull(_scalars.GraphQLString), - description: 'The name of the current Object type at runtime.', - args: [], - resolve: (_source, _args, _context, { parentType }) => parentType.name, - deprecationReason: undefined, - extensions: Object.create(null), - astNode: undefined, -}; -exports.TypeNameMetaFieldDef = TypeNameMetaFieldDef; -const introspectionTypes = Object.freeze([ - __Schema, - __Directive, - __DirectiveLocation, - __Type, - __Field, - __InputValue, - __EnumValue, - __TypeKind, -]); -exports.introspectionTypes = introspectionTypes; + function checkTypeName(node) { + const typeName = node.name.value; -function isIntrospectionType(type) { - return introspectionTypes.some(({ name }) => type.name === name); + if (schema !== null && schema !== void 0 && schema.getType(typeName)) { + context.reportError( + new _GraphQLError.GraphQLError( + `Type "${typeName}" already exists in the schema. It cannot also be defined in this type definition.`, + { + nodes: node.name, + }, + ), + ); + return; + } + + if (knownTypeNames[typeName]) { + context.reportError( + new _GraphQLError.GraphQLError( + `There can be only one type named "${typeName}".`, + { + nodes: [knownTypeNames[typeName], node.name], + }, + ), + ); + } else { + knownTypeNames[typeName] = node.name; + } + + return false; + } } /***/ }), -/***/ 93145: +/***/ 65931: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -288133,375 +289322,343 @@ function isIntrospectionType(type) { Object.defineProperty(exports, "__esModule", ({ value: true, })); -exports.GraphQLString = - exports.GraphQLInt = - exports.GraphQLID = - exports.GraphQLFloat = - exports.GraphQLBoolean = - exports.GRAPHQL_MIN_INT = - exports.GRAPHQL_MAX_INT = - void 0; -exports.isSpecifiedScalarType = isSpecifiedScalarType; -exports.specifiedScalarTypes = void 0; - -var _inspect = __nccwpck_require__(10102); +exports.UniqueVariableNamesRule = UniqueVariableNamesRule; -var _isObjectLike = __nccwpck_require__(95865); +var _groupBy = __nccwpck_require__(93173); var _GraphQLError = __nccwpck_require__(4797); -var _kinds = __nccwpck_require__(11927); +/** + * Unique variable names + * + * A GraphQL operation is only valid if all its variables are uniquely named. + */ +function UniqueVariableNamesRule(context) { + return { + OperationDefinition(operationNode) { + var _operationNode$variab; + + // See: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const variableDefinitions = + (_operationNode$variab = operationNode.variableDefinitions) !== null && + _operationNode$variab !== void 0 + ? _operationNode$variab + : []; + const seenVariableDefinitions = (0, _groupBy.groupBy)( + variableDefinitions, + (node) => node.variable.name.value, + ); + + for (const [variableName, variableNodes] of seenVariableDefinitions) { + if (variableNodes.length > 1) { + context.reportError( + new _GraphQLError.GraphQLError( + `There can be only one variable named "$${variableName}".`, + { + nodes: variableNodes.map((node) => node.variable.name), + }, + ), + ); + } + } + }, + }; +} -var _printer = __nccwpck_require__(68203); -var _definition = __nccwpck_require__(32150); +/***/ }), -/** - * Maximum possible Int value as per GraphQL Spec (32-bit signed integer). - * n.b. This differs from JavaScript's numbers that are IEEE 754 doubles safe up-to 2^53 - 1 - * */ -const GRAPHQL_MAX_INT = 2147483647; -/** - * Minimum possible Int value as per GraphQL Spec (32-bit signed integer). - * n.b. This differs from JavaScript's numbers that are IEEE 754 doubles safe starting at -(2^53 - 1) - * */ +/***/ 85189: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -exports.GRAPHQL_MAX_INT = GRAPHQL_MAX_INT; -const GRAPHQL_MIN_INT = -2147483648; -exports.GRAPHQL_MIN_INT = GRAPHQL_MIN_INT; -const GraphQLInt = new _definition.GraphQLScalarType({ - name: 'Int', - description: - 'The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.', +"use strict"; - serialize(outputValue) { - const coercedValue = serializeObject(outputValue); - if (typeof coercedValue === 'boolean') { - return coercedValue ? 1 : 0; - } +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.ValuesOfCorrectTypeRule = ValuesOfCorrectTypeRule; - let num = coercedValue; +var _didYouMean = __nccwpck_require__(42878); - if (typeof coercedValue === 'string' && coercedValue !== '') { - num = Number(coercedValue); - } +var _inspect = __nccwpck_require__(10102); - if (typeof num !== 'number' || !Number.isInteger(num)) { - throw new _GraphQLError.GraphQLError( - `Int cannot represent non-integer value: ${(0, _inspect.inspect)( - coercedValue, - )}`, - ); - } +var _keyMap = __nccwpck_require__(10711); - if (num > GRAPHQL_MAX_INT || num < GRAPHQL_MIN_INT) { - throw new _GraphQLError.GraphQLError( - 'Int cannot represent non 32-bit signed integer value: ' + - (0, _inspect.inspect)(coercedValue), - ); - } +var _suggestionList = __nccwpck_require__(57704); - return num; - }, +var _GraphQLError = __nccwpck_require__(4797); - parseValue(inputValue) { - if (typeof inputValue !== 'number' || !Number.isInteger(inputValue)) { - throw new _GraphQLError.GraphQLError( - `Int cannot represent non-integer value: ${(0, _inspect.inspect)( - inputValue, - )}`, - ); - } +var _kinds = __nccwpck_require__(11927); - if (inputValue > GRAPHQL_MAX_INT || inputValue < GRAPHQL_MIN_INT) { - throw new _GraphQLError.GraphQLError( - `Int cannot represent non 32-bit signed integer value: ${inputValue}`, - ); - } +var _printer = __nccwpck_require__(68203); - return inputValue; - }, +var _definition = __nccwpck_require__(32150); - parseLiteral(valueNode) { - if (valueNode.kind !== _kinds.Kind.INT) { - throw new _GraphQLError.GraphQLError( - `Int cannot represent non-integer value: ${(0, _printer.print)( - valueNode, - )}`, - { - nodes: valueNode, - }, - ); - } +/** + * Value literals of correct type + * + * A GraphQL document is only valid if all value literals are of the type + * expected at their position. + * + * See https://spec.graphql.org/draft/#sec-Values-of-Correct-Type + */ +function ValuesOfCorrectTypeRule(context) { + let variableDefinitions = {}; + return { + OperationDefinition: { + enter() { + variableDefinitions = {}; + }, + }, - const num = parseInt(valueNode.value, 10); + VariableDefinition(definition) { + variableDefinitions[definition.variable.name.value] = definition; + }, - if (num > GRAPHQL_MAX_INT || num < GRAPHQL_MIN_INT) { - throw new _GraphQLError.GraphQLError( - `Int cannot represent non 32-bit signed integer value: ${valueNode.value}`, - { - nodes: valueNode, - }, + ListValue(node) { + // Note: TypeInfo will traverse into a list's item type, so look to the + // parent input type to check if it is a list. + const type = (0, _definition.getNullableType)( + context.getParentInputType(), ); - } - - return num; - }, -}); -exports.GraphQLInt = GraphQLInt; -const GraphQLFloat = new _definition.GraphQLScalarType({ - name: 'Float', - description: - 'The `Float` scalar type represents signed double-precision fractional values as specified by [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point).', - serialize(outputValue) { - const coercedValue = serializeObject(outputValue); - - if (typeof coercedValue === 'boolean') { - return coercedValue ? 1 : 0; - } + if (!(0, _definition.isListType)(type)) { + isValidValueNode(context, node); + return false; // Don't traverse further. + } + }, - let num = coercedValue; + ObjectValue(node) { + const type = (0, _definition.getNamedType)(context.getInputType()); - if (typeof coercedValue === 'string' && coercedValue !== '') { - num = Number(coercedValue); - } + if (!(0, _definition.isInputObjectType)(type)) { + isValidValueNode(context, node); + return false; // Don't traverse further. + } // Ensure every required field exists. - if (typeof num !== 'number' || !Number.isFinite(num)) { - throw new _GraphQLError.GraphQLError( - `Float cannot represent non numeric value: ${(0, _inspect.inspect)( - coercedValue, - )}`, + const fieldNodeMap = (0, _keyMap.keyMap)( + node.fields, + (field) => field.name.value, ); - } - return num; - }, + for (const fieldDef of Object.values(type.getFields())) { + const fieldNode = fieldNodeMap[fieldDef.name]; - parseValue(inputValue) { - if (typeof inputValue !== 'number' || !Number.isFinite(inputValue)) { - throw new _GraphQLError.GraphQLError( - `Float cannot represent non numeric value: ${(0, _inspect.inspect)( - inputValue, - )}`, - ); - } + if (!fieldNode && (0, _definition.isRequiredInputField)(fieldDef)) { + const typeStr = (0, _inspect.inspect)(fieldDef.type); + context.reportError( + new _GraphQLError.GraphQLError( + `Field "${type.name}.${fieldDef.name}" of required type "${typeStr}" was not provided.`, + { + nodes: node, + }, + ), + ); + } + } - return inputValue; - }, + if (type.isOneOf) { + validateOneOfInputObject( + context, + node, + type, + fieldNodeMap, + variableDefinitions, + ); + } + }, - parseLiteral(valueNode) { - if ( - valueNode.kind !== _kinds.Kind.FLOAT && - valueNode.kind !== _kinds.Kind.INT - ) { - throw new _GraphQLError.GraphQLError( - `Float cannot represent non numeric value: ${(0, _printer.print)( - valueNode, - )}`, - valueNode, + ObjectField(node) { + const parentType = (0, _definition.getNamedType)( + context.getParentInputType(), ); - } - - return parseFloat(valueNode.value); - }, -}); -exports.GraphQLFloat = GraphQLFloat; -const GraphQLString = new _definition.GraphQLScalarType({ - name: 'String', - description: - 'The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.', + const fieldType = context.getInputType(); - serialize(outputValue) { - const coercedValue = serializeObject(outputValue); // Serialize string, boolean and number values to a string, but do not - // attempt to coerce object, function, symbol, or other types as strings. + if (!fieldType && (0, _definition.isInputObjectType)(parentType)) { + const suggestions = (0, _suggestionList.suggestionList)( + node.name.value, + Object.keys(parentType.getFields()), + ); + context.reportError( + new _GraphQLError.GraphQLError( + `Field "${node.name.value}" is not defined by type "${parentType.name}".` + + (0, _didYouMean.didYouMean)(suggestions), + { + nodes: node, + }, + ), + ); + } + }, - if (typeof coercedValue === 'string') { - return coercedValue; - } + NullValue(node) { + const type = context.getInputType(); - if (typeof coercedValue === 'boolean') { - return coercedValue ? 'true' : 'false'; - } + if ((0, _definition.isNonNullType)(type)) { + context.reportError( + new _GraphQLError.GraphQLError( + `Expected value of type "${(0, _inspect.inspect)( + type, + )}", found ${(0, _printer.print)(node)}.`, + { + nodes: node, + }, + ), + ); + } + }, - if (typeof coercedValue === 'number' && Number.isFinite(coercedValue)) { - return coercedValue.toString(); - } + EnumValue: (node) => isValidValueNode(context, node), + IntValue: (node) => isValidValueNode(context, node), + FloatValue: (node) => isValidValueNode(context, node), + StringValue: (node) => isValidValueNode(context, node), + BooleanValue: (node) => isValidValueNode(context, node), + }; +} +/** + * Any value literal may be a valid representation of a Scalar, depending on + * that scalar type. + */ - throw new _GraphQLError.GraphQLError( - `String cannot represent value: ${(0, _inspect.inspect)(outputValue)}`, - ); - }, +function isValidValueNode(context, node) { + // Report any error at the full type expected by the location. + const locationType = context.getInputType(); - parseValue(inputValue) { - if (typeof inputValue !== 'string') { - throw new _GraphQLError.GraphQLError( - `String cannot represent a non string value: ${(0, _inspect.inspect)( - inputValue, - )}`, - ); - } + if (!locationType) { + return; + } - return inputValue; - }, + const type = (0, _definition.getNamedType)(locationType); - parseLiteral(valueNode) { - if (valueNode.kind !== _kinds.Kind.STRING) { - throw new _GraphQLError.GraphQLError( - `String cannot represent a non string value: ${(0, _printer.print)( - valueNode, - )}`, + if (!(0, _definition.isLeafType)(type)) { + const typeStr = (0, _inspect.inspect)(locationType); + context.reportError( + new _GraphQLError.GraphQLError( + `Expected value of type "${typeStr}", found ${(0, _printer.print)( + node, + )}.`, { - nodes: valueNode, + nodes: node, }, - ); - } - - return valueNode.value; - }, -}); -exports.GraphQLString = GraphQLString; -const GraphQLBoolean = new _definition.GraphQLScalarType({ - name: 'Boolean', - description: 'The `Boolean` scalar type represents `true` or `false`.', - - serialize(outputValue) { - const coercedValue = serializeObject(outputValue); - - if (typeof coercedValue === 'boolean') { - return coercedValue; - } - - if (Number.isFinite(coercedValue)) { - return coercedValue !== 0; - } + ), + ); + return; + } // Scalars and Enums determine if a literal value is valid via parseLiteral(), + // which may throw or return an invalid value to indicate failure. - throw new _GraphQLError.GraphQLError( - `Boolean cannot represent a non boolean value: ${(0, _inspect.inspect)( - coercedValue, - )}`, + try { + const parseResult = type.parseLiteral( + node, + undefined, + /* variables */ ); - }, - parseValue(inputValue) { - if (typeof inputValue !== 'boolean') { - throw new _GraphQLError.GraphQLError( - `Boolean cannot represent a non boolean value: ${(0, _inspect.inspect)( - inputValue, - )}`, + if (parseResult === undefined) { + const typeStr = (0, _inspect.inspect)(locationType); + context.reportError( + new _GraphQLError.GraphQLError( + `Expected value of type "${typeStr}", found ${(0, _printer.print)( + node, + )}.`, + { + nodes: node, + }, + ), ); } + } catch (error) { + const typeStr = (0, _inspect.inspect)(locationType); - return inputValue; - }, - - parseLiteral(valueNode) { - if (valueNode.kind !== _kinds.Kind.BOOLEAN) { - throw new _GraphQLError.GraphQLError( - `Boolean cannot represent a non boolean value: ${(0, _printer.print)( - valueNode, - )}`, - { - nodes: valueNode, - }, + if (error instanceof _GraphQLError.GraphQLError) { + context.reportError(error); + } else { + context.reportError( + new _GraphQLError.GraphQLError( + `Expected value of type "${typeStr}", found ${(0, _printer.print)( + node, + )}; ` + error.message, + { + nodes: node, + originalError: error, + }, + ), ); } + } +} - return valueNode.value; - }, -}); -exports.GraphQLBoolean = GraphQLBoolean; -const GraphQLID = new _definition.GraphQLScalarType({ - name: 'ID', - description: - 'The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `"4"`) or integer (such as `4`) input value will be accepted as an ID.', - - serialize(outputValue) { - const coercedValue = serializeObject(outputValue); - - if (typeof coercedValue === 'string') { - return coercedValue; - } +function validateOneOfInputObject( + context, + node, + type, + fieldNodeMap, + variableDefinitions, +) { + var _fieldNodeMap$keys$; - if (Number.isInteger(coercedValue)) { - return String(coercedValue); - } + const keys = Object.keys(fieldNodeMap); + const isNotExactlyOneField = keys.length !== 1; - throw new _GraphQLError.GraphQLError( - `ID cannot represent value: ${(0, _inspect.inspect)(outputValue)}`, + if (isNotExactlyOneField) { + context.reportError( + new _GraphQLError.GraphQLError( + `OneOf Input Object "${type.name}" must specify exactly one key.`, + { + nodes: [node], + }, + ), ); - }, - - parseValue(inputValue) { - if (typeof inputValue === 'string') { - return inputValue; - } - - if (typeof inputValue === 'number' && Number.isInteger(inputValue)) { - return inputValue.toString(); - } + return; + } - throw new _GraphQLError.GraphQLError( - `ID cannot represent value: ${(0, _inspect.inspect)(inputValue)}`, - ); - }, + const value = + (_fieldNodeMap$keys$ = fieldNodeMap[keys[0]]) === null || + _fieldNodeMap$keys$ === void 0 + ? void 0 + : _fieldNodeMap$keys$.value; + const isNullLiteral = !value || value.kind === _kinds.Kind.NULL; + const isVariable = + (value === null || value === void 0 ? void 0 : value.kind) === + _kinds.Kind.VARIABLE; - parseLiteral(valueNode) { - if ( - valueNode.kind !== _kinds.Kind.STRING && - valueNode.kind !== _kinds.Kind.INT - ) { - throw new _GraphQLError.GraphQLError( - 'ID cannot represent a non-string and non-integer value: ' + - (0, _printer.print)(valueNode), + if (isNullLiteral) { + context.reportError( + new _GraphQLError.GraphQLError( + `Field "${type.name}.${keys[0]}" must be non-null.`, { - nodes: valueNode, + nodes: [node], }, - ); - } - - return valueNode.value; - }, -}); -exports.GraphQLID = GraphQLID; -const specifiedScalarTypes = Object.freeze([ - GraphQLString, - GraphQLInt, - GraphQLFloat, - GraphQLBoolean, - GraphQLID, -]); -exports.specifiedScalarTypes = specifiedScalarTypes; - -function isSpecifiedScalarType(type) { - return specifiedScalarTypes.some(({ name }) => type.name === name); -} // Support serializing objects with custom valueOf() or toJSON() functions - -// a common way to represent a complex value which can be represented as -// a string (ex: MongoDB id objects). - -function serializeObject(outputValue) { - if ((0, _isObjectLike.isObjectLike)(outputValue)) { - if (typeof outputValue.valueOf === 'function') { - const valueOfResult = outputValue.valueOf(); + ), + ); + return; + } - if (!(0, _isObjectLike.isObjectLike)(valueOfResult)) { - return valueOfResult; - } - } + if (isVariable) { + const variableName = value.name.value; + const definition = variableDefinitions[variableName]; + const isNullableVariable = + definition.type.kind !== _kinds.Kind.NON_NULL_TYPE; - if (typeof outputValue.toJSON === 'function') { - return outputValue.toJSON(); + if (isNullableVariable) { + context.reportError( + new _GraphQLError.GraphQLError( + `Variable "${variableName}" must be non-nullable to be used for OneOf Input Object "${type.name}".`, + { + nodes: [node], + }, + ), + ); } } - - return outputValue; } /***/ }), -/***/ 8505: +/***/ 99506: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -288510,408 +289667,330 @@ function serializeObject(outputValue) { Object.defineProperty(exports, "__esModule", ({ value: true, })); -exports.GraphQLSchema = void 0; -exports.assertSchema = assertSchema; -exports.isSchema = isSchema; - -var _devAssert = __nccwpck_require__(46514); - -var _inspect = __nccwpck_require__(10102); - -var _instanceOf = __nccwpck_require__(93481); - -var _isObjectLike = __nccwpck_require__(95865); +exports.VariablesAreInputTypesRule = VariablesAreInputTypesRule; -var _toObjMap = __nccwpck_require__(74728); +var _GraphQLError = __nccwpck_require__(4797); -var _ast = __nccwpck_require__(45494); +var _printer = __nccwpck_require__(68203); var _definition = __nccwpck_require__(32150); -var _directives = __nccwpck_require__(83614); - -var _introspection = __nccwpck_require__(28344); - -/** - * Test if the given value is a GraphQL schema. - */ -function isSchema(schema) { - return (0, _instanceOf.instanceOf)(schema, GraphQLSchema); -} - -function assertSchema(schema) { - if (!isSchema(schema)) { - throw new Error( - `Expected ${(0, _inspect.inspect)(schema)} to be a GraphQL schema.`, - ); - } - - return schema; -} -/** - * Custom extensions - * - * @remarks - * Use a unique identifier name for your extension, for example the name of - * your library or project. Do not use a shortened identifier as this increases - * the risk of conflicts. We recommend you add at most one extension field, - * an object which can contain all the values you need. - */ +var _typeFromAST = __nccwpck_require__(27664); /** - * Schema Definition - * - * A Schema is created by supplying the root types of each type of operation, - * query and mutation (optional). A schema definition is then supplied to the - * validator and executor. - * - * Example: - * - * ```ts - * const MyAppSchema = new GraphQLSchema({ - * query: MyAppQueryRootType, - * mutation: MyAppMutationRootType, - * }) - * ``` - * - * Note: When the schema is constructed, by default only the types that are - * reachable by traversing the root types are included, other types must be - * explicitly referenced. - * - * Example: - * - * ```ts - * const characterInterface = new GraphQLInterfaceType({ - * name: 'Character', - * ... - * }); - * - * const humanType = new GraphQLObjectType({ - * name: 'Human', - * interfaces: [characterInterface], - * ... - * }); - * - * const droidType = new GraphQLObjectType({ - * name: 'Droid', - * interfaces: [characterInterface], - * ... - * }); - * - * const schema = new GraphQLSchema({ - * query: new GraphQLObjectType({ - * name: 'Query', - * fields: { - * hero: { type: characterInterface, ... }, - * } - * }), - * ... - * // Since this schema references only the `Character` interface it's - * // necessary to explicitly list the types that implement it if - * // you want them to be included in the final schema. - * types: [humanType, droidType], - * }) - * ``` + * Variables are input types * - * Note: If an array of `directives` are provided to GraphQLSchema, that will be - * the exact list of directives represented and allowed. If `directives` is not - * provided then a default set of the specified directives (e.g. `@include` and - * `@skip`) will be used. If you wish to provide *additional* directives to these - * specified directives, you must explicitly declare them. Example: + * A GraphQL operation is only valid if all the variables it defines are of + * input types (scalar, enum, or input object). * - * ```ts - * const MyAppSchema = new GraphQLSchema({ - * ... - * directives: specifiedDirectives.concat([ myCustomDirective ]), - * }) - * ``` + * See https://spec.graphql.org/draft/#sec-Variables-Are-Input-Types */ -class GraphQLSchema { - // Used as a cache for validateSchema(). - constructor(config) { - var _config$extensionASTN, _config$directives; - - // If this schema was built from a source known to be valid, then it may be - // marked with assumeValid to avoid an additional type system validation. - this.__validationErrors = config.assumeValid === true ? [] : undefined; // Check for common mistakes during construction to produce early errors. - - (0, _isObjectLike.isObjectLike)(config) || - (0, _devAssert.devAssert)(false, 'Must provide configuration object.'); - !config.types || - Array.isArray(config.types) || - (0, _devAssert.devAssert)( - false, - `"types" must be Array if provided but got: ${(0, _inspect.inspect)( - config.types, - )}.`, - ); - !config.directives || - Array.isArray(config.directives) || - (0, _devAssert.devAssert)( - false, - '"directives" must be Array if provided but got: ' + - `${(0, _inspect.inspect)(config.directives)}.`, +function VariablesAreInputTypesRule(context) { + return { + VariableDefinition(node) { + const type = (0, _typeFromAST.typeFromAST)( + context.getSchema(), + node.type, ); - this.description = config.description; - this.extensions = (0, _toObjMap.toObjMap)(config.extensions); - this.astNode = config.astNode; - this.extensionASTNodes = - (_config$extensionASTN = config.extensionASTNodes) !== null && - _config$extensionASTN !== void 0 - ? _config$extensionASTN - : []; - this._queryType = config.query; - this._mutationType = config.mutation; - this._subscriptionType = config.subscription; // Provide specified directives (e.g. @include and @skip) by default. - this._directives = - (_config$directives = config.directives) !== null && - _config$directives !== void 0 - ? _config$directives - : _directives.specifiedDirectives; // To preserve order of user-provided types, we add first to add them to - // the set of "collected" types, so `collectReferencedTypes` ignore them. + if (type !== undefined && !(0, _definition.isInputType)(type)) { + const variableName = node.variable.name.value; + const typeName = (0, _printer.print)(node.type); + context.reportError( + new _GraphQLError.GraphQLError( + `Variable "$${variableName}" cannot be non-input type "${typeName}".`, + { + nodes: node.type, + }, + ), + ); + } + }, + }; +} - const allReferencedTypes = new Set(config.types); - if (config.types != null) { - for (const type of config.types) { - // When we ready to process this type, we remove it from "collected" types - // and then add it together with all dependent types in the correct position. - allReferencedTypes.delete(type); - collectReferencedTypes(type, allReferencedTypes); - } - } +/***/ }), - if (this._queryType != null) { - collectReferencedTypes(this._queryType, allReferencedTypes); - } +/***/ 8815: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (this._mutationType != null) { - collectReferencedTypes(this._mutationType, allReferencedTypes); - } +"use strict"; - if (this._subscriptionType != null) { - collectReferencedTypes(this._subscriptionType, allReferencedTypes); - } - for (const directive of this._directives) { - // Directives are not validated until validateSchema() is called. - if ((0, _directives.isDirective)(directive)) { - for (const arg of directive.args) { - collectReferencedTypes(arg.type, allReferencedTypes); - } - } - } +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.VariablesInAllowedPositionRule = VariablesInAllowedPositionRule; - collectReferencedTypes(_introspection.__Schema, allReferencedTypes); // Storing the resulting map for reference by the schema. +var _inspect = __nccwpck_require__(10102); - this._typeMap = Object.create(null); - this._subTypeMap = Object.create(null); // Keep track of all implementations by interface name. +var _GraphQLError = __nccwpck_require__(4797); - this._implementationsMap = Object.create(null); +var _kinds = __nccwpck_require__(11927); - for (const namedType of allReferencedTypes) { - if (namedType == null) { - continue; - } +var _definition = __nccwpck_require__(32150); - const typeName = namedType.name; - typeName || - (0, _devAssert.devAssert)( - false, - 'One of the provided types for building the Schema is missing a name.', - ); +var _typeComparators = __nccwpck_require__(10333); - if (this._typeMap[typeName] !== undefined) { - throw new Error( - `Schema must contain uniquely named types but contains multiple types named "${typeName}".`, - ); - } +var _typeFromAST = __nccwpck_require__(27664); - this._typeMap[typeName] = namedType; +/** + * Variables in allowed position + * + * Variable usages must be compatible with the arguments they are passed to. + * + * See https://spec.graphql.org/draft/#sec-All-Variable-Usages-are-Allowed + */ +function VariablesInAllowedPositionRule(context) { + let varDefMap = Object.create(null); + return { + OperationDefinition: { + enter() { + varDefMap = Object.create(null); + }, - if ((0, _definition.isInterfaceType)(namedType)) { - // Store implementations by interface. - for (const iface of namedType.getInterfaces()) { - if ((0, _definition.isInterfaceType)(iface)) { - let implementations = this._implementationsMap[iface.name]; + leave(operation) { + const usages = context.getRecursiveVariableUsages(operation); - if (implementations === undefined) { - implementations = this._implementationsMap[iface.name] = { - objects: [], - interfaces: [], - }; - } + for (const { node, type, defaultValue, parentType } of usages) { + const varName = node.name.value; + const varDef = varDefMap[varName]; - implementations.interfaces.push(namedType); - } - } - } else if ((0, _definition.isObjectType)(namedType)) { - // Store implementations by objects. - for (const iface of namedType.getInterfaces()) { - if ((0, _definition.isInterfaceType)(iface)) { - let implementations = this._implementationsMap[iface.name]; + if (varDef && type) { + // A var type is allowed if it is the same or more strict (e.g. is + // a subtype of) than the expected type. It can be more strict if + // the variable type is non-null when the expected type is nullable. + // If both are list types, the variable item type can be more strict + // than the expected item type (contravariant). + const schema = context.getSchema(); + const varType = (0, _typeFromAST.typeFromAST)(schema, varDef.type); - if (implementations === undefined) { - implementations = this._implementationsMap[iface.name] = { - objects: [], - interfaces: [], - }; + if ( + varType && + !allowedVariableUsage( + schema, + varType, + varDef.defaultValue, + type, + defaultValue, + ) + ) { + const varTypeStr = (0, _inspect.inspect)(varType); + const typeStr = (0, _inspect.inspect)(type); + context.reportError( + new _GraphQLError.GraphQLError( + `Variable "$${varName}" of type "${varTypeStr}" used in position expecting type "${typeStr}".`, + { + nodes: [varDef, node], + }, + ), + ); } - implementations.objects.push(namedType); + if ( + (0, _definition.isInputObjectType)(parentType) && + parentType.isOneOf && + (0, _definition.isNullableType)(varType) + ) { + context.reportError( + new _GraphQLError.GraphQLError( + `Variable "$${varName}" is of type "${varType}" but must be non-nullable to be used for OneOf Input Object "${parentType}".`, + { + nodes: [varDef, node], + }, + ), + ); + } } } - } - } - } - - get [Symbol.toStringTag]() { - return 'GraphQLSchema'; - } - - getQueryType() { - return this._queryType; - } - - getMutationType() { - return this._mutationType; - } - - getSubscriptionType() { - return this._subscriptionType; - } + }, + }, - getRootType(operation) { - switch (operation) { - case _ast.OperationTypeNode.QUERY: - return this.getQueryType(); + VariableDefinition(node) { + varDefMap[node.variable.name.value] = node; + }, + }; +} +/** + * Returns true if the variable is allowed in the location it was found, + * which includes considering if default values exist for either the variable + * or the location at which it is located. + */ - case _ast.OperationTypeNode.MUTATION: - return this.getMutationType(); +function allowedVariableUsage( + schema, + varType, + varDefaultValue, + locationType, + locationDefaultValue, +) { + if ( + (0, _definition.isNonNullType)(locationType) && + !(0, _definition.isNonNullType)(varType) + ) { + const hasNonNullVariableDefaultValue = + varDefaultValue != null && varDefaultValue.kind !== _kinds.Kind.NULL; + const hasLocationDefaultValue = locationDefaultValue !== undefined; - case _ast.OperationTypeNode.SUBSCRIPTION: - return this.getSubscriptionType(); + if (!hasNonNullVariableDefaultValue && !hasLocationDefaultValue) { + return false; } - } - - getTypeMap() { - return this._typeMap; - } - - getType(name) { - return this.getTypeMap()[name]; - } - getPossibleTypes(abstractType) { - return (0, _definition.isUnionType)(abstractType) - ? abstractType.getTypes() - : this.getImplementations(abstractType).objects; + const nullableLocationType = locationType.ofType; + return (0, _typeComparators.isTypeSubTypeOf)( + schema, + varType, + nullableLocationType, + ); } - getImplementations(interfaceType) { - const implementations = this._implementationsMap[interfaceType.name]; - return implementations !== null && implementations !== void 0 - ? implementations - : { - objects: [], - interfaces: [], - }; - } + return (0, _typeComparators.isTypeSubTypeOf)(schema, varType, locationType); +} - isSubType(abstractType, maybeSubType) { - let map = this._subTypeMap[abstractType.name]; - if (map === undefined) { - map = Object.create(null); +/***/ }), - if ((0, _definition.isUnionType)(abstractType)) { - for (const type of abstractType.getTypes()) { - map[type.name] = true; - } - } else { - const implementations = this.getImplementations(abstractType); +/***/ 33915: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - for (const type of implementations.objects) { - map[type.name] = true; - } +"use strict"; - for (const type of implementations.interfaces) { - map[type.name] = true; - } - } - this._subTypeMap[abstractType.name] = map; - } +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.NoDeprecatedCustomRule = NoDeprecatedCustomRule; - return map[maybeSubType.name] !== undefined; - } +var _invariant = __nccwpck_require__(28847); - getDirectives() { - return this._directives; - } +var _GraphQLError = __nccwpck_require__(4797); - getDirective(name) { - return this.getDirectives().find((directive) => directive.name === name); - } +var _definition = __nccwpck_require__(32150); - toConfig() { - return { - description: this.description, - query: this.getQueryType(), - mutation: this.getMutationType(), - subscription: this.getSubscriptionType(), - types: Object.values(this.getTypeMap()), - directives: this.getDirectives(), - extensions: this.extensions, - astNode: this.astNode, - extensionASTNodes: this.extensionASTNodes, - assumeValid: this.__validationErrors !== undefined, - }; - } -} +/** + * No deprecated + * + * A GraphQL document is only valid if all selected fields and all used enum values have not been + * deprecated. + * + * Note: This rule is optional and is not part of the Validation section of the GraphQL + * Specification. The main purpose of this rule is detection of deprecated usages and not + * necessarily to forbid their use when querying a service. + */ +function NoDeprecatedCustomRule(context) { + return { + Field(node) { + const fieldDef = context.getFieldDef(); + const deprecationReason = + fieldDef === null || fieldDef === void 0 + ? void 0 + : fieldDef.deprecationReason; -exports.GraphQLSchema = GraphQLSchema; + if (fieldDef && deprecationReason != null) { + const parentType = context.getParentType(); + parentType != null || (0, _invariant.invariant)(false); + context.reportError( + new _GraphQLError.GraphQLError( + `The field ${parentType.name}.${fieldDef.name} is deprecated. ${deprecationReason}`, + { + nodes: node, + }, + ), + ); + } + }, -function collectReferencedTypes(type, typeSet) { - const namedType = (0, _definition.getNamedType)(type); + Argument(node) { + const argDef = context.getArgument(); + const deprecationReason = + argDef === null || argDef === void 0 + ? void 0 + : argDef.deprecationReason; - if (!typeSet.has(namedType)) { - typeSet.add(namedType); + if (argDef && deprecationReason != null) { + const directiveDef = context.getDirective(); - if ((0, _definition.isUnionType)(namedType)) { - for (const memberType of namedType.getTypes()) { - collectReferencedTypes(memberType, typeSet); - } - } else if ( - (0, _definition.isObjectType)(namedType) || - (0, _definition.isInterfaceType)(namedType) - ) { - for (const interfaceType of namedType.getInterfaces()) { - collectReferencedTypes(interfaceType, typeSet); + if (directiveDef != null) { + context.reportError( + new _GraphQLError.GraphQLError( + `Directive "@${directiveDef.name}" argument "${argDef.name}" is deprecated. ${deprecationReason}`, + { + nodes: node, + }, + ), + ); + } else { + const parentType = context.getParentType(); + const fieldDef = context.getFieldDef(); + (parentType != null && fieldDef != null) || + (0, _invariant.invariant)(false); + context.reportError( + new _GraphQLError.GraphQLError( + `Field "${parentType.name}.${fieldDef.name}" argument "${argDef.name}" is deprecated. ${deprecationReason}`, + { + nodes: node, + }, + ), + ); + } } + }, - for (const field of Object.values(namedType.getFields())) { - collectReferencedTypes(field.type, typeSet); + ObjectField(node) { + const inputObjectDef = (0, _definition.getNamedType)( + context.getParentInputType(), + ); - for (const arg of field.args) { - collectReferencedTypes(arg.type, typeSet); + if ((0, _definition.isInputObjectType)(inputObjectDef)) { + const inputFieldDef = inputObjectDef.getFields()[node.name.value]; + const deprecationReason = + inputFieldDef === null || inputFieldDef === void 0 + ? void 0 + : inputFieldDef.deprecationReason; + + if (deprecationReason != null) { + context.reportError( + new _GraphQLError.GraphQLError( + `The input field ${inputObjectDef.name}.${inputFieldDef.name} is deprecated. ${deprecationReason}`, + { + nodes: node, + }, + ), + ); } } - } else if ((0, _definition.isInputObjectType)(namedType)) { - for (const field of Object.values(namedType.getFields())) { - collectReferencedTypes(field.type, typeSet); - } - } - } + }, - return typeSet; + EnumValue(node) { + const enumValueDef = context.getEnumValue(); + const deprecationReason = + enumValueDef === null || enumValueDef === void 0 + ? void 0 + : enumValueDef.deprecationReason; + + if (enumValueDef && deprecationReason != null) { + const enumTypeDef = (0, _definition.getNamedType)( + context.getInputType(), + ); + enumTypeDef != null || (0, _invariant.invariant)(false); + context.reportError( + new _GraphQLError.GraphQLError( + `The enum value "${enumTypeDef.name}.${enumValueDef.name}" is deprecated. ${deprecationReason}`, + { + nodes: node, + }, + ), + ); + } + }, + }; } /***/ }), -/***/ 22430: +/***/ 39478: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -288920,28668 +289999,28286 @@ function collectReferencedTypes(type, typeSet) { Object.defineProperty(exports, "__esModule", ({ value: true, })); -exports.assertValidSchema = assertValidSchema; -exports.validateSchema = validateSchema; - -var _inspect = __nccwpck_require__(10102); +exports.NoSchemaIntrospectionCustomRule = NoSchemaIntrospectionCustomRule; var _GraphQLError = __nccwpck_require__(4797); -var _ast = __nccwpck_require__(45494); - -var _typeComparators = __nccwpck_require__(10333); - var _definition = __nccwpck_require__(32150); -var _directives = __nccwpck_require__(83614); - var _introspection = __nccwpck_require__(28344); -var _schema = __nccwpck_require__(8505); - /** - * Implements the "Type Validation" sub-sections of the specification's - * "Type System" section. + * Prohibit introspection queries * - * Validation runs synchronously, returning an array of encountered errors, or - * an empty array if no errors were encountered and the Schema is valid. + * A GraphQL document is only valid if all fields selected are not fields that + * return an introspection type. + * + * Note: This rule is optional and is not part of the Validation section of the + * GraphQL Specification. This rule effectively disables introspection, which + * does not reflect best practices and should only be done if absolutely necessary. */ -function validateSchema(schema) { - // First check to ensure the provided value is in fact a GraphQLSchema. - (0, _schema.assertSchema)(schema); // If this Schema has already been validated, return the previous results. +function NoSchemaIntrospectionCustomRule(context) { + return { + Field(node) { + const type = (0, _definition.getNamedType)(context.getType()); - if (schema.__validationErrors) { - return schema.__validationErrors; - } // Validate the schema, producing a list of errors. + if (type && (0, _introspection.isIntrospectionType)(type)) { + context.reportError( + new _GraphQLError.GraphQLError( + `GraphQL introspection has been disabled, but the requested query contained the field "${node.name.value}".`, + { + nodes: node, + }, + ), + ); + } + }, + }; +} - const context = new SchemaValidationContext(schema); - validateRootTypes(context); - validateDirectives(context); - validateTypes(context); // Persist the results of validation before returning to ensure validation - // does not run multiple times for this schema. - const errors = context.getErrors(); - schema.__validationErrors = errors; - return errors; -} -/** - * Utility function which asserts a schema is valid by throwing an error if - * it is invalid. - */ +/***/ }), -function assertValidSchema(schema) { - const errors = validateSchema(schema); +/***/ 61556: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (errors.length !== 0) { - throw new Error(errors.map((error) => error.message).join('\n\n')); - } -} +"use strict"; -class SchemaValidationContext { - constructor(schema) { - this._errors = []; - this.schema = schema; - } - reportError(message, nodes) { - const _nodes = Array.isArray(nodes) ? nodes.filter(Boolean) : nodes; +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.specifiedSDLRules = + exports.specifiedRules = + exports.recommendedRules = + void 0; - this._errors.push( - new _GraphQLError.GraphQLError(message, { - nodes: _nodes, - }), - ); - } +var _ExecutableDefinitionsRule = __nccwpck_require__(89199); - getErrors() { - return this._errors; - } -} +var _FieldsOnCorrectTypeRule = __nccwpck_require__(63016); -function validateRootTypes(context) { - const schema = context.schema; - const queryType = schema.getQueryType(); +var _FragmentsOnCompositeTypesRule = __nccwpck_require__(60381); - if (!queryType) { - context.reportError('Query root type must be provided.', schema.astNode); - } else if (!(0, _definition.isObjectType)(queryType)) { - var _getOperationTypeNode; +var _KnownArgumentNamesRule = __nccwpck_require__(67147); - context.reportError( - `Query root type must be Object type, it cannot be ${(0, - _inspect.inspect)(queryType)}.`, - (_getOperationTypeNode = getOperationTypeNode( - schema, - _ast.OperationTypeNode.QUERY, - )) !== null && _getOperationTypeNode !== void 0 - ? _getOperationTypeNode - : queryType.astNode, - ); - } +var _KnownDirectivesRule = __nccwpck_require__(85303); - const mutationType = schema.getMutationType(); +var _KnownFragmentNamesRule = __nccwpck_require__(15166); - if (mutationType && !(0, _definition.isObjectType)(mutationType)) { - var _getOperationTypeNode2; +var _KnownTypeNamesRule = __nccwpck_require__(42509); - context.reportError( - 'Mutation root type must be Object type if provided, it cannot be ' + - `${(0, _inspect.inspect)(mutationType)}.`, - (_getOperationTypeNode2 = getOperationTypeNode( - schema, - _ast.OperationTypeNode.MUTATION, - )) !== null && _getOperationTypeNode2 !== void 0 - ? _getOperationTypeNode2 - : mutationType.astNode, - ); - } +var _LoneAnonymousOperationRule = __nccwpck_require__(45726); - const subscriptionType = schema.getSubscriptionType(); +var _LoneSchemaDefinitionRule = __nccwpck_require__(48307); - if (subscriptionType && !(0, _definition.isObjectType)(subscriptionType)) { - var _getOperationTypeNode3; +var _MaxIntrospectionDepthRule = __nccwpck_require__(53318); - context.reportError( - 'Subscription root type must be Object type if provided, it cannot be ' + - `${(0, _inspect.inspect)(subscriptionType)}.`, - (_getOperationTypeNode3 = getOperationTypeNode( - schema, - _ast.OperationTypeNode.SUBSCRIPTION, - )) !== null && _getOperationTypeNode3 !== void 0 - ? _getOperationTypeNode3 - : subscriptionType.astNode, - ); - } -} +var _NoFragmentCyclesRule = __nccwpck_require__(62564); -function getOperationTypeNode(schema, operation) { - var _flatMap$find; +var _NoUndefinedVariablesRule = __nccwpck_require__(61671); - return (_flatMap$find = [schema.astNode, ...schema.extensionASTNodes] - .flatMap( - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - (schemaNode) => { - var _schemaNode$operation; +var _NoUnusedFragmentsRule = __nccwpck_require__(192); - return ( - /* c8 ignore next */ - (_schemaNode$operation = - schemaNode === null || schemaNode === void 0 - ? void 0 - : schemaNode.operationTypes) !== null && - _schemaNode$operation !== void 0 - ? _schemaNode$operation - : [] - ); - }, - ) - .find((operationNode) => operationNode.operation === operation)) === null || - _flatMap$find === void 0 - ? void 0 - : _flatMap$find.type; -} +var _NoUnusedVariablesRule = __nccwpck_require__(40242); -function validateDirectives(context) { - for (const directive of context.schema.getDirectives()) { - // Ensure all directives are in fact GraphQL directives. - if (!(0, _directives.isDirective)(directive)) { - context.reportError( - `Expected directive but got: ${(0, _inspect.inspect)(directive)}.`, - directive === null || directive === void 0 ? void 0 : directive.astNode, - ); - continue; - } // Ensure they are named correctly. +var _OverlappingFieldsCanBeMergedRule = __nccwpck_require__(23577); - validateName(context, directive); +var _PossibleFragmentSpreadsRule = __nccwpck_require__(62450); - if (directive.locations.length === 0) { - context.reportError( - `Directive @${directive.name} must include 1 or more locations.`, - directive.astNode, - ); - } // Ensure the arguments are valid. +var _PossibleTypeExtensionsRule = __nccwpck_require__(70075); - for (const arg of directive.args) { - // Ensure they are named correctly. - validateName(context, arg); // Ensure the type is an input type. +var _ProvidedRequiredArgumentsRule = __nccwpck_require__(57669); - if (!(0, _definition.isInputType)(arg.type)) { - context.reportError( - `The type of @${directive.name}(${arg.name}:) must be Input Type ` + - `but got: ${(0, _inspect.inspect)(arg.type)}.`, - arg.astNode, - ); - } +var _ScalarLeafsRule = __nccwpck_require__(16830); - if ( - (0, _definition.isRequiredArgument)(arg) && - arg.deprecationReason != null - ) { - var _arg$astNode; +var _SingleFieldSubscriptionsRule = __nccwpck_require__(4365); - context.reportError( - `Required argument @${directive.name}(${arg.name}:) cannot be deprecated.`, - [ - getDeprecatedDirectiveNode(arg.astNode), - (_arg$astNode = arg.astNode) === null || _arg$astNode === void 0 - ? void 0 - : _arg$astNode.type, - ], - ); - } - } - } -} +var _UniqueArgumentDefinitionNamesRule = __nccwpck_require__(55104); -function validateName(context, node) { - // Ensure names are valid, however introspection types opt out. - if (node.name.startsWith('__')) { - context.reportError( - `Name "${node.name}" must not begin with "__", which is reserved by GraphQL introspection.`, - node.astNode, - ); - } -} +var _UniqueArgumentNamesRule = __nccwpck_require__(45799); -function validateTypes(context) { - const validateInputObjectCircularRefs = - createInputObjectCircularRefsValidator(context); - const typeMap = context.schema.getTypeMap(); +var _UniqueDirectiveNamesRule = __nccwpck_require__(17074); - for (const type of Object.values(typeMap)) { - // Ensure all provided types are in fact GraphQL type. - if (!(0, _definition.isNamedType)(type)) { - context.reportError( - `Expected GraphQL named type but got: ${(0, _inspect.inspect)(type)}.`, - type.astNode, - ); - continue; - } // Ensure it is named correctly (excluding introspection types). +var _UniqueDirectivesPerLocationRule = __nccwpck_require__(61944); - if (!(0, _introspection.isIntrospectionType)(type)) { - validateName(context, type); - } +var _UniqueEnumValueNamesRule = __nccwpck_require__(44437); - if ((0, _definition.isObjectType)(type)) { - // Ensure fields are valid - validateFields(context, type); // Ensure objects implement the interfaces they claim to. +var _UniqueFieldDefinitionNamesRule = __nccwpck_require__(9502); - validateInterfaces(context, type); - } else if ((0, _definition.isInterfaceType)(type)) { - // Ensure fields are valid. - validateFields(context, type); // Ensure interfaces implement the interfaces they claim to. +var _UniqueFragmentNamesRule = __nccwpck_require__(79402); - validateInterfaces(context, type); - } else if ((0, _definition.isUnionType)(type)) { - // Ensure Unions include valid member types. - validateUnionMembers(context, type); - } else if ((0, _definition.isEnumType)(type)) { - // Ensure Enums have valid values. - validateEnumValues(context, type); - } else if ((0, _definition.isInputObjectType)(type)) { - // Ensure Input Object fields are valid. - validateInputFields(context, type); // Ensure Input Objects do not contain non-nullable circular references +var _UniqueInputFieldNamesRule = __nccwpck_require__(83552); - validateInputObjectCircularRefs(type); - } - } -} +var _UniqueOperationNamesRule = __nccwpck_require__(94865); -function validateFields(context, type) { - const fields = Object.values(type.getFields()); // Objects and Interfaces both must define one or more fields. +var _UniqueOperationTypesRule = __nccwpck_require__(31492); - if (fields.length === 0) { - context.reportError(`Type ${type.name} must define one or more fields.`, [ - type.astNode, - ...type.extensionASTNodes, - ]); - } +var _UniqueTypeNamesRule = __nccwpck_require__(24316); - for (const field of fields) { - // Ensure they are named correctly. - validateName(context, field); // Ensure the type is an output type +var _UniqueVariableNamesRule = __nccwpck_require__(65931); - if (!(0, _definition.isOutputType)(field.type)) { - var _field$astNode; +var _ValuesOfCorrectTypeRule = __nccwpck_require__(85189); - context.reportError( - `The type of ${type.name}.${field.name} must be Output Type ` + - `but got: ${(0, _inspect.inspect)(field.type)}.`, - (_field$astNode = field.astNode) === null || _field$astNode === void 0 - ? void 0 - : _field$astNode.type, - ); - } // Ensure the arguments are valid +var _VariablesAreInputTypesRule = __nccwpck_require__(99506); - for (const arg of field.args) { - const argName = arg.name; // Ensure they are named correctly. +var _VariablesInAllowedPositionRule = __nccwpck_require__(8815); - validateName(context, arg); // Ensure the type is an input type +// Spec Section: "Executable Definitions" +// Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" +// Spec Section: "Fragments on Composite Types" +// Spec Section: "Argument Names" +// Spec Section: "Directives Are Defined" +// Spec Section: "Fragment spread target defined" +// Spec Section: "Fragment Spread Type Existence" +// Spec Section: "Lone Anonymous Operation" +// SDL-specific validation rules +// TODO: Spec Section +// Spec Section: "Fragments must not form cycles" +// Spec Section: "All Variable Used Defined" +// Spec Section: "Fragments must be used" +// Spec Section: "All Variables Used" +// Spec Section: "Field Selection Merging" +// Spec Section: "Fragment spread is possible" +// Spec Section: "Argument Optionality" +// Spec Section: "Leaf Field Selections" +// Spec Section: "Subscriptions with Single Root Field" +// Spec Section: "Argument Uniqueness" +// Spec Section: "Directives Are Unique Per Location" +// Spec Section: "Fragment Name Uniqueness" +// Spec Section: "Input Object Field Uniqueness" +// Spec Section: "Operation Name Uniqueness" +// Spec Section: "Variable Uniqueness" +// Spec Section: "Value Type Correctness" +// Spec Section: "Variables are Input Types" +// Spec Section: "All Variable Usages Are Allowed" - if (!(0, _definition.isInputType)(arg.type)) { - var _arg$astNode2; +/** + * Technically these aren't part of the spec but they are strongly encouraged + * validation rules. + */ +const recommendedRules = Object.freeze([ + _MaxIntrospectionDepthRule.MaxIntrospectionDepthRule, +]); +/** + * This set includes all validation rules defined by the GraphQL spec. + * + * The order of the rules in this list has been adjusted to lead to the + * most clear output when encountering multiple validation errors. + */ - context.reportError( - `The type of ${type.name}.${field.name}(${argName}:) must be Input ` + - `Type but got: ${(0, _inspect.inspect)(arg.type)}.`, - (_arg$astNode2 = arg.astNode) === null || _arg$astNode2 === void 0 - ? void 0 - : _arg$astNode2.type, - ); - } +exports.recommendedRules = recommendedRules; +const specifiedRules = Object.freeze([ + _ExecutableDefinitionsRule.ExecutableDefinitionsRule, + _UniqueOperationNamesRule.UniqueOperationNamesRule, + _LoneAnonymousOperationRule.LoneAnonymousOperationRule, + _SingleFieldSubscriptionsRule.SingleFieldSubscriptionsRule, + _KnownTypeNamesRule.KnownTypeNamesRule, + _FragmentsOnCompositeTypesRule.FragmentsOnCompositeTypesRule, + _VariablesAreInputTypesRule.VariablesAreInputTypesRule, + _ScalarLeafsRule.ScalarLeafsRule, + _FieldsOnCorrectTypeRule.FieldsOnCorrectTypeRule, + _UniqueFragmentNamesRule.UniqueFragmentNamesRule, + _KnownFragmentNamesRule.KnownFragmentNamesRule, + _NoUnusedFragmentsRule.NoUnusedFragmentsRule, + _PossibleFragmentSpreadsRule.PossibleFragmentSpreadsRule, + _NoFragmentCyclesRule.NoFragmentCyclesRule, + _UniqueVariableNamesRule.UniqueVariableNamesRule, + _NoUndefinedVariablesRule.NoUndefinedVariablesRule, + _NoUnusedVariablesRule.NoUnusedVariablesRule, + _KnownDirectivesRule.KnownDirectivesRule, + _UniqueDirectivesPerLocationRule.UniqueDirectivesPerLocationRule, + _KnownArgumentNamesRule.KnownArgumentNamesRule, + _UniqueArgumentNamesRule.UniqueArgumentNamesRule, + _ValuesOfCorrectTypeRule.ValuesOfCorrectTypeRule, + _ProvidedRequiredArgumentsRule.ProvidedRequiredArgumentsRule, + _VariablesInAllowedPositionRule.VariablesInAllowedPositionRule, + _OverlappingFieldsCanBeMergedRule.OverlappingFieldsCanBeMergedRule, + _UniqueInputFieldNamesRule.UniqueInputFieldNamesRule, + ...recommendedRules, +]); +/** + * @internal + */ - if ( - (0, _definition.isRequiredArgument)(arg) && - arg.deprecationReason != null - ) { - var _arg$astNode3; +exports.specifiedRules = specifiedRules; +const specifiedSDLRules = Object.freeze([ + _LoneSchemaDefinitionRule.LoneSchemaDefinitionRule, + _UniqueOperationTypesRule.UniqueOperationTypesRule, + _UniqueTypeNamesRule.UniqueTypeNamesRule, + _UniqueEnumValueNamesRule.UniqueEnumValueNamesRule, + _UniqueFieldDefinitionNamesRule.UniqueFieldDefinitionNamesRule, + _UniqueArgumentDefinitionNamesRule.UniqueArgumentDefinitionNamesRule, + _UniqueDirectiveNamesRule.UniqueDirectiveNamesRule, + _KnownTypeNamesRule.KnownTypeNamesRule, + _KnownDirectivesRule.KnownDirectivesRule, + _UniqueDirectivesPerLocationRule.UniqueDirectivesPerLocationRule, + _PossibleTypeExtensionsRule.PossibleTypeExtensionsRule, + _KnownArgumentNamesRule.KnownArgumentNamesOnDirectivesRule, + _UniqueArgumentNamesRule.UniqueArgumentNamesRule, + _UniqueInputFieldNamesRule.UniqueInputFieldNamesRule, + _ProvidedRequiredArgumentsRule.ProvidedRequiredArgumentsOnDirectivesRule, +]); +exports.specifiedSDLRules = specifiedSDLRules; - context.reportError( - `Required argument ${type.name}.${field.name}(${argName}:) cannot be deprecated.`, - [ - getDeprecatedDirectiveNode(arg.astNode), - (_arg$astNode3 = arg.astNode) === null || _arg$astNode3 === void 0 - ? void 0 - : _arg$astNode3.type, - ], - ); - } - } - } -} -function validateInterfaces(context, type) { - const ifaceTypeNames = Object.create(null); +/***/ }), - for (const iface of type.getInterfaces()) { - if (!(0, _definition.isInterfaceType)(iface)) { - context.reportError( - `Type ${(0, _inspect.inspect)( - type, - )} must only implement Interface types, ` + - `it cannot implement ${(0, _inspect.inspect)(iface)}.`, - getAllImplementsInterfaceNodes(type, iface), - ); - continue; - } +/***/ 14193: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (type === iface) { - context.reportError( - `Type ${type.name} cannot implement itself because it would create a circular reference.`, - getAllImplementsInterfaceNodes(type, iface), - ); - continue; - } +"use strict"; - if (ifaceTypeNames[iface.name]) { - context.reportError( - `Type ${type.name} can only implement ${iface.name} once.`, - getAllImplementsInterfaceNodes(type, iface), - ); - continue; - } - ifaceTypeNames[iface.name] = true; - validateTypeImplementsAncestors(context, type, iface); - validateTypeImplementsInterface(context, type, iface); - } -} +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.assertValidSDL = assertValidSDL; +exports.assertValidSDLExtension = assertValidSDLExtension; +exports.validate = validate; +exports.validateSDL = validateSDL; -function validateTypeImplementsInterface(context, type, iface) { - const typeFieldMap = type.getFields(); // Assert each interface field is implemented. +var _devAssert = __nccwpck_require__(46514); - for (const ifaceField of Object.values(iface.getFields())) { - const fieldName = ifaceField.name; - const typeField = typeFieldMap[fieldName]; // Assert interface field exists on type. +var _GraphQLError = __nccwpck_require__(4797); - if (!typeField) { - context.reportError( - `Interface field ${iface.name}.${fieldName} expected but ${type.name} does not provide it.`, - [ifaceField.astNode, type.astNode, ...type.extensionASTNodes], - ); - continue; - } // Assert interface field type is satisfied by type field type, by being - // a valid subtype. (covariant) +var _visitor = __nccwpck_require__(5678); - if ( - !(0, _typeComparators.isTypeSubTypeOf)( - context.schema, - typeField.type, - ifaceField.type, - ) - ) { - var _ifaceField$astNode, _typeField$astNode; +var _validate = __nccwpck_require__(22430); - context.reportError( - `Interface field ${iface.name}.${fieldName} expects type ` + - `${(0, _inspect.inspect)(ifaceField.type)} but ${ - type.name - }.${fieldName} ` + - `is type ${(0, _inspect.inspect)(typeField.type)}.`, - [ - (_ifaceField$astNode = ifaceField.astNode) === null || - _ifaceField$astNode === void 0 - ? void 0 - : _ifaceField$astNode.type, - (_typeField$astNode = typeField.astNode) === null || - _typeField$astNode === void 0 - ? void 0 - : _typeField$astNode.type, - ], - ); - } // Assert each interface field arg is implemented. +var _TypeInfo = __nccwpck_require__(76625); - for (const ifaceArg of ifaceField.args) { - const argName = ifaceArg.name; - const typeArg = typeField.args.find((arg) => arg.name === argName); // Assert interface field arg exists on object field. +var _specifiedRules = __nccwpck_require__(61556); - if (!typeArg) { - context.reportError( - `Interface field argument ${iface.name}.${fieldName}(${argName}:) expected but ${type.name}.${fieldName} does not provide it.`, - [ifaceArg.astNode, typeField.astNode], - ); - continue; - } // Assert interface field arg type matches object field arg type. - // (invariant) - // TODO: change to contravariant? +var _ValidationContext = __nccwpck_require__(28263); - if (!(0, _typeComparators.isEqualType)(ifaceArg.type, typeArg.type)) { - var _ifaceArg$astNode, _typeArg$astNode; +/** + * Implements the "Validation" section of the spec. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the document is valid. + * + * A list of specific validation rules may be provided. If not provided, the + * default list of rules defined by the GraphQL specification will be used. + * + * Each validation rules is a function which returns a visitor + * (see the language/visitor API). Visitor methods are expected to return + * GraphQLErrors, or Arrays of GraphQLErrors when invalid. + * + * Validate will stop validation after a `maxErrors` limit has been reached. + * Attackers can send pathologically invalid queries to induce a DoS attack, + * so by default `maxErrors` set to 100 errors. + * + * Optionally a custom TypeInfo instance may be provided. If not provided, one + * will be created from the provided schema. + */ +function validate( + schema, + documentAST, + rules = _specifiedRules.specifiedRules, + options, + /** @deprecated will be removed in 17.0.0 */ + typeInfo = new _TypeInfo.TypeInfo(schema), +) { + var _options$maxErrors; - context.reportError( - `Interface field argument ${iface.name}.${fieldName}(${argName}:) ` + - `expects type ${(0, _inspect.inspect)(ifaceArg.type)} but ` + - `${type.name}.${fieldName}(${argName}:) is type ` + - `${(0, _inspect.inspect)(typeArg.type)}.`, - [ - (_ifaceArg$astNode = ifaceArg.astNode) === null || - _ifaceArg$astNode === void 0 - ? void 0 - : _ifaceArg$astNode.type, - (_typeArg$astNode = typeArg.astNode) === null || - _typeArg$astNode === void 0 - ? void 0 - : _typeArg$astNode.type, - ], - ); - } // TODO: validate default values? - } // Assert additional arguments must not be required. + const maxErrors = + (_options$maxErrors = + options === null || options === void 0 ? void 0 : options.maxErrors) !== + null && _options$maxErrors !== void 0 + ? _options$maxErrors + : 100; + documentAST || (0, _devAssert.devAssert)(false, 'Must provide document.'); // If the schema used for validation is invalid, throw an error. - for (const typeArg of typeField.args) { - const argName = typeArg.name; - const ifaceArg = ifaceField.args.find((arg) => arg.name === argName); + (0, _validate.assertValidSchema)(schema); + const abortObj = Object.freeze({}); + const errors = []; + const context = new _ValidationContext.ValidationContext( + schema, + documentAST, + typeInfo, + (error) => { + if (errors.length >= maxErrors) { + errors.push( + new _GraphQLError.GraphQLError( + 'Too many validation errors, error limit reached. Validation aborted.', + ), + ); // eslint-disable-next-line @typescript-eslint/no-throw-literal - if (!ifaceArg && (0, _definition.isRequiredArgument)(typeArg)) { - context.reportError( - `Object field ${type.name}.${fieldName} includes required argument ${argName} that is missing from the Interface field ${iface.name}.${fieldName}.`, - [typeArg.astNode, ifaceField.astNode], - ); + throw abortObj; } - } - } -} -function validateTypeImplementsAncestors(context, type, iface) { - const ifaceInterfaces = type.getInterfaces(); - - for (const transitive of iface.getInterfaces()) { - if (!ifaceInterfaces.includes(transitive)) { - context.reportError( - transitive === type - ? `Type ${type.name} cannot implement ${iface.name} because it would create a circular reference.` - : `Type ${type.name} must implement ${transitive.name} because it is implemented by ${iface.name}.`, - [ - ...getAllImplementsInterfaceNodes(iface, transitive), - ...getAllImplementsInterfaceNodes(type, iface), - ], - ); - } - } -} + errors.push(error); + }, + ); // This uses a specialized visitor which runs multiple visitors in parallel, + // while maintaining the visitor skip and break API. -function validateUnionMembers(context, union) { - const memberTypes = union.getTypes(); + const visitor = (0, _visitor.visitInParallel)( + rules.map((rule) => rule(context)), + ); // Visit the whole document with each instance of all provided rules. - if (memberTypes.length === 0) { - context.reportError( - `Union type ${union.name} must define one or more member types.`, - [union.astNode, ...union.extensionASTNodes], + try { + (0, _visitor.visit)( + documentAST, + (0, _TypeInfo.visitWithTypeInfo)(typeInfo, visitor), ); - } - - const includedTypeNames = Object.create(null); - - for (const memberType of memberTypes) { - if (includedTypeNames[memberType.name]) { - context.reportError( - `Union type ${union.name} can only include type ${memberType.name} once.`, - getUnionMemberTypeNodes(union, memberType.name), - ); - continue; - } - - includedTypeNames[memberType.name] = true; - - if (!(0, _definition.isObjectType)(memberType)) { - context.reportError( - `Union type ${union.name} can only include Object types, ` + - `it cannot include ${(0, _inspect.inspect)(memberType)}.`, - getUnionMemberTypeNodes(union, String(memberType)), - ); + } catch (e) { + if (e !== abortObj) { + throw e; } } -} - -function validateEnumValues(context, enumType) { - const enumValues = enumType.getValues(); - - if (enumValues.length === 0) { - context.reportError( - `Enum type ${enumType.name} must define one or more values.`, - [enumType.astNode, ...enumType.extensionASTNodes], - ); - } - for (const enumValue of enumValues) { - // Ensure valid name. - validateName(context, enumValue); - } + return errors; } +/** + * @internal + */ -function validateInputFields(context, inputObj) { - const fields = Object.values(inputObj.getFields()); - - if (fields.length === 0) { - context.reportError( - `Input Object type ${inputObj.name} must define one or more fields.`, - [inputObj.astNode, ...inputObj.extensionASTNodes], - ); - } // Ensure the arguments are valid - - for (const field of fields) { - // Ensure they are named correctly. - validateName(context, field); // Ensure the type is an input type - - if (!(0, _definition.isInputType)(field.type)) { - var _field$astNode2; - - context.reportError( - `The type of ${inputObj.name}.${field.name} must be Input Type ` + - `but got: ${(0, _inspect.inspect)(field.type)}.`, - (_field$astNode2 = field.astNode) === null || _field$astNode2 === void 0 - ? void 0 - : _field$astNode2.type, - ); - } - - if ( - (0, _definition.isRequiredInputField)(field) && - field.deprecationReason != null - ) { - var _field$astNode3; +function validateSDL( + documentAST, + schemaToExtend, + rules = _specifiedRules.specifiedSDLRules, +) { + const errors = []; + const context = new _ValidationContext.SDLValidationContext( + documentAST, + schemaToExtend, + (error) => { + errors.push(error); + }, + ); + const visitors = rules.map((rule) => rule(context)); + (0, _visitor.visit)(documentAST, (0, _visitor.visitInParallel)(visitors)); + return errors; +} +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ - context.reportError( - `Required input field ${inputObj.name}.${field.name} cannot be deprecated.`, - [ - getDeprecatedDirectiveNode(field.astNode), - (_field$astNode3 = field.astNode) === null || - _field$astNode3 === void 0 - ? void 0 - : _field$astNode3.type, - ], - ); - } +function assertValidSDL(documentAST) { + const errors = validateSDL(documentAST); - if (inputObj.isOneOf) { - validateOneOfInputObjectField(inputObj, field, context); - } + if (errors.length !== 0) { + throw new Error(errors.map((error) => error.message).join('\n\n')); } } +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ -function validateOneOfInputObjectField(type, field, context) { - if ((0, _definition.isNonNullType)(field.type)) { - var _field$astNode4; - - context.reportError( - `OneOf input field ${type.name}.${field.name} must be nullable.`, - (_field$astNode4 = field.astNode) === null || _field$astNode4 === void 0 - ? void 0 - : _field$astNode4.type, - ); - } +function assertValidSDLExtension(documentAST, schema) { + const errors = validateSDL(documentAST, schema); - if (field.defaultValue !== undefined) { - context.reportError( - `OneOf input field ${type.name}.${field.name} cannot have a default value.`, - field.astNode, - ); + if (errors.length !== 0) { + throw new Error(errors.map((error) => error.message).join('\n\n')); } } -function createInputObjectCircularRefsValidator(context) { - // Modified copy of algorithm from 'src/validation/rules/NoFragmentCycles.js'. - // Tracks already visited types to maintain O(N) and to ensure that cycles - // are not redundantly reported. - const visitedTypes = Object.create(null); // Array of types nodes used to produce meaningful errors - - const fieldPath = []; // Position in the type path - - const fieldPathIndexByTypeName = Object.create(null); - return detectCycleRecursive; // This does a straight-forward DFS to find cycles. - // It does not terminate when a cycle was found but continues to explore - // the graph to find all possible cycles. - - function detectCycleRecursive(inputObj) { - if (visitedTypes[inputObj.name]) { - return; - } - visitedTypes[inputObj.name] = true; - fieldPathIndexByTypeName[inputObj.name] = fieldPath.length; - const fields = Object.values(inputObj.getFields()); +/***/ }), - for (const field of fields) { - if ( - (0, _definition.isNonNullType)(field.type) && - (0, _definition.isInputObjectType)(field.type.ofType) - ) { - const fieldType = field.type.ofType; - const cycleIndex = fieldPathIndexByTypeName[fieldType.name]; - fieldPath.push(field); +/***/ 81923: +/***/ ((__unused_webpack_module, exports) => { - if (cycleIndex === undefined) { - detectCycleRecursive(fieldType); - } else { - const cyclePath = fieldPath.slice(cycleIndex); - const pathStr = cyclePath.map((fieldObj) => fieldObj.name).join('.'); - context.reportError( - `Cannot reference Input Object "${fieldType.name}" within itself through a series of non-null fields: "${pathStr}".`, - cyclePath.map((fieldObj) => fieldObj.astNode), - ); - } +"use strict"; - fieldPath.pop(); - } - } - fieldPathIndexByTypeName[inputObj.name] = undefined; - } -} +Object.defineProperty(exports, "__esModule", ({ + value: true, +})); +exports.versionInfo = exports.version = void 0; +// Note: This file is autogenerated using "resources/gen-version.js" script and +// automatically updated by "npm version" command. -function getAllImplementsInterfaceNodes(type, iface) { - const { astNode, extensionASTNodes } = type; - const nodes = - astNode != null ? [astNode, ...extensionASTNodes] : extensionASTNodes; // FIXME: https://github.com/graphql/graphql-js/issues/2203 +/** + * A string containing the version of the GraphQL.js library + */ +const version = '16.11.0'; +/** + * An object containing the components of the GraphQL.js version string + */ - return nodes - .flatMap((typeNode) => { - var _typeNode$interfaces; +exports.version = version; +const versionInfo = Object.freeze({ + major: 16, + minor: 11, + patch: 0, + preReleaseTag: null, +}); +exports.versionInfo = versionInfo; - return ( - /* c8 ignore next */ - (_typeNode$interfaces = typeNode.interfaces) !== null && - _typeNode$interfaces !== void 0 - ? _typeNode$interfaces - : [] - ); - }) - .filter((ifaceNode) => ifaceNode.name.value === iface.name); -} -function getUnionMemberTypeNodes(union, typeName) { - const { astNode, extensionASTNodes } = union; - const nodes = - astNode != null ? [astNode, ...extensionASTNodes] : extensionASTNodes; // FIXME: https://github.com/graphql/graphql-js/issues/2203 +/***/ }), - return nodes - .flatMap((unionNode) => { - var _unionNode$types; +/***/ 13679: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return ( - /* c8 ignore next */ - (_unionNode$types = unionNode.types) !== null && - _unionNode$types !== void 0 - ? _unionNode$types - : [] - ); - }) - .filter((typeNode) => typeNode.name.value === typeName); -} +"use strict"; -function getDeprecatedDirectiveNode(definitionNode) { - var _definitionNode$direc; - return definitionNode === null || definitionNode === void 0 - ? void 0 - : (_definitionNode$direc = definitionNode.directives) === null || - _definitionNode$direc === void 0 - ? void 0 - : _definitionNode$direc.find( - (node) => - node.name.value === _directives.GraphQLDeprecatedDirective.name, - ); +module.exports = { + afterRequest: __nccwpck_require__(83932), + beforeRequest: __nccwpck_require__(36136), + browser: __nccwpck_require__(805), + cache: __nccwpck_require__(51632), + content: __nccwpck_require__(61567), + cookie: __nccwpck_require__(25725), + creator: __nccwpck_require__(47218), + entry: __nccwpck_require__(74560), + har: __nccwpck_require__(75579), + header: __nccwpck_require__(75147), + log: __nccwpck_require__(53013), + page: __nccwpck_require__(34777), + pageTimings: __nccwpck_require__(5538), + postData: __nccwpck_require__(12096), + query: __nccwpck_require__(21251), + request: __nccwpck_require__(99646), + response: __nccwpck_require__(9103), + timings: __nccwpck_require__(22007) } /***/ }), -/***/ 76625: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 74944: +/***/ ((module) => { -"use strict"; +function HARError (errors) { + var message = 'validation failed' + this.name = 'HARError' + this.message = message + this.errors = errors -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.TypeInfo = void 0; -exports.visitWithTypeInfo = visitWithTypeInfo; + if (typeof Error.captureStackTrace === 'function') { + Error.captureStackTrace(this, this.constructor) + } else { + this.stack = (new Error(message)).stack + } +} -var _ast = __nccwpck_require__(45494); +HARError.prototype = Error.prototype -var _kinds = __nccwpck_require__(11927); +module.exports = HARError -var _visitor = __nccwpck_require__(5678); -var _definition = __nccwpck_require__(32150); +/***/ }), -var _introspection = __nccwpck_require__(28344); +/***/ 75697: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var _typeFromAST = __nccwpck_require__(27664); +var Ajv = __nccwpck_require__(64941) +var HARError = __nccwpck_require__(74944) +var schemas = __nccwpck_require__(13679) -/** - * TypeInfo is a utility class which, given a GraphQL schema, can keep track - * of the current field and type definitions at any point in a GraphQL document - * AST during a recursive descent by calling `enter(node)` and `leave(node)`. - */ -class TypeInfo { - constructor( - schema, - /** - * Initial type may be provided in rare cases to facilitate traversals - * beginning somewhere other than documents. - */ - initialType, - /** @deprecated will be removed in 17.0.0 */ - getFieldDefFn, - ) { - this._schema = schema; - this._typeStack = []; - this._parentTypeStack = []; - this._inputTypeStack = []; - this._fieldDefStack = []; - this._defaultValueStack = []; - this._directive = null; - this._argument = null; - this._enumValue = null; - this._getFieldDef = - getFieldDefFn !== null && getFieldDefFn !== void 0 - ? getFieldDefFn - : getFieldDef; +var ajv - if (initialType) { - if ((0, _definition.isInputType)(initialType)) { - this._inputTypeStack.push(initialType); - } +function createAjvInstance () { + var ajv = new Ajv({ + allErrors: true + }) + ajv.addMetaSchema(__nccwpck_require__(96273)) + ajv.addSchema(schemas) - if ((0, _definition.isCompositeType)(initialType)) { - this._parentTypeStack.push(initialType); - } + return ajv +} - if ((0, _definition.isOutputType)(initialType)) { - this._typeStack.push(initialType); - } - } - } +function validate (name, data) { + data = data || {} - get [Symbol.toStringTag]() { - return 'TypeInfo'; - } + // validator config + ajv = ajv || createAjvInstance() - getType() { - if (this._typeStack.length > 0) { - return this._typeStack[this._typeStack.length - 1]; - } - } + var validate = ajv.getSchema(name + '.json') - getParentType() { - if (this._parentTypeStack.length > 0) { - return this._parentTypeStack[this._parentTypeStack.length - 1]; - } - } + return new Promise(function (resolve, reject) { + var valid = validate(data) - getInputType() { - if (this._inputTypeStack.length > 0) { - return this._inputTypeStack[this._inputTypeStack.length - 1]; - } - } + !valid ? reject(new HARError(validate.errors)) : resolve(data) + }) +} - getParentInputType() { - if (this._inputTypeStack.length > 1) { - return this._inputTypeStack[this._inputTypeStack.length - 2]; - } - } +exports.afterRequest = function (data) { + return validate('afterRequest', data) +} - getFieldDef() { - if (this._fieldDefStack.length > 0) { - return this._fieldDefStack[this._fieldDefStack.length - 1]; - } - } +exports.beforeRequest = function (data) { + return validate('beforeRequest', data) +} - getDefaultValue() { - if (this._defaultValueStack.length > 0) { - return this._defaultValueStack[this._defaultValueStack.length - 1]; - } - } +exports.browser = function (data) { + return validate('browser', data) +} - getDirective() { - return this._directive; - } +exports.cache = function (data) { + return validate('cache', data) +} - getArgument() { - return this._argument; - } +exports.content = function (data) { + return validate('content', data) +} - getEnumValue() { - return this._enumValue; - } +exports.cookie = function (data) { + return validate('cookie', data) +} - enter(node) { - const schema = this._schema; // Note: many of the types below are explicitly typed as "unknown" to drop - // any assumptions of a valid schema to ensure runtime types are properly - // checked before continuing since TypeInfo is used as part of validation - // which occurs before guarantees of schema and document validity. +exports.creator = function (data) { + return validate('creator', data) +} - switch (node.kind) { - case _kinds.Kind.SELECTION_SET: { - const namedType = (0, _definition.getNamedType)(this.getType()); +exports.entry = function (data) { + return validate('entry', data) +} - this._parentTypeStack.push( - (0, _definition.isCompositeType)(namedType) ? namedType : undefined, - ); +exports.har = function (data) { + return validate('har', data) +} - break; - } +exports.header = function (data) { + return validate('header', data) +} - case _kinds.Kind.FIELD: { - const parentType = this.getParentType(); - let fieldDef; - let fieldType; +exports.log = function (data) { + return validate('log', data) +} - if (parentType) { - fieldDef = this._getFieldDef(schema, parentType, node); +exports.page = function (data) { + return validate('page', data) +} - if (fieldDef) { - fieldType = fieldDef.type; - } - } +exports.pageTimings = function (data) { + return validate('pageTimings', data) +} - this._fieldDefStack.push(fieldDef); +exports.postData = function (data) { + return validate('postData', data) +} - this._typeStack.push( - (0, _definition.isOutputType)(fieldType) ? fieldType : undefined, - ); +exports.query = function (data) { + return validate('query', data) +} - break; - } +exports.request = function (data) { + return validate('request', data) +} - case _kinds.Kind.DIRECTIVE: - this._directive = schema.getDirective(node.name.value); - break; +exports.response = function (data) { + return validate('response', data) +} - case _kinds.Kind.OPERATION_DEFINITION: { - const rootType = schema.getRootType(node.operation); +exports.timings = function (data) { + return validate('timings', data) +} - this._typeStack.push( - (0, _definition.isObjectType)(rootType) ? rootType : undefined, - ); - break; - } +/***/ }), - case _kinds.Kind.INLINE_FRAGMENT: - case _kinds.Kind.FRAGMENT_DEFINITION: { - const typeConditionAST = node.typeCondition; - const outputType = typeConditionAST - ? (0, _typeFromAST.typeFromAST)(schema, typeConditionAST) - : (0, _definition.getNamedType)(this.getType()); +/***/ 31621: +/***/ ((module) => { - this._typeStack.push( - (0, _definition.isOutputType)(outputType) ? outputType : undefined, - ); +"use strict"; - break; - } - case _kinds.Kind.VARIABLE_DEFINITION: { - const inputType = (0, _typeFromAST.typeFromAST)(schema, node.type); +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); +}; - this._inputTypeStack.push( - (0, _definition.isInputType)(inputType) ? inputType : undefined, - ); - break; - } +/***/ }), - case _kinds.Kind.ARGUMENT: { - var _this$getDirective; +/***/ 57747: +/***/ ((module) => { - let argDef; - let argType; - const fieldOrDirective = - (_this$getDirective = this.getDirective()) !== null && - _this$getDirective !== void 0 - ? _this$getDirective - : this.getFieldDef(); +"use strict"; - if (fieldOrDirective) { - argDef = fieldOrDirective.args.find( - (arg) => arg.name === node.name.value, - ); - if (argDef) { - argType = argDef.type; - } - } +/* eslint complexity: [2, 18], max-statements: [2, 33] */ +module.exports = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } - this._argument = argDef; + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } - this._defaultValueStack.push(argDef ? argDef.defaultValue : undefined); + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } - this._inputTypeStack.push( - (0, _definition.isInputType)(argType) ? argType : undefined, - ); + // temp disabled per https://github.com/ljharb/object.assign/issues/17 + // if (sym instanceof Symbol) { return false; } + // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + // if (!(symObj instanceof Symbol)) { return false; } - break; - } + // if (typeof Symbol.prototype.toString !== 'function') { return false; } + // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } - case _kinds.Kind.LIST: { - const listType = (0, _definition.getNullableType)(this.getInputType()); - const itemType = (0, _definition.isListType)(listType) - ? listType.ofType - : listType; // List positions never have a default value. + var symVal = 42; + obj[sym] = symVal; + for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } - this._defaultValueStack.push(undefined); + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } - this._inputTypeStack.push( - (0, _definition.isInputType)(itemType) ? itemType : undefined, - ); + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } - break; - } + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } - case _kinds.Kind.OBJECT_FIELD: { - const objectType = (0, _definition.getNamedType)(this.getInputType()); - let inputFieldType; - let inputField; + if (typeof Object.getOwnPropertyDescriptor === 'function') { + var descriptor = Object.getOwnPropertyDescriptor(obj, sym); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } - if ((0, _definition.isInputObjectType)(objectType)) { - inputField = objectType.getFields()[node.name.value]; + return true; +}; - if (inputField) { - inputFieldType = inputField.type; - } - } - this._defaultValueStack.push( - inputField ? inputField.defaultValue : undefined, - ); +/***/ }), - this._inputTypeStack.push( - (0, _definition.isInputType)(inputFieldType) - ? inputFieldType - : undefined, - ); +/***/ 62157: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - break; - } +"use strict"; - case _kinds.Kind.ENUM: { - const enumType = (0, _definition.getNamedType)(this.getInputType()); - let enumValue; - if ((0, _definition.isEnumType)(enumType)) { - enumValue = enumType.getValue(node.value); - } +var call = Function.prototype.call; +var $hasOwn = Object.prototype.hasOwnProperty; +var bind = __nccwpck_require__(37138); - this._enumValue = enumValue; - break; - } +/** @type {import('.')} */ +module.exports = bind.call(call, $hasOwn); - default: // Ignore other nodes - } - } - leave(node) { - switch (node.kind) { - case _kinds.Kind.SELECTION_SET: - this._parentTypeStack.pop(); +/***/ }), - break; +/***/ 29788: +/***/ ((module) => { - case _kinds.Kind.FIELD: - this._fieldDefStack.pop(); +"use strict"; - this._typeStack.pop(); - break; +/* eslint no-invalid-this: 1 */ - case _kinds.Kind.DIRECTIVE: - this._directive = null; - break; +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var toStr = Object.prototype.toString; +var max = Math.max; +var funcType = '[object Function]'; - case _kinds.Kind.OPERATION_DEFINITION: - case _kinds.Kind.INLINE_FRAGMENT: - case _kinds.Kind.FRAGMENT_DEFINITION: - this._typeStack.pop(); +var concatty = function concatty(a, b) { + var arr = []; - break; + for (var i = 0; i < a.length; i += 1) { + arr[i] = a[i]; + } + for (var j = 0; j < b.length; j += 1) { + arr[j + a.length] = b[j]; + } - case _kinds.Kind.VARIABLE_DEFINITION: - this._inputTypeStack.pop(); + return arr; +}; - break; +var slicy = function slicy(arrLike, offset) { + var arr = []; + for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { + arr[j] = arrLike[i]; + } + return arr; +}; - case _kinds.Kind.ARGUMENT: - this._argument = null; +var joiny = function (arr, joiner) { + var str = ''; + for (var i = 0; i < arr.length; i += 1) { + str += arr[i]; + if (i + 1 < arr.length) { + str += joiner; + } + } + return str; +}; - this._defaultValueStack.pop(); +module.exports = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.apply(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slicy(arguments, 1); - this._inputTypeStack.pop(); + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + concatty(args, arguments) + ); + if (Object(result) === result) { + return result; + } + return this; + } + return target.apply( + that, + concatty(args, arguments) + ); - break; + }; - case _kinds.Kind.LIST: - case _kinds.Kind.OBJECT_FIELD: - this._defaultValueStack.pop(); + var boundLength = max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs[i] = '$' + i; + } - this._inputTypeStack.pop(); + bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); - break; + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } - case _kinds.Kind.ENUM: - this._enumValue = null; - break; + return bound; +}; - default: // Ignore other nodes - } - } -} -exports.TypeInfo = TypeInfo; +/***/ }), -/** - * Not exactly the same as the executor's definition of getFieldDef, in this - * statically evaluated environment we do not always have an Object type, - * and need to handle Interface and Union types. - */ -function getFieldDef(schema, parentType, fieldNode) { - const name = fieldNode.name.value; +/***/ 37138: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if ( - name === _introspection.SchemaMetaFieldDef.name && - schema.getQueryType() === parentType - ) { - return _introspection.SchemaMetaFieldDef; - } +"use strict"; - if ( - name === _introspection.TypeMetaFieldDef.name && - schema.getQueryType() === parentType - ) { - return _introspection.TypeMetaFieldDef; - } - if ( - name === _introspection.TypeNameMetaFieldDef.name && - (0, _definition.isCompositeType)(parentType) - ) { - return _introspection.TypeNameMetaFieldDef; - } +var implementation = __nccwpck_require__(29788); - if ( - (0, _definition.isObjectType)(parentType) || - (0, _definition.isInterfaceType)(parentType) - ) { - return parentType.getFields()[name]; - } -} -/** - * Creates a new visitor instance which maintains a provided TypeInfo instance - * along with visiting visitor. - */ +module.exports = Function.prototype.bind || implementation; -function visitWithTypeInfo(typeInfo, visitor) { - return { - enter(...args) { - const node = args[0]; - typeInfo.enter(node); - const fn = (0, _visitor.getEnterLeaveForKind)(visitor, node.kind).enter; - if (fn) { - const result = fn.apply(visitor, args); +/***/ }), - if (result !== undefined) { - typeInfo.leave(node); +/***/ 61002: +/***/ ((module) => { - if ((0, _ast.isNode)(result)) { - typeInfo.enter(result); - } - } +"use strict"; - return result; - } - }, +// rfc7231 6.1 +const statusCodeCacheableByDefault = new Set([ + 200, + 203, + 204, + 206, + 300, + 301, + 308, + 404, + 405, + 410, + 414, + 501, +]); - leave(...args) { - const node = args[0]; - const fn = (0, _visitor.getEnterLeaveForKind)(visitor, node.kind).leave; - let result; +// 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, +]); - if (fn) { - result = fn.apply(visitor, args); - } +const errorStatusCodes = new Set([ + 500, + 502, + 503, + 504, +]); - typeInfo.leave(node); - return result; - }, - }; +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; -/***/ 25780: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // 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, ''); + } -"use strict"; + 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(', '); +} -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.assertValidName = assertValidName; -exports.isValidNameError = isValidNameError; +module.exports = class CachePolicy { + constructor( + req, + res, + { + shared, + cacheHeuristic, + immutableMinTimeToLive, + ignoreCargoCult, + _fromObject, + } = {} + ) { + if (_fromObject) { + this._fromObject(_fromObject); + return; + } -var _devAssert = __nccwpck_require__(46514); + if (!res || !res.headers) { + throw Error('Response headers missing'); + } + this._assertRequestHasHeaders(req); -var _GraphQLError = __nccwpck_require__(4797); + 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; -var _assertName = __nccwpck_require__(74947); + 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']); -/* c8 ignore start */ + // 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; + } -/** - * Upholds the spec rules about naming. - * @deprecated Please use `assertName` instead. Will be removed in v17 - */ -function assertValidName(name) { - const error = isValidNameError(name); + // 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; + } + } - if (error) { - throw error; - } + now() { + return Date.now(); + } - return name; -} -/** - * Returns an Error if a name is invalid. - * @deprecated Please use `assertName` instead. Will be removed in v17 - */ + 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)) + ); + } -function isValidNameError(name) { - typeof name === 'string' || - (0, _devAssert.devAssert)(false, 'Expected name to be a string.'); + _hasExplicitExpiration() { + // 4.2.1 Calculating Freshness Lifetime + return ( + (this._isShared && this._rescc['s-maxage']) || + this._rescc['max-age'] || + this._resHeaders.expires + ); + } - if (name.startsWith('__')) { - return new _GraphQLError.GraphQLError( - `Name "${name}" must not begin with "__", which is reserved by GraphQL introspection.`, - ); - } + _assertRequestHasHeaders(req) { + if (!req || !req.headers) { + throw Error('Request headers missing'); + } + } - try { - (0, _assertName.assertName)(name); - } catch (error) { - return error; - } -} -/* c8 ignore stop */ + 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; + } -/***/ 12653: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if ( + requestCC['min-fresh'] && + this.timeToLive() < 1000 * requestCC['min-fresh'] + ) { + return false; + } -"use strict"; + // 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 this._requestMatches(req, false); + } -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.astFromValue = astFromValue; + _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 _inspect = __nccwpck_require__(10102); + _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 _invariant = __nccwpck_require__(28847); + _varyMatches(req) { + if (!this._resHeaders.vary) { + return true; + } -var _isIterableObject = __nccwpck_require__(81258); + // A Vary header field-value of "*" always fails to match + if (this._resHeaders.vary === '*') { + return false; + } -var _isObjectLike = __nccwpck_require__(95865); + 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; + } -var _kinds = __nccwpck_require__(11927); + _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; + } -var _definition = __nccwpck_require__(32150); + responseHeaders() { + const headers = this._copyWithoutHopByHopHeaders(this._resHeaders); + const age = this.age(); -var _scalars = __nccwpck_require__(93145); + // 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; + } -/** - * Produces a GraphQL Value AST given a JavaScript object. - * Function will match JavaScript/JSON values to GraphQL AST schema format - * by using suggested GraphQLInputType. For example: - * - * astFromValue("value", GraphQLString) - * - * A GraphQL type must be provided, which will be used to interpret different - * JavaScript values. - * - * | JSON Value | GraphQL Value | - * | ------------- | -------------------- | - * | Object | Input Object | - * | Array | List | - * | Boolean | Boolean | - * | String | String / Enum Value | - * | Number | Int / Float | - * | Unknown | Enum Value | - * | null | NullValue | - * - */ -function astFromValue(value, type) { - if ((0, _definition.isNonNullType)(type)) { - const astValue = astFromValue(value, type.ofType); + /** + * 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; + } - if ( - (astValue === null || astValue === void 0 ? void 0 : astValue.kind) === - _kinds.Kind.NULL - ) { - return null; + /** + * Value of the Age header, in seconds, updated for the current time. + * May be fractional. + * + * @return Number + */ + age() { + let age = this._ageValue(); + + const residentTime = (this.now() - this._responseTime) / 1000; + return age + residentTime; } - return astValue; - } // only explicit null, not undefined, NaN + _ageValue() { + return toNumberOrZero(this._resHeaders.age); + } - if (value === null) { - return { - kind: _kinds.Kind.NULL, - }; - } // undefined + /** + * 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; + } - if (value === undefined) { - return null; - } // Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but - // the value is not an array, convert the value using the list's item type. + // 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; + } + + 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']); + } + } - if ((0, _definition.isListType)(type)) { - const itemType = type.ofType; + // 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']); + } - if ((0, _isIterableObject.isIterableObject)(value)) { - const valuesNodes = []; + const defaultMinTtl = this._rescc.immutable ? this._immutableMinTtl : 0; - for (const item of value) { - const itemNode = astFromValue(item, itemType); + 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); + } - if (itemNode != null) { - valuesNodes.push(itemNode); + 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 { - kind: _kinds.Kind.LIST, - values: valuesNodes, - }; + return defaultMinTtl; } - return astFromValue(value, itemType); - } // Populate the fields of the input object by creating ASTs from each value - // in the JavaScript object according to the fields in the input type. - - if ((0, _definition.isInputObjectType)(type)) { - if (!(0, _isObjectLike.isObjectLike)(value)) { - return null; + 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; } - const fieldNodes = []; - - for (const field of Object.values(type.getFields())) { - const fieldValue = astFromValue(value[field.name], field.type); - - if (fieldValue) { - fieldNodes.push({ - kind: _kinds.Kind.OBJECT_FIELD, - name: { - kind: _kinds.Kind.NAME, - value: field.name, - }, - value: fieldValue, - }); - } + stale() { + return this.maxAge() <= this.age(); } - return { - kind: _kinds.Kind.OBJECT, - fields: fieldNodes, - }; - } + _useStaleIfError() { + return this.maxAge() + toNumberOrZero(this._rescc['stale-if-error']) > this.age(); + } - if ((0, _definition.isLeafType)(type)) { - // Since value is an internally represented value, it must be serialized - // to an externally represented value before converting into an AST. - const serialized = type.serialize(value); + useStaleWhileRevalidate() { + return this.maxAge() + toNumberOrZero(this._rescc['stale-while-revalidate']) > this.age(); + } - if (serialized == null) { - return null; - } // Others serialize based on their corresponding JavaScript scalar types. + static fromObject(obj) { + return new this(undefined, undefined, { _fromObject: obj }); + } - if (typeof serialized === 'boolean') { - return { - kind: _kinds.Kind.BOOLEAN, - value: serialized, - }; - } // JavaScript numbers can be Int or Float values. + _fromObject(obj) { + if (this._responseTime) throw Error('Reinitialized'); + if (!obj || obj.v !== 1) throw Error('Invalid serialization'); - if (typeof serialized === 'number' && Number.isFinite(serialized)) { - const stringNum = String(serialized); - return integerStringRegExp.test(stringNum) - ? { - kind: _kinds.Kind.INT, - value: stringNum, - } - : { - kind: _kinds.Kind.FLOAT, - value: stringNum, - }; + 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; } - if (typeof serialized === 'string') { - // Enum types use Enum literals. - if ((0, _definition.isEnumType)(type)) { - return { - kind: _kinds.Kind.ENUM, - value: serialized, - }; - } // ID types can use Int literals. - - if (type === _scalars.GraphQLID && integerStringRegExp.test(serialized)) { + toObject() { return { - kind: _kinds.Kind.INT, - value: serialized, + 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 { - kind: _kinds.Kind.STRING, - value: serialized, - }; } - throw new TypeError( - `Cannot convert value to AST: ${(0, _inspect.inspect)(serialized)}.`, - ); - } - /* c8 ignore next 3 */ - // Not reachable, all possible types have been considered. + /** + * 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); - false || - (0, _invariant.invariant)( - false, - 'Unexpected input type: ' + (0, _inspect.inspect)(type), - ); -} -/** - * IntValue: - * - NegativeSign? 0 - * - NegativeSign? NonZeroDigit ( Digit+ )? - */ + // This implementation does not understand range requests + delete headers['if-range']; -const integerStringRegExp = /^-?(?:0|[1-9][0-9]*)$/; + 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; + } + /* 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'); -/***/ 9337: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + /* 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']; -"use strict"; + 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; + } -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.buildASTSchema = buildASTSchema; -exports.buildSchema = buildSchema; + /** + * 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'); + } -var _devAssert = __nccwpck_require__(46514); + // 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; + } + } -var _kinds = __nccwpck_require__(11927); + 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, + }; + } -var _parser = __nccwpck_require__(50655); + // 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]; + } -var _directives = __nccwpck_require__(83614); + 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, + }; + } +}; -var _schema = __nccwpck_require__(8505); -var _validate = __nccwpck_require__(14193); +/***/ }), -var _extendSchema = __nccwpck_require__(51832); +/***/ 42479: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * This takes the ast of a schema document produced by the parse function in - * src/language/parser.js. - * - * If no schema definition is provided, then it will look for types named Query, - * Mutation and Subscription. - * - * Given that AST it constructs a GraphQLSchema. The resulting schema - * has no resolve methods, so execution will use default resolvers. - */ -function buildASTSchema(documentAST, options) { - (documentAST != null && documentAST.kind === _kinds.Kind.DOCUMENT) || - (0, _devAssert.devAssert)(false, 'Must provide valid Document AST.'); +// Copyright 2015 Joyent, Inc. - if ( - (options === null || options === void 0 ? void 0 : options.assumeValid) !== - true && - (options === null || options === void 0 - ? void 0 - : options.assumeValidSDL) !== true - ) { - (0, _validate.assertValidSDL)(documentAST); - } +var parser = __nccwpck_require__(95086); +var signer = __nccwpck_require__(38143); +var verify = __nccwpck_require__(51227); +var utils = __nccwpck_require__(65689); - const emptySchemaConfig = { - description: undefined, - types: [], - directives: [], - extensions: Object.create(null), - extensionASTNodes: [], - assumeValid: false, - }; - const config = (0, _extendSchema.extendSchemaImpl)( - emptySchemaConfig, - documentAST, - options, - ); - if (config.astNode == null) { - for (const type of config.types) { - switch (type.name) { - // Note: While this could make early assertions to get the correctly - // typed values below, that would throw immediately while type system - // validation with validateSchema() will produce more actionable results. - case 'Query': - // @ts-expect-error validated in `validateSchema` - config.query = type; - break; - case 'Mutation': - // @ts-expect-error validated in `validateSchema` - config.mutation = type; - break; +///--- API - case 'Subscription': - // @ts-expect-error validated in `validateSchema` - config.subscription = type; - break; - } - } - } +module.exports = { - const directives = [ - ...config.directives, // If specified directives were not explicitly declared, add them. - ..._directives.specifiedDirectives.filter((stdDirective) => - config.directives.every( - (directive) => directive.name !== stdDirective.name, - ), - ), - ]; - return new _schema.GraphQLSchema({ ...config, directives }); -} -/** - * A helper function to build a GraphQLSchema directly from a source - * document. - */ + parse: parser.parseRequest, + parseRequest: parser.parseRequest, -function buildSchema(source, options) { - const document = (0, _parser.parse)(source, { - noLocation: - options === null || options === void 0 ? void 0 : options.noLocation, - allowLegacyFragmentVariables: - options === null || options === void 0 - ? void 0 - : options.allowLegacyFragmentVariables, - }); - return buildASTSchema(document, { - assumeValidSDL: - options === null || options === void 0 ? void 0 : options.assumeValidSDL, - assumeValid: - options === null || options === void 0 ? void 0 : options.assumeValid, - }); -} + sign: signer.signRequest, + signRequest: signer.signRequest, + createSigner: signer.createSigner, + isSigner: signer.isSigner, + sshKeyToPEM: utils.sshKeyToPEM, + sshKeyFingerprint: utils.fingerprint, + pemToRsaSSHKey: utils.pemToRsaSSHKey, -/***/ }), + verify: verify.verifySignature, + verifySignature: verify.verifySignature, + verifyHMAC: verify.verifyHMAC +}; -/***/ 9352: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +/***/ }), +/***/ 95086: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.buildClientSchema = buildClientSchema; +// Copyright 2012 Joyent, Inc. All rights reserved. -var _devAssert = __nccwpck_require__(46514); +var assert = __nccwpck_require__(66631); +var util = __nccwpck_require__(73837); +var utils = __nccwpck_require__(65689); -var _inspect = __nccwpck_require__(10102); -var _isObjectLike = __nccwpck_require__(95865); -var _keyValMap = __nccwpck_require__(49268); +///--- Globals -var _parser = __nccwpck_require__(50655); +var HASH_ALGOS = utils.HASH_ALGOS; +var PK_ALGOS = utils.PK_ALGOS; +var HttpSignatureError = utils.HttpSignatureError; +var InvalidAlgorithmError = utils.InvalidAlgorithmError; +var validateAlgorithm = utils.validateAlgorithm; -var _definition = __nccwpck_require__(32150); +var State = { + New: 0, + Params: 1 +}; -var _directives = __nccwpck_require__(83614); +var ParamsState = { + Name: 0, + Quote: 1, + Value: 2, + Comma: 3 +}; -var _introspection = __nccwpck_require__(28344); -var _scalars = __nccwpck_require__(93145); +///--- Specific Errors -var _schema = __nccwpck_require__(8505); -var _valueFromAST = __nccwpck_require__(83181); +function ExpiredRequestError(message) { + HttpSignatureError.call(this, message, ExpiredRequestError); +} +util.inherits(ExpiredRequestError, HttpSignatureError); -/** - * Build a GraphQLSchema for use by client tools. - * - * Given the result of a client running the introspection query, creates and - * returns a GraphQLSchema instance which can be then used with all graphql-js - * tools, but cannot be used to execute a query, as introspection does not - * represent the "resolver", "parse" or "serialize" functions or any other - * server-internal mechanisms. - * - * This function expects a complete introspection result. Don't forget to check - * the "errors" field of a server response before calling this function. - */ -function buildClientSchema(introspection, options) { - ((0, _isObjectLike.isObjectLike)(introspection) && - (0, _isObjectLike.isObjectLike)(introspection.__schema)) || - (0, _devAssert.devAssert)( - false, - `Invalid or incomplete introspection result. Ensure that you are passing "data" property of introspection response and no "errors" was returned alongside: ${(0, - _inspect.inspect)(introspection)}.`, - ); // Get the schema from the introspection result. - const schemaIntrospection = introspection.__schema; // Iterate through all types, getting the type definition for each. +function InvalidHeaderError(message) { + HttpSignatureError.call(this, message, InvalidHeaderError); +} +util.inherits(InvalidHeaderError, HttpSignatureError); - const typeMap = (0, _keyValMap.keyValMap)( - schemaIntrospection.types, - (typeIntrospection) => typeIntrospection.name, - (typeIntrospection) => buildType(typeIntrospection), - ); // Include standard types only if they are used. - for (const stdType of [ - ..._scalars.specifiedScalarTypes, - ..._introspection.introspectionTypes, - ]) { - if (typeMap[stdType.name]) { - typeMap[stdType.name] = stdType; - } - } // Get the root Query, Mutation, and Subscription types. +function InvalidParamsError(message) { + HttpSignatureError.call(this, message, InvalidParamsError); +} +util.inherits(InvalidParamsError, HttpSignatureError); - const queryType = schemaIntrospection.queryType - ? getObjectType(schemaIntrospection.queryType) - : null; - const mutationType = schemaIntrospection.mutationType - ? getObjectType(schemaIntrospection.mutationType) - : null; - const subscriptionType = schemaIntrospection.subscriptionType - ? getObjectType(schemaIntrospection.subscriptionType) - : null; // Get the directives supported by Introspection, assuming empty-set if - // directives were not queried for. - const directives = schemaIntrospection.directives - ? schemaIntrospection.directives.map(buildDirective) - : []; // Then produce and return a Schema with these types. +function MissingHeaderError(message) { + HttpSignatureError.call(this, message, MissingHeaderError); +} +util.inherits(MissingHeaderError, HttpSignatureError); - return new _schema.GraphQLSchema({ - description: schemaIntrospection.description, - query: queryType, - mutation: mutationType, - subscription: subscriptionType, - types: Object.values(typeMap), - directives, - assumeValid: - options === null || options === void 0 ? void 0 : options.assumeValid, - }); // Given a type reference in introspection, return the GraphQLType instance. - // preferring cached instances before building new instances. +function StrictParsingError(message) { + HttpSignatureError.call(this, message, StrictParsingError); +} +util.inherits(StrictParsingError, HttpSignatureError); - function getType(typeRef) { - if (typeRef.kind === _introspection.TypeKind.LIST) { - const itemRef = typeRef.ofType; +///--- Exported API - if (!itemRef) { - throw new Error('Decorated type deeper than introspection query.'); - } +module.exports = { - return new _definition.GraphQLList(getType(itemRef)); + /** + * Parses the 'Authorization' header out of an http.ServerRequest object. + * + * Note that this API will fully validate the Authorization header, and throw + * on any error. It will not however check the signature, or the keyId format + * as those are specific to your environment. You can use the options object + * to pass in extra constraints. + * + * As a response object you can expect this: + * + * { + * "scheme": "Signature", + * "params": { + * "keyId": "foo", + * "algorithm": "rsa-sha256", + * "headers": [ + * "date" or "x-date", + * "digest" + * ], + * "signature": "base64" + * }, + * "signingString": "ready to be passed to crypto.verify()" + * } + * + * @param {Object} request an http.ServerRequest. + * @param {Object} options an optional options object with: + * - clockSkew: allowed clock skew in seconds (default 300). + * - headers: required header names (def: date or x-date) + * - algorithms: algorithms to support (default: all). + * - strict: should enforce latest spec parsing + * (default: false). + * @return {Object} parsed out object (see above). + * @throws {TypeError} on invalid input. + * @throws {InvalidHeaderError} on an invalid Authorization header error. + * @throws {InvalidParamsError} if the params in the scheme are invalid. + * @throws {MissingHeaderError} if the params indicate a header not present, + * either in the request headers from the params, + * or not in the params from a required header + * in options. + * @throws {StrictParsingError} if old attributes are used in strict parsing + * mode. + * @throws {ExpiredRequestError} if the value of date or x-date exceeds skew. + */ + parseRequest: function parseRequest(request, options) { + assert.object(request, 'request'); + assert.object(request.headers, 'request.headers'); + if (options === undefined) { + options = {}; } - - if (typeRef.kind === _introspection.TypeKind.NON_NULL) { - const nullableRef = typeRef.ofType; - - if (!nullableRef) { - throw new Error('Decorated type deeper than introspection query.'); - } - - const nullableType = getType(nullableRef); - return new _definition.GraphQLNonNull( - (0, _definition.assertNullableType)(nullableType), - ); + if (options.headers === undefined) { + options.headers = [request.headers['x-date'] ? 'x-date' : 'date']; } + assert.object(options, 'options'); + assert.arrayOfString(options.headers, 'options.headers'); + assert.optionalFinite(options.clockSkew, 'options.clockSkew'); - return getNamedType(typeRef); - } - - function getNamedType(typeRef) { - const typeName = typeRef.name; + var authzHeaderName = options.authorizationHeaderName || 'authorization'; - if (!typeName) { - throw new Error( - `Unknown type reference: ${(0, _inspect.inspect)(typeRef)}.`, - ); + if (!request.headers[authzHeaderName]) { + throw new MissingHeaderError('no ' + authzHeaderName + ' header ' + + 'present in the request'); } - const type = typeMap[typeName]; + options.clockSkew = options.clockSkew || 300; - if (!type) { - throw new Error( - `Invalid or incomplete schema, unknown type: ${typeName}. Ensure that a full introspection query is used in order to build a client schema.`, - ); - } - return type; - } + var i = 0; + var state = State.New; + var substate = ParamsState.Name; + var tmpName = ''; + var tmpValue = ''; - function getObjectType(typeRef) { - return (0, _definition.assertObjectType)(getNamedType(typeRef)); - } + var parsed = { + scheme: '', + params: {}, + signingString: '' + }; - function getInterfaceType(typeRef) { - return (0, _definition.assertInterfaceType)(getNamedType(typeRef)); - } // Given a type's introspection result, construct the correct - // GraphQLType instance. + var authz = request.headers[authzHeaderName]; + for (i = 0; i < authz.length; i++) { + var c = authz.charAt(i); - function buildType(type) { - // eslint-disable-next-line @typescript-eslint/prefer-optional-chain - if (type != null && type.name != null && type.kind != null) { - // FIXME: Properly type IntrospectionType, it's a breaking change so fix in v17 - // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check - switch (type.kind) { - case _introspection.TypeKind.SCALAR: - return buildScalarDef(type); + switch (Number(state)) { - case _introspection.TypeKind.OBJECT: - return buildObjectDef(type); + case State.New: + if (c !== ' ') parsed.scheme += c; + else state = State.Params; + break; - case _introspection.TypeKind.INTERFACE: - return buildInterfaceDef(type); + case State.Params: + switch (Number(substate)) { - case _introspection.TypeKind.UNION: - return buildUnionDef(type); + case ParamsState.Name: + var code = c.charCodeAt(0); + // restricted name of A-Z / a-z + if ((code >= 0x41 && code <= 0x5a) || // A-Z + (code >= 0x61 && code <= 0x7a)) { // a-z + tmpName += c; + } else if (c === '=') { + if (tmpName.length === 0) + throw new InvalidHeaderError('bad param format'); + substate = ParamsState.Quote; + } else { + throw new InvalidHeaderError('bad param format'); + } + break; - case _introspection.TypeKind.ENUM: - return buildEnumDef(type); + case ParamsState.Quote: + if (c === '"') { + tmpValue = ''; + substate = ParamsState.Value; + } else { + throw new InvalidHeaderError('bad param format'); + } + break; - case _introspection.TypeKind.INPUT_OBJECT: - return buildInputObjectDef(type); - } - } + case ParamsState.Value: + if (c === '"') { + parsed.params[tmpName] = tmpValue; + substate = ParamsState.Comma; + } else { + tmpValue += c; + } + break; - const typeStr = (0, _inspect.inspect)(type); - throw new Error( - `Invalid or incomplete introspection result. Ensure that a full introspection query is used in order to build a client schema: ${typeStr}.`, - ); - } + case ParamsState.Comma: + if (c === ',') { + tmpName = ''; + substate = ParamsState.Name; + } else { + throw new InvalidHeaderError('bad param format'); + } + break; - function buildScalarDef(scalarIntrospection) { - return new _definition.GraphQLScalarType({ - name: scalarIntrospection.name, - description: scalarIntrospection.description, - specifiedByURL: scalarIntrospection.specifiedByURL, - }); - } + default: + throw new Error('Invalid substate'); + } + break; - function buildImplementationsList(implementingIntrospection) { - // TODO: Temporary workaround until GraphQL ecosystem will fully support - // 'interfaces' on interface types. - if ( - implementingIntrospection.interfaces === null && - implementingIntrospection.kind === _introspection.TypeKind.INTERFACE - ) { - return []; - } + default: + throw new Error('Invalid substate'); + } - if (!implementingIntrospection.interfaces) { - const implementingIntrospectionStr = (0, _inspect.inspect)( - implementingIntrospection, - ); - throw new Error( - `Introspection result missing interfaces: ${implementingIntrospectionStr}.`, - ); } - return implementingIntrospection.interfaces.map(getInterfaceType); - } - - function buildObjectDef(objectIntrospection) { - return new _definition.GraphQLObjectType({ - name: objectIntrospection.name, - description: objectIntrospection.description, - interfaces: () => buildImplementationsList(objectIntrospection), - fields: () => buildFieldDefMap(objectIntrospection), - }); - } - - function buildInterfaceDef(interfaceIntrospection) { - return new _definition.GraphQLInterfaceType({ - name: interfaceIntrospection.name, - description: interfaceIntrospection.description, - interfaces: () => buildImplementationsList(interfaceIntrospection), - fields: () => buildFieldDefMap(interfaceIntrospection), - }); - } - - function buildUnionDef(unionIntrospection) { - if (!unionIntrospection.possibleTypes) { - const unionIntrospectionStr = (0, _inspect.inspect)(unionIntrospection); - throw new Error( - `Introspection result missing possibleTypes: ${unionIntrospectionStr}.`, - ); + if (!parsed.params.headers || parsed.params.headers === '') { + if (request.headers['x-date']) { + parsed.params.headers = ['x-date']; + } else { + parsed.params.headers = ['date']; + } + } else { + parsed.params.headers = parsed.params.headers.split(' '); } - return new _definition.GraphQLUnionType({ - name: unionIntrospection.name, - description: unionIntrospection.description, - types: () => unionIntrospection.possibleTypes.map(getObjectType), - }); - } - - function buildEnumDef(enumIntrospection) { - if (!enumIntrospection.enumValues) { - const enumIntrospectionStr = (0, _inspect.inspect)(enumIntrospection); - throw new Error( - `Introspection result missing enumValues: ${enumIntrospectionStr}.`, - ); - } + // Minimally validate the parsed object + if (!parsed.scheme || parsed.scheme !== 'Signature') + throw new InvalidHeaderError('scheme was not "Signature"'); - return new _definition.GraphQLEnumType({ - name: enumIntrospection.name, - description: enumIntrospection.description, - values: (0, _keyValMap.keyValMap)( - enumIntrospection.enumValues, - (valueIntrospection) => valueIntrospection.name, - (valueIntrospection) => ({ - description: valueIntrospection.description, - deprecationReason: valueIntrospection.deprecationReason, - }), - ), - }); - } + if (!parsed.params.keyId) + throw new InvalidHeaderError('keyId was not specified'); - function buildInputObjectDef(inputObjectIntrospection) { - if (!inputObjectIntrospection.inputFields) { - const inputObjectIntrospectionStr = (0, _inspect.inspect)( - inputObjectIntrospection, - ); - throw new Error( - `Introspection result missing inputFields: ${inputObjectIntrospectionStr}.`, - ); - } + if (!parsed.params.algorithm) + throw new InvalidHeaderError('algorithm was not specified'); - return new _definition.GraphQLInputObjectType({ - name: inputObjectIntrospection.name, - description: inputObjectIntrospection.description, - fields: () => buildInputValueDefMap(inputObjectIntrospection.inputFields), - isOneOf: inputObjectIntrospection.isOneOf, - }); - } + if (!parsed.params.signature) + throw new InvalidHeaderError('signature was not specified'); - function buildFieldDefMap(typeIntrospection) { - if (!typeIntrospection.fields) { - throw new Error( - `Introspection result missing fields: ${(0, _inspect.inspect)( - typeIntrospection, - )}.`, - ); + // Check the algorithm against the official list + parsed.params.algorithm = parsed.params.algorithm.toLowerCase(); + try { + validateAlgorithm(parsed.params.algorithm); + } catch (e) { + if (e instanceof InvalidAlgorithmError) + throw (new InvalidParamsError(parsed.params.algorithm + ' is not ' + + 'supported')); + else + throw (e); } - return (0, _keyValMap.keyValMap)( - typeIntrospection.fields, - (fieldIntrospection) => fieldIntrospection.name, - buildField, - ); - } - - function buildField(fieldIntrospection) { - const type = getType(fieldIntrospection.type); + // Build the signingString + for (i = 0; i < parsed.params.headers.length; i++) { + var h = parsed.params.headers[i].toLowerCase(); + parsed.params.headers[i] = h; - if (!(0, _definition.isOutputType)(type)) { - const typeStr = (0, _inspect.inspect)(type); - throw new Error( - `Introspection must provide output type for fields, but received: ${typeStr}.`, - ); - } + if (h === 'request-line') { + if (!options.strict) { + /* + * We allow headers from the older spec drafts if strict parsing isn't + * specified in options. + */ + parsed.signingString += + request.method + ' ' + request.url + ' HTTP/' + request.httpVersion; + } else { + /* Strict parsing doesn't allow older draft headers. */ + throw (new StrictParsingError('request-line is not a valid header ' + + 'with strict parsing enabled.')); + } + } else if (h === '(request-target)') { + parsed.signingString += + '(request-target): ' + request.method.toLowerCase() + ' ' + + request.url; + } else { + var value = request.headers[h]; + if (value === undefined) + throw new MissingHeaderError(h + ' was not in the request'); + parsed.signingString += h + ': ' + value; + } - if (!fieldIntrospection.args) { - const fieldIntrospectionStr = (0, _inspect.inspect)(fieldIntrospection); - throw new Error( - `Introspection result missing field args: ${fieldIntrospectionStr}.`, - ); + if ((i + 1) < parsed.params.headers.length) + parsed.signingString += '\n'; } - return { - description: fieldIntrospection.description, - deprecationReason: fieldIntrospection.deprecationReason, - type, - args: buildInputValueDefMap(fieldIntrospection.args), - }; - } - - function buildInputValueDefMap(inputValueIntrospections) { - return (0, _keyValMap.keyValMap)( - inputValueIntrospections, - (inputValue) => inputValue.name, - buildInputValue, - ); - } - - function buildInputValue(inputValueIntrospection) { - const type = getType(inputValueIntrospection.type); + // Check against the constraints + var date; + if (request.headers.date || request.headers['x-date']) { + if (request.headers['x-date']) { + date = new Date(request.headers['x-date']); + } else { + date = new Date(request.headers.date); + } + var now = new Date(); + var skew = Math.abs(now.getTime() - date.getTime()); - if (!(0, _definition.isInputType)(type)) { - const typeStr = (0, _inspect.inspect)(type); - throw new Error( - `Introspection must provide input type for arguments, but received: ${typeStr}.`, - ); + if (skew > options.clockSkew * 1000) { + throw new ExpiredRequestError('clock skew of ' + + (skew / 1000) + + 's was greater than ' + + options.clockSkew + 's'); + } } - const defaultValue = - inputValueIntrospection.defaultValue != null - ? (0, _valueFromAST.valueFromAST)( - (0, _parser.parseValue)(inputValueIntrospection.defaultValue), - type, - ) - : undefined; - return { - description: inputValueIntrospection.description, - type, - defaultValue, - deprecationReason: inputValueIntrospection.deprecationReason, - }; - } - - function buildDirective(directiveIntrospection) { - if (!directiveIntrospection.args) { - const directiveIntrospectionStr = (0, _inspect.inspect)( - directiveIntrospection, - ); - throw new Error( - `Introspection result missing directive args: ${directiveIntrospectionStr}.`, - ); - } + options.headers.forEach(function (hdr) { + // Remember that we already checked any headers in the params + // were in the request, so if this passes we're good. + if (parsed.params.headers.indexOf(hdr.toLowerCase()) < 0) + throw new MissingHeaderError(hdr + ' was not a signed header'); + }); - if (!directiveIntrospection.locations) { - const directiveIntrospectionStr = (0, _inspect.inspect)( - directiveIntrospection, - ); - throw new Error( - `Introspection result missing directive locations: ${directiveIntrospectionStr}.`, - ); + if (options.algorithms) { + if (options.algorithms.indexOf(parsed.params.algorithm) === -1) + throw new InvalidParamsError(parsed.params.algorithm + + ' is not a supported algorithm'); } - return new _directives.GraphQLDirective({ - name: directiveIntrospection.name, - description: directiveIntrospection.description, - isRepeatable: directiveIntrospection.isRepeatable, - locations: directiveIntrospection.locations.slice(), - args: buildInputValueDefMap(directiveIntrospection.args), - }); + parsed.algorithm = parsed.params.algorithm.toUpperCase(); + parsed.keyId = parsed.params.keyId; + return parsed; } -} +}; -/***/ }), -/***/ 39603: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ }), -"use strict"; +/***/ 38143: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// Copyright 2012 Joyent, Inc. All rights reserved. -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.coerceInputValue = coerceInputValue; +var assert = __nccwpck_require__(66631); +var crypto = __nccwpck_require__(6113); +var http = __nccwpck_require__(13685); +var util = __nccwpck_require__(73837); +var sshpk = __nccwpck_require__(87022); +var jsprim = __nccwpck_require__(6287); +var utils = __nccwpck_require__(65689); -var _didYouMean = __nccwpck_require__(42878); +var sprintf = (__nccwpck_require__(73837).format); -var _inspect = __nccwpck_require__(10102); +var HASH_ALGOS = utils.HASH_ALGOS; +var PK_ALGOS = utils.PK_ALGOS; +var InvalidAlgorithmError = utils.InvalidAlgorithmError; +var HttpSignatureError = utils.HttpSignatureError; +var validateAlgorithm = utils.validateAlgorithm; -var _invariant = __nccwpck_require__(28847); +///--- Globals -var _isIterableObject = __nccwpck_require__(81258); +var AUTHZ_FMT = + 'Signature keyId="%s",algorithm="%s",headers="%s",signature="%s"'; -var _isObjectLike = __nccwpck_require__(95865); +///--- Specific Errors -var _Path = __nccwpck_require__(11262); +function MissingHeaderError(message) { + HttpSignatureError.call(this, message, MissingHeaderError); +} +util.inherits(MissingHeaderError, HttpSignatureError); -var _printPathArray = __nccwpck_require__(94281); +function StrictParsingError(message) { + HttpSignatureError.call(this, message, StrictParsingError); +} +util.inherits(StrictParsingError, HttpSignatureError); -var _suggestionList = __nccwpck_require__(57704); +/* See createSigner() */ +function RequestSigner(options) { + assert.object(options, 'options'); -var _GraphQLError = __nccwpck_require__(4797); + var alg = []; + if (options.algorithm !== undefined) { + assert.string(options.algorithm, 'options.algorithm'); + alg = validateAlgorithm(options.algorithm); + } + this.rs_alg = alg; -var _definition = __nccwpck_require__(32150); + /* + * RequestSigners come in two varieties: ones with an rs_signFunc, and ones + * with an rs_signer. + * + * rs_signFunc-based RequestSigners have to build up their entire signing + * string within the rs_lines array and give it to rs_signFunc as a single + * concat'd blob. rs_signer-based RequestSigners can add a line at a time to + * their signing state by using rs_signer.update(), thus only needing to + * buffer the hash function state and one line at a time. + */ + if (options.sign !== undefined) { + assert.func(options.sign, 'options.sign'); + this.rs_signFunc = options.sign; -/** - * Coerces a JavaScript value given a GraphQL Input Type. - */ -function coerceInputValue(inputValue, type, onError = defaultOnError) { - return coerceInputValueImpl(inputValue, type, onError, undefined); -} + } else if (alg[0] === 'hmac' && options.key !== undefined) { + assert.string(options.keyId, 'options.keyId'); + this.rs_keyId = options.keyId; -function defaultOnError(path, invalidValue, error) { - let errorPrefix = 'Invalid value ' + (0, _inspect.inspect)(invalidValue); + if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key)) + throw (new TypeError('options.key for HMAC must be a string or Buffer')); - if (path.length > 0) { - errorPrefix += ` at "value${(0, _printPathArray.printPathArray)(path)}"`; - } + /* + * Make an rs_signer for HMACs, not a rs_signFunc -- HMACs digest their + * data in chunks rather than requiring it all to be given in one go + * at the end, so they are more similar to signers than signFuncs. + */ + this.rs_signer = crypto.createHmac(alg[1].toUpperCase(), options.key); + this.rs_signer.sign = function () { + var digest = this.digest('base64'); + return ({ + hashAlgorithm: alg[1], + toString: function () { return (digest); } + }); + }; - error.message = errorPrefix + ': ' + error.message; - throw error; -} + } else if (options.key !== undefined) { + var key = options.key; + if (typeof (key) === 'string' || Buffer.isBuffer(key)) + key = sshpk.parsePrivateKey(key); -function coerceInputValueImpl(inputValue, type, onError, path) { - if ((0, _definition.isNonNullType)(type)) { - if (inputValue != null) { - return coerceInputValueImpl(inputValue, type.ofType, onError, path); - } + assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]), + 'options.key must be a sshpk.PrivateKey'); + this.rs_key = key; - onError( - (0, _Path.pathToArray)(path), - inputValue, - new _GraphQLError.GraphQLError( - `Expected non-nullable type "${(0, _inspect.inspect)( - type, - )}" not to be null.`, - ), - ); - return; - } + assert.string(options.keyId, 'options.keyId'); + this.rs_keyId = options.keyId; - if (inputValue == null) { - // Explicitly return the value null. - return null; - } + if (!PK_ALGOS[key.type]) { + throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' + + 'keys are not supported')); + } - if ((0, _definition.isListType)(type)) { - const itemType = type.ofType; + if (alg[0] !== undefined && key.type !== alg[0]) { + throw (new InvalidAlgorithmError('options.key must be a ' + + alg[0].toUpperCase() + ' key, was given a ' + + key.type.toUpperCase() + ' key instead')); + } - if ((0, _isIterableObject.isIterableObject)(inputValue)) { - return Array.from(inputValue, (itemValue, index) => { - const itemPath = (0, _Path.addPath)(path, index, undefined); - return coerceInputValueImpl(itemValue, itemType, onError, itemPath); - }); - } // Lists accept a non-list value as a list of one. + this.rs_signer = key.createSign(alg[1]); - return [coerceInputValueImpl(inputValue, itemType, onError, path)]; + } else { + throw (new TypeError('options.sign (func) or options.key is required')); } - if ((0, _definition.isInputObjectType)(type)) { - if ( - !(0, _isObjectLike.isObjectLike)(inputValue) || - Array.isArray(inputValue) - ) { - onError( - (0, _Path.pathToArray)(path), - inputValue, - new _GraphQLError.GraphQLError( - `Expected type "${type.name}" to be an object.`, - ), - ); - return; - } + this.rs_headers = []; + this.rs_lines = []; +} - const coercedValue = {}; - const fieldDefs = type.getFields(); +/** + * Adds a header to be signed, with its value, into this signer. + * + * @param {String} header + * @param {String} value + * @return {String} value written + */ +RequestSigner.prototype.writeHeader = function (header, value) { + assert.string(header, 'header'); + header = header.toLowerCase(); + assert.string(value, 'value'); - for (const field of Object.values(fieldDefs)) { - const fieldValue = inputValue[field.name]; + this.rs_headers.push(header); - if (fieldValue === undefined) { - if (field.defaultValue !== undefined) { - coercedValue[field.name] = field.defaultValue; - } else if ((0, _definition.isNonNullType)(field.type)) { - const typeStr = (0, _inspect.inspect)(field.type); - onError( - (0, _Path.pathToArray)(path), - inputValue, - new _GraphQLError.GraphQLError( - `Field "${field.name}" of required type "${typeStr}" was not provided.`, - ), - ); - } + if (this.rs_signFunc) { + this.rs_lines.push(header + ': ' + value); - continue; - } + } else { + var line = header + ': ' + value; + if (this.rs_headers.length > 0) + line = '\n' + line; + this.rs_signer.update(line); + } - coercedValue[field.name] = coerceInputValueImpl( - fieldValue, - field.type, - onError, - (0, _Path.addPath)(path, field.name, type.name), - ); - } // Ensure every provided field is defined. + return (value); +}; - for (const fieldName of Object.keys(inputValue)) { - if (!fieldDefs[fieldName]) { - const suggestions = (0, _suggestionList.suggestionList)( - fieldName, - Object.keys(type.getFields()), - ); - onError( - (0, _Path.pathToArray)(path), - inputValue, - new _GraphQLError.GraphQLError( - `Field "${fieldName}" is not defined by type "${type.name}".` + - (0, _didYouMean.didYouMean)(suggestions), - ), - ); - } - } +/** + * Adds a default Date header, returning its value. + * + * @return {String} + */ +RequestSigner.prototype.writeDateHeader = function () { + return (this.writeHeader('date', jsprim.rfc1123(new Date()))); +}; - if (type.isOneOf) { - const keys = Object.keys(coercedValue); +/** + * Adds the request target line to be signed. + * + * @param {String} method, HTTP method (e.g. 'get', 'post', 'put') + * @param {String} path + */ +RequestSigner.prototype.writeTarget = function (method, path) { + assert.string(method, 'method'); + assert.string(path, 'path'); + method = method.toLowerCase(); + this.writeHeader('(request-target)', method + ' ' + path); +}; - if (keys.length !== 1) { - onError( - (0, _Path.pathToArray)(path), - inputValue, - new _GraphQLError.GraphQLError( - `Exactly one key must be specified for OneOf type "${type.name}".`, - ), - ); - } +/** + * Calculate the value for the Authorization header on this request + * asynchronously. + * + * @param {Func} callback (err, authz) + */ +RequestSigner.prototype.sign = function (cb) { + assert.func(cb, 'callback'); - const key = keys[0]; - const value = coercedValue[key]; + if (this.rs_headers.length < 1) + throw (new Error('At least one header must be signed')); - if (value === null) { - onError( - (0, _Path.pathToArray)(path).concat(key), - value, - new _GraphQLError.GraphQLError(`Field "${key}" must be non-null.`), - ); + var alg, authz; + if (this.rs_signFunc) { + var data = this.rs_lines.join('\n'); + var self = this; + this.rs_signFunc(data, function (err, sig) { + if (err) { + cb(err); + return; } - } - - return coercedValue; - } - - if ((0, _definition.isLeafType)(type)) { - let parseResult; // Scalars and Enums determine if a input value is valid via parseValue(), - // which can throw to indicate failure. If it throws, maintain a reference - // to the original error. + try { + assert.object(sig, 'signature'); + assert.string(sig.keyId, 'signature.keyId'); + assert.string(sig.algorithm, 'signature.algorithm'); + assert.string(sig.signature, 'signature.signature'); + alg = validateAlgorithm(sig.algorithm); - try { - parseResult = type.parseValue(inputValue); - } catch (error) { - if (error instanceof _GraphQLError.GraphQLError) { - onError((0, _Path.pathToArray)(path), inputValue, error); - } else { - onError( - (0, _Path.pathToArray)(path), - inputValue, - new _GraphQLError.GraphQLError( - `Expected type "${type.name}". ` + error.message, - { - originalError: error, - }, - ), - ); + authz = sprintf(AUTHZ_FMT, + sig.keyId, + sig.algorithm, + self.rs_headers.join(' '), + sig.signature); + } catch (e) { + cb(e); + return; } + cb(null, authz); + }); + } else { + try { + var sigObj = this.rs_signer.sign(); + } catch (e) { + cb(e); return; } - - if (parseResult === undefined) { - onError( - (0, _Path.pathToArray)(path), - inputValue, - new _GraphQLError.GraphQLError(`Expected type "${type.name}".`), - ); - } - - return parseResult; + alg = (this.rs_alg[0] || this.rs_key.type) + '-' + sigObj.hashAlgorithm; + var signature = sigObj.toString(); + authz = sprintf(AUTHZ_FMT, + this.rs_keyId, + alg, + this.rs_headers.join(' '), + signature); + cb(null, authz); } - /* c8 ignore next 3 */ - // Not reachable, all possible types have been considered. - - false || - (0, _invariant.invariant)( - false, - 'Unexpected input type: ' + (0, _inspect.inspect)(type), - ); -} - - -/***/ }), - -/***/ 17232: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +}; -"use strict"; +///--- Exported API +module.exports = { + /** + * Identifies whether a given object is a request signer or not. + * + * @param {Object} object, the object to identify + * @returns {Boolean} + */ + isSigner: function (obj) { + if (typeof (obj) === 'object' && obj instanceof RequestSigner) + return (true); + return (false); + }, -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.concatAST = concatAST; + /** + * Creates a request signer, used to asynchronously build a signature + * for a request (does not have to be an http.ClientRequest). + * + * @param {Object} options, either: + * - {String} keyId + * - {String|Buffer} key + * - {String} algorithm (optional, required for HMAC) + * or: + * - {Func} sign (data, cb) + * @return {RequestSigner} + */ + createSigner: function createSigner(options) { + return (new RequestSigner(options)); + }, -var _kinds = __nccwpck_require__(11927); + /** + * Adds an 'Authorization' header to an http.ClientRequest object. + * + * Note that this API will add a Date header if it's not already set. Any + * other headers in the options.headers array MUST be present, or this + * will throw. + * + * You shouldn't need to check the return type; it's just there if you want + * to be pedantic. + * + * The optional flag indicates whether parsing should use strict enforcement + * of the version draft-cavage-http-signatures-04 of the spec or beyond. + * The default is to be loose and support + * older versions for compatibility. + * + * @param {Object} request an instance of http.ClientRequest. + * @param {Object} options signing parameters object: + * - {String} keyId required. + * - {String} key required (either a PEM or HMAC key). + * - {Array} headers optional; defaults to ['date']. + * - {String} algorithm optional (unless key is HMAC); + * default is the same as the sshpk default + * signing algorithm for the type of key given + * - {String} httpVersion optional; defaults to '1.1'. + * - {Boolean} strict optional; defaults to 'false'. + * @return {Boolean} true if Authorization (and optionally Date) were added. + * @throws {TypeError} on bad parameter types (input). + * @throws {InvalidAlgorithmError} if algorithm was bad or incompatible with + * the given key. + * @throws {sshpk.KeyParseError} if key was bad. + * @throws {MissingHeaderError} if a header to be signed was specified but + * was not present. + */ + signRequest: function signRequest(request, options) { + assert.object(request, 'request'); + assert.object(options, 'options'); + assert.optionalString(options.algorithm, 'options.algorithm'); + assert.string(options.keyId, 'options.keyId'); + assert.optionalArrayOfString(options.headers, 'options.headers'); + assert.optionalString(options.httpVersion, 'options.httpVersion'); -/** - * Provided a collection of ASTs, presumably each from different files, - * concatenate the ASTs together into batched AST, useful for validating many - * GraphQL source files which together represent one conceptual application. - */ -function concatAST(documents) { - const definitions = []; + if (!request.getHeader('Date')) + request.setHeader('Date', jsprim.rfc1123(new Date())); + if (!options.headers) + options.headers = ['date']; + if (!options.httpVersion) + options.httpVersion = '1.1'; - for (const doc of documents) { - definitions.push(...doc.definitions); - } + var alg = []; + if (options.algorithm) { + options.algorithm = options.algorithm.toLowerCase(); + alg = validateAlgorithm(options.algorithm); + } - return { - kind: _kinds.Kind.DOCUMENT, - definitions, - }; -} + var i; + var stringToSign = ''; + for (i = 0; i < options.headers.length; i++) { + if (typeof (options.headers[i]) !== 'string') + throw new TypeError('options.headers must be an array of Strings'); + var h = options.headers[i].toLowerCase(); -/***/ }), + if (h === 'request-line') { + if (!options.strict) { + /** + * We allow headers from the older spec drafts if strict parsing isn't + * specified in options. + */ + stringToSign += + request.method + ' ' + request.path + ' HTTP/' + + options.httpVersion; + } else { + /* Strict parsing doesn't allow older draft headers. */ + throw (new StrictParsingError('request-line is not a valid header ' + + 'with strict parsing enabled.')); + } + } else if (h === '(request-target)') { + stringToSign += + '(request-target): ' + request.method.toLowerCase() + ' ' + + request.path; + } else { + var value = request.getHeader(h); + if (value === undefined || value === '') { + throw new MissingHeaderError(h + ' was not in the request'); + } + stringToSign += h + ': ' + value; + } -/***/ 51832: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if ((i + 1) < options.headers.length) + stringToSign += '\n'; + } -"use strict"; + /* This is just for unit tests. */ + if (request.hasOwnProperty('_stringToSign')) { + request._stringToSign = stringToSign; + } + var signature; + if (alg[0] === 'hmac') { + if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key)) + throw (new TypeError('options.key must be a string or Buffer')); -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.extendSchema = extendSchema; -exports.extendSchemaImpl = extendSchemaImpl; + var hmac = crypto.createHmac(alg[1].toUpperCase(), options.key); + hmac.update(stringToSign); + signature = hmac.digest('base64'); -var _devAssert = __nccwpck_require__(46514); + } else { + var key = options.key; + if (typeof (key) === 'string' || Buffer.isBuffer(key)) + key = sshpk.parsePrivateKey(options.key); -var _inspect = __nccwpck_require__(10102); + assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]), + 'options.key must be a sshpk.PrivateKey'); -var _invariant = __nccwpck_require__(28847); + if (!PK_ALGOS[key.type]) { + throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' + + 'keys are not supported')); + } -var _keyMap = __nccwpck_require__(10711); + if (alg[0] !== undefined && key.type !== alg[0]) { + throw (new InvalidAlgorithmError('options.key must be a ' + + alg[0].toUpperCase() + ' key, was given a ' + + key.type.toUpperCase() + ' key instead')); + } -var _mapValue = __nccwpck_require__(32223); + var signer = key.createSign(alg[1]); + signer.update(stringToSign); + var sigObj = signer.sign(); + if (!HASH_ALGOS[sigObj.hashAlgorithm]) { + throw (new InvalidAlgorithmError(sigObj.hashAlgorithm.toUpperCase() + + ' is not a supported hash algorithm')); + } + options.algorithm = key.type + '-' + sigObj.hashAlgorithm; + signature = sigObj.toString(); + assert.notStrictEqual(signature, '', 'empty signature produced'); + } -var _kinds = __nccwpck_require__(11927); + var authzHeaderName = options.authorizationHeaderName || 'Authorization'; -var _predicates = __nccwpck_require__(20535); + request.setHeader(authzHeaderName, sprintf(AUTHZ_FMT, + options.keyId, + options.algorithm, + options.headers.join(' '), + signature)); -var _definition = __nccwpck_require__(32150); + return true; + } -var _directives = __nccwpck_require__(83614); +}; -var _introspection = __nccwpck_require__(28344); -var _scalars = __nccwpck_require__(93145); +/***/ }), -var _schema = __nccwpck_require__(8505); +/***/ 65689: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var _validate = __nccwpck_require__(14193); +// Copyright 2012 Joyent, Inc. All rights reserved. -var _values = __nccwpck_require__(94834); +var assert = __nccwpck_require__(66631); +var sshpk = __nccwpck_require__(87022); +var util = __nccwpck_require__(73837); -var _valueFromAST = __nccwpck_require__(83181); +var HASH_ALGOS = { + 'sha1': true, + 'sha256': true, + 'sha512': true +}; -/** - * Produces a new schema given an existing schema and a document which may - * contain GraphQL type extensions and definitions. The original schema will - * remain unaltered. - * - * Because a schema represents a graph of references, a schema cannot be - * extended without effectively making an entire copy. We do not know until it's - * too late if subgraphs remain unchanged. - * - * This algorithm copies the provided schema, applying extensions while - * producing the copy. The original schema remains unaltered. - */ -function extendSchema(schema, documentAST, options) { - (0, _schema.assertSchema)(schema); - (documentAST != null && documentAST.kind === _kinds.Kind.DOCUMENT) || - (0, _devAssert.devAssert)(false, 'Must provide valid Document AST.'); +var PK_ALGOS = { + 'rsa': true, + 'dsa': true, + 'ecdsa': true +}; - if ( - (options === null || options === void 0 ? void 0 : options.assumeValid) !== - true && - (options === null || options === void 0 - ? void 0 - : options.assumeValidSDL) !== true - ) { - (0, _validate.assertValidSDLExtension)(documentAST, schema); - } +function HttpSignatureError(message, caller) { + if (Error.captureStackTrace) + Error.captureStackTrace(this, caller || HttpSignatureError); - const schemaConfig = schema.toConfig(); - const extendedConfig = extendSchemaImpl(schemaConfig, documentAST, options); - return schemaConfig === extendedConfig - ? schema - : new _schema.GraphQLSchema(extendedConfig); + this.message = message; + this.name = caller.name; } -/** - * @internal - */ - -function extendSchemaImpl(schemaConfig, documentAST, options) { - var _schemaDef, _schemaDef$descriptio, _schemaDef2, _options$assumeValid; - - // Collect the type definitions and extensions found in the document. - const typeDefs = []; - const typeExtensionsMap = Object.create(null); // New directives and types are separate because a directives and types can - // have the same name. For example, a type named "skip". - - const directiveDefs = []; - let schemaDef; // Schema extensions are collected which may add additional operation types. +util.inherits(HttpSignatureError, Error); - const schemaExtensions = []; +function InvalidAlgorithmError(message) { + HttpSignatureError.call(this, message, InvalidAlgorithmError); +} +util.inherits(InvalidAlgorithmError, HttpSignatureError); - for (const def of documentAST.definitions) { - if (def.kind === _kinds.Kind.SCHEMA_DEFINITION) { - schemaDef = def; - } else if (def.kind === _kinds.Kind.SCHEMA_EXTENSION) { - schemaExtensions.push(def); - } else if ((0, _predicates.isTypeDefinitionNode)(def)) { - typeDefs.push(def); - } else if ((0, _predicates.isTypeExtensionNode)(def)) { - const extendedTypeName = def.name.value; - const existingTypeExtensions = typeExtensionsMap[extendedTypeName]; - typeExtensionsMap[extendedTypeName] = existingTypeExtensions - ? existingTypeExtensions.concat([def]) - : [def]; - } else if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { - directiveDefs.push(def); - } - } // If this document contains no new types, extensions, or directives then - // return the same unmodified GraphQLSchema instance. +function validateAlgorithm(algorithm) { + var alg = algorithm.toLowerCase().split('-'); - if ( - Object.keys(typeExtensionsMap).length === 0 && - typeDefs.length === 0 && - directiveDefs.length === 0 && - schemaExtensions.length === 0 && - schemaDef == null - ) { - return schemaConfig; + if (alg.length !== 2) { + throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' is not a ' + + 'valid algorithm')); } - const typeMap = Object.create(null); - - for (const existingType of schemaConfig.types) { - typeMap[existingType.name] = extendNamedType(existingType); + if (alg[0] !== 'hmac' && !PK_ALGOS[alg[0]]) { + throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' type keys ' + + 'are not supported')); } - for (const typeNode of typeDefs) { - var _stdTypeMap$name; - - const name = typeNode.name.value; - typeMap[name] = - (_stdTypeMap$name = stdTypeMap[name]) !== null && - _stdTypeMap$name !== void 0 - ? _stdTypeMap$name - : buildType(typeNode); + if (!HASH_ALGOS[alg[1]]) { + throw (new InvalidAlgorithmError(alg[1].toUpperCase() + ' is not a ' + + 'supported hash algorithm')); } - const operationTypes = { - // Get the extended root operation types. - query: schemaConfig.query && replaceNamedType(schemaConfig.query), - mutation: schemaConfig.mutation && replaceNamedType(schemaConfig.mutation), - subscription: - schemaConfig.subscription && replaceNamedType(schemaConfig.subscription), - // Then, incorporate schema definition and all schema extensions. - ...(schemaDef && getOperationTypes([schemaDef])), - ...getOperationTypes(schemaExtensions), - }; // Then produce and return a Schema config with these types. + return (alg); +} - return { - description: - (_schemaDef = schemaDef) === null || _schemaDef === void 0 - ? void 0 - : (_schemaDef$descriptio = _schemaDef.description) === null || - _schemaDef$descriptio === void 0 - ? void 0 - : _schemaDef$descriptio.value, - ...operationTypes, - types: Object.values(typeMap), - directives: [ - ...schemaConfig.directives.map(replaceDirective), - ...directiveDefs.map(buildDirective), - ], - extensions: Object.create(null), - astNode: - (_schemaDef2 = schemaDef) !== null && _schemaDef2 !== void 0 - ? _schemaDef2 - : schemaConfig.astNode, - extensionASTNodes: schemaConfig.extensionASTNodes.concat(schemaExtensions), - assumeValid: - (_options$assumeValid = - options === null || options === void 0 - ? void 0 - : options.assumeValid) !== null && _options$assumeValid !== void 0 - ? _options$assumeValid - : false, - }; // Below are functions used for producing this schema that have closed over - // this scope and have access to the schema, cache, and newly defined types. +///--- API - function replaceType(type) { - if ((0, _definition.isListType)(type)) { - // @ts-expect-error - return new _definition.GraphQLList(replaceType(type.ofType)); - } +module.exports = { - if ((0, _definition.isNonNullType)(type)) { - // @ts-expect-error - return new _definition.GraphQLNonNull(replaceType(type.ofType)); - } // @ts-expect-error FIXME + HASH_ALGOS: HASH_ALGOS, + PK_ALGOS: PK_ALGOS, - return replaceNamedType(type); - } + HttpSignatureError: HttpSignatureError, + InvalidAlgorithmError: InvalidAlgorithmError, - function replaceNamedType(type) { - // Note: While this could make early assertions to get the correctly - // typed values, that would throw immediately while type system - // validation with validateSchema() will produce more actionable results. - return typeMap[type.name]; - } + validateAlgorithm: validateAlgorithm, - function replaceDirective(directive) { - const config = directive.toConfig(); - return new _directives.GraphQLDirective({ - ...config, - args: (0, _mapValue.mapValue)(config.args, extendArg), - }); - } + /** + * Converts an OpenSSH public key (rsa only) to a PKCS#8 PEM file. + * + * The intent of this module is to interoperate with OpenSSL only, + * specifically the node crypto module's `verify` method. + * + * @param {String} key an OpenSSH public key. + * @return {String} PEM encoded form of the RSA public key. + * @throws {TypeError} on bad input. + * @throws {Error} on invalid ssh key formatted data. + */ + sshKeyToPEM: function sshKeyToPEM(key) { + assert.string(key, 'ssh_key'); - function extendNamedType(type) { - if ( - (0, _introspection.isIntrospectionType)(type) || - (0, _scalars.isSpecifiedScalarType)(type) - ) { - // Builtin types are not extended. - return type; - } + var k = sshpk.parseKey(key, 'ssh'); + return (k.toString('pem')); + }, - if ((0, _definition.isScalarType)(type)) { - return extendScalarType(type); - } - if ((0, _definition.isObjectType)(type)) { - return extendObjectType(type); - } + /** + * Generates an OpenSSH fingerprint from an ssh public key. + * + * @param {String} key an OpenSSH public key. + * @return {String} key fingerprint. + * @throws {TypeError} on bad input. + * @throws {Error} if what you passed doesn't look like an ssh public key. + */ + fingerprint: function fingerprint(key) { + assert.string(key, 'ssh_key'); - if ((0, _definition.isInterfaceType)(type)) { - return extendInterfaceType(type); - } + var k = sshpk.parseKey(key, 'ssh'); + return (k.fingerprint('md5').toString('hex')); + }, - if ((0, _definition.isUnionType)(type)) { - return extendUnionType(type); - } + /** + * Converts a PKGCS#8 PEM file to an OpenSSH public key (rsa) + * + * The reverse of the above function. + */ + pemToRsaSSHKey: function pemToRsaSSHKey(pem, comment) { + assert.equal('string', typeof (pem), 'typeof pem'); - if ((0, _definition.isEnumType)(type)) { - return extendEnumType(type); - } + var k = sshpk.parseKey(pem, 'pem'); + k.comment = comment; + return (k.toString('ssh')); + } +}; - if ((0, _definition.isInputObjectType)(type)) { - return extendInputObjectType(type); - } - /* c8 ignore next 3 */ - // Not reachable, all possible type definition nodes have been considered. - false || - (0, _invariant.invariant)( - false, - 'Unexpected type: ' + (0, _inspect.inspect)(type), - ); - } +/***/ }), - function extendInputObjectType(type) { - var _typeExtensionsMap$co; +/***/ 51227: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const config = type.toConfig(); - const extensions = - (_typeExtensionsMap$co = typeExtensionsMap[config.name]) !== null && - _typeExtensionsMap$co !== void 0 - ? _typeExtensionsMap$co - : []; - return new _definition.GraphQLInputObjectType({ - ...config, - fields: () => ({ - ...(0, _mapValue.mapValue)(config.fields, (field) => ({ - ...field, - type: replaceType(field.type), - })), - ...buildInputFieldMap(extensions), - }), - extensionASTNodes: config.extensionASTNodes.concat(extensions), - }); - } +// Copyright 2015 Joyent, Inc. - function extendEnumType(type) { - var _typeExtensionsMap$ty; +var assert = __nccwpck_require__(66631); +var crypto = __nccwpck_require__(6113); +var sshpk = __nccwpck_require__(87022); +var utils = __nccwpck_require__(65689); - const config = type.toConfig(); - const extensions = - (_typeExtensionsMap$ty = typeExtensionsMap[type.name]) !== null && - _typeExtensionsMap$ty !== void 0 - ? _typeExtensionsMap$ty - : []; - return new _definition.GraphQLEnumType({ - ...config, - values: { ...config.values, ...buildEnumValueMap(extensions) }, - extensionASTNodes: config.extensionASTNodes.concat(extensions), - }); - } +var HASH_ALGOS = utils.HASH_ALGOS; +var PK_ALGOS = utils.PK_ALGOS; +var InvalidAlgorithmError = utils.InvalidAlgorithmError; +var HttpSignatureError = utils.HttpSignatureError; +var validateAlgorithm = utils.validateAlgorithm; - function extendScalarType(type) { - var _typeExtensionsMap$co2; +///--- Exported API - const config = type.toConfig(); - const extensions = - (_typeExtensionsMap$co2 = typeExtensionsMap[config.name]) !== null && - _typeExtensionsMap$co2 !== void 0 - ? _typeExtensionsMap$co2 - : []; - let specifiedByURL = config.specifiedByURL; +module.exports = { + /** + * Verify RSA/DSA signature against public key. You are expected to pass in + * an object that was returned from `parse()`. + * + * @param {Object} parsedSignature the object you got from `parse`. + * @param {String} pubkey RSA/DSA private key PEM. + * @return {Boolean} true if valid, false otherwise. + * @throws {TypeError} if you pass in bad arguments. + * @throws {InvalidAlgorithmError} + */ + verifySignature: function verifySignature(parsedSignature, pubkey) { + assert.object(parsedSignature, 'parsedSignature'); + if (typeof (pubkey) === 'string' || Buffer.isBuffer(pubkey)) + pubkey = sshpk.parseKey(pubkey); + assert.ok(sshpk.Key.isKey(pubkey, [1, 1]), 'pubkey must be a sshpk.Key'); - for (const extensionNode of extensions) { - var _getSpecifiedByURL; + var alg = validateAlgorithm(parsedSignature.algorithm); + if (alg[0] === 'hmac' || alg[0] !== pubkey.type) + return (false); - specifiedByURL = - (_getSpecifiedByURL = getSpecifiedByURL(extensionNode)) !== null && - _getSpecifiedByURL !== void 0 - ? _getSpecifiedByURL - : specifiedByURL; - } + var v = pubkey.createVerify(alg[1]); + v.update(parsedSignature.signingString); + return (v.verify(parsedSignature.params.signature, 'base64')); + }, - return new _definition.GraphQLScalarType({ - ...config, - specifiedByURL, - extensionASTNodes: config.extensionASTNodes.concat(extensions), - }); - } + /** + * Verify HMAC against shared secret. You are expected to pass in an object + * that was returned from `parse()`. + * + * @param {Object} parsedSignature the object you got from `parse`. + * @param {String} secret HMAC shared secret. + * @return {Boolean} true if valid, false otherwise. + * @throws {TypeError} if you pass in bad arguments. + * @throws {InvalidAlgorithmError} + */ + verifyHMAC: function verifyHMAC(parsedSignature, secret) { + assert.object(parsedSignature, 'parsedHMAC'); + assert.string(secret, 'secret'); - function extendObjectType(type) { - var _typeExtensionsMap$co3; + var alg = validateAlgorithm(parsedSignature.algorithm); + if (alg[0] !== 'hmac') + return (false); - const config = type.toConfig(); - const extensions = - (_typeExtensionsMap$co3 = typeExtensionsMap[config.name]) !== null && - _typeExtensionsMap$co3 !== void 0 - ? _typeExtensionsMap$co3 - : []; - return new _definition.GraphQLObjectType({ - ...config, - interfaces: () => [ - ...type.getInterfaces().map(replaceNamedType), - ...buildInterfaces(extensions), - ], - fields: () => ({ - ...(0, _mapValue.mapValue)(config.fields, extendField), - ...buildFieldMap(extensions), - }), - extensionASTNodes: config.extensionASTNodes.concat(extensions), - }); - } + var hashAlg = alg[1].toUpperCase(); - function extendInterfaceType(type) { - var _typeExtensionsMap$co4; + var hmac = crypto.createHmac(hashAlg, secret); + hmac.update(parsedSignature.signingString); - const config = type.toConfig(); - const extensions = - (_typeExtensionsMap$co4 = typeExtensionsMap[config.name]) !== null && - _typeExtensionsMap$co4 !== void 0 - ? _typeExtensionsMap$co4 - : []; - return new _definition.GraphQLInterfaceType({ - ...config, - interfaces: () => [ - ...type.getInterfaces().map(replaceNamedType), - ...buildInterfaces(extensions), - ], - fields: () => ({ - ...(0, _mapValue.mapValue)(config.fields, extendField), - ...buildFieldMap(extensions), - }), - extensionASTNodes: config.extensionASTNodes.concat(extensions), - }); - } + /* + * Now double-hash to avoid leaking timing information - there's + * no easy constant-time compare in JS, so we use this approach + * instead. See for more info: + * https://www.isecpartners.com/blog/2011/february/double-hmac- + * verification.aspx + */ + var h1 = crypto.createHmac(hashAlg, secret); + h1.update(hmac.digest()); + h1 = h1.digest(); + var h2 = crypto.createHmac(hashAlg, secret); + h2.update(new Buffer(parsedSignature.params.signature, 'base64')); + h2 = h2.digest(); - function extendUnionType(type) { - var _typeExtensionsMap$co5; + /* Node 0.8 returns strings from .digest(). */ + if (typeof (h1) === 'string') + return (h1 === h2); + /* And node 0.10 lacks the .equals() method on Buffers. */ + if (Buffer.isBuffer(h1) && !h1.equals) + return (h1.toString('binary') === h2.toString('binary')); - const config = type.toConfig(); - const extensions = - (_typeExtensionsMap$co5 = typeExtensionsMap[config.name]) !== null && - _typeExtensionsMap$co5 !== void 0 - ? _typeExtensionsMap$co5 - : []; - return new _definition.GraphQLUnionType({ - ...config, - types: () => [ - ...type.getTypes().map(replaceNamedType), - ...buildUnionTypes(extensions), - ], - extensionASTNodes: config.extensionASTNodes.concat(extensions), - }); + return (h1.equals(h2)); } +}; - function extendField(field) { - return { - ...field, - type: replaceType(field.type), - args: field.args && (0, _mapValue.mapValue)(field.args, extendArg), - }; - } - function extendArg(arg) { - return { ...arg, type: replaceType(arg.type) }; - } +/***/ }), - function getOperationTypes(nodes) { - const opTypes = {}; +/***/ 79898: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - for (const node of nodes) { - var _node$operationTypes; +"use strict"; - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - const operationTypesNodes = - /* c8 ignore next */ - (_node$operationTypes = node.operationTypes) !== null && - _node$operationTypes !== void 0 - ? _node$operationTypes - : []; +const EventEmitter = __nccwpck_require__(82361); +const tls = __nccwpck_require__(24404); +const http2 = __nccwpck_require__(85158); +const QuickLRU = __nccwpck_require__(49273); - for (const operationType of operationTypesNodes) { - // Note: While this could make early assertions to get the correctly - // typed values below, that would throw immediately while type system - // validation with validateSchema() will produce more actionable results. - // @ts-expect-error - opTypes[operationType.operation] = getNamedType(operationType.type); - } - } +const kCurrentStreamsCount = Symbol('currentStreamsCount'); +const kRequest = Symbol('request'); +const kOriginSet = Symbol('cachedOriginSet'); +const kGracefullyClosing = Symbol('gracefullyClosing'); - return opTypes; - } +const nameKeys = [ + // `http2.connect()` options + 'maxDeflateDynamicTableSize', + 'maxSessionMemory', + 'maxHeaderListPairs', + 'maxOutstandingPings', + 'maxReservedRemoteStreams', + 'maxSendHeaderBlockLength', + 'paddingStrategy', - function getNamedType(node) { - var _stdTypeMap$name2; + // `tls.connect()` options + 'localAddress', + 'path', + 'rejectUnauthorized', + 'minDHSize', - const name = node.name.value; - const type = - (_stdTypeMap$name2 = stdTypeMap[name]) !== null && - _stdTypeMap$name2 !== void 0 - ? _stdTypeMap$name2 - : typeMap[name]; + // `tls.createSecureContext()` options + 'ca', + 'cert', + 'clientCertEngine', + 'ciphers', + 'key', + 'pfx', + 'servername', + 'minVersion', + 'maxVersion', + 'secureProtocol', + 'crl', + 'honorCipherOrder', + 'ecdhCurve', + 'dhparam', + 'secureOptions', + 'sessionIdContext' +]; - if (type === undefined) { - throw new Error(`Unknown type: "${name}".`); - } +const getSortedIndex = (array, value, compare) => { + let low = 0; + let high = array.length; - return type; - } + while (low < high) { + const mid = (low + high) >>> 1; - function getWrappedType(node) { - if (node.kind === _kinds.Kind.LIST_TYPE) { - return new _definition.GraphQLList(getWrappedType(node.type)); - } + /* istanbul ignore next */ + if (compare(array[mid], value)) { + // This never gets called because we use descending sort. Better to have this anyway. + low = mid + 1; + } else { + high = mid; + } + } - if (node.kind === _kinds.Kind.NON_NULL_TYPE) { - return new _definition.GraphQLNonNull(getWrappedType(node.type)); - } + return low; +}; - return getNamedType(node); - } +const compareSessions = (a, b) => { + return a.remoteSettings.maxConcurrentStreams > b.remoteSettings.maxConcurrentStreams; +}; - function buildDirective(node) { - var _node$description; +// See https://tools.ietf.org/html/rfc8336 +const closeCoveredSessions = (where, session) => { + // Clients SHOULD NOT emit new requests on any connection whose Origin + // Set is a proper subset of another connection's Origin Set, and they + // SHOULD close it once all outstanding requests are satisfied. + for (const coveredSession of where) { + if ( + // The set is a proper subset when its length is less than the other set. + coveredSession[kOriginSet].length < session[kOriginSet].length && - return new _directives.GraphQLDirective({ - name: node.name.value, - description: - (_node$description = node.description) === null || - _node$description === void 0 - ? void 0 - : _node$description.value, - // @ts-expect-error - locations: node.locations.map(({ value }) => value), - isRepeatable: node.repeatable, - args: buildArgumentMap(node.arguments), - astNode: node, - }); - } + // And the other set includes all elements of the subset. + coveredSession[kOriginSet].every(origin => session[kOriginSet].includes(origin)) && - function buildFieldMap(nodes) { - const fieldConfigMap = Object.create(null); + // Makes sure that the session can handle all requests from the covered session. + coveredSession[kCurrentStreamsCount] + session[kCurrentStreamsCount] <= session.remoteSettings.maxConcurrentStreams + ) { + // This allows pending requests to finish and prevents making new requests. + gracefullyClose(coveredSession); + } + } +}; - for (const node of nodes) { - var _node$fields; +// This is basically inverted `closeCoveredSessions(...)`. +const closeSessionIfCovered = (where, coveredSession) => { + for (const session of where) { + if ( + coveredSession[kOriginSet].length < session[kOriginSet].length && + coveredSession[kOriginSet].every(origin => session[kOriginSet].includes(origin)) && + coveredSession[kCurrentStreamsCount] + session[kCurrentStreamsCount] <= session.remoteSettings.maxConcurrentStreams + ) { + gracefullyClose(coveredSession); + } + } +}; - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - const nodeFields = - /* c8 ignore next */ - (_node$fields = node.fields) !== null && _node$fields !== void 0 - ? _node$fields - : []; +const getSessions = ({agent, isFree}) => { + const result = {}; - for (const field of nodeFields) { - var _field$description; + // eslint-disable-next-line guard-for-in + for (const normalizedOptions in agent.sessions) { + const sessions = agent.sessions[normalizedOptions]; - fieldConfigMap[field.name.value] = { - // Note: While this could make assertions to get the correctly typed - // value, that would throw immediately while type system validation - // with validateSchema() will produce more actionable results. - type: getWrappedType(field.type), - description: - (_field$description = field.description) === null || - _field$description === void 0 - ? void 0 - : _field$description.value, - args: buildArgumentMap(field.arguments), - deprecationReason: getDeprecationReason(field), - astNode: field, - }; - } - } + const filtered = sessions.filter(session => { + const result = session[Agent.kCurrentStreamsCount] < session.remoteSettings.maxConcurrentStreams; - return fieldConfigMap; - } + return isFree ? result : !result; + }); - function buildArgumentMap(args) { - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - const argsNodes = - /* c8 ignore next */ - args !== null && args !== void 0 ? args : []; - const argConfigMap = Object.create(null); + if (filtered.length !== 0) { + result[normalizedOptions] = filtered; + } + } - for (const arg of argsNodes) { - var _arg$description; + return result; +}; - // Note: While this could make assertions to get the correctly typed - // value, that would throw immediately while type system validation - // with validateSchema() will produce more actionable results. - const type = getWrappedType(arg.type); - argConfigMap[arg.name.value] = { - type, - description: - (_arg$description = arg.description) === null || - _arg$description === void 0 - ? void 0 - : _arg$description.value, - defaultValue: (0, _valueFromAST.valueFromAST)(arg.defaultValue, type), - deprecationReason: getDeprecationReason(arg), - astNode: arg, - }; - } +const gracefullyClose = session => { + session[kGracefullyClosing] = true; - return argConfigMap; - } + if (session[kCurrentStreamsCount] === 0) { + session.close(); + } +}; - function buildInputFieldMap(nodes) { - const inputFieldMap = Object.create(null); +class Agent extends EventEmitter { + constructor({timeout = 60000, maxSessions = Infinity, maxFreeSessions = 10, maxCachedTlsSessions = 100} = {}) { + super(); - for (const node of nodes) { - var _node$fields2; + // A session is considered busy when its current streams count + // is equal to or greater than the `maxConcurrentStreams` value. - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - const fieldsNodes = - /* c8 ignore next */ - (_node$fields2 = node.fields) !== null && _node$fields2 !== void 0 - ? _node$fields2 - : []; + // A session is considered free when its current streams count + // is less than the `maxConcurrentStreams` value. - for (const field of fieldsNodes) { - var _field$description2; + // SESSIONS[NORMALIZED_OPTIONS] = []; + this.sessions = {}; - // Note: While this could make assertions to get the correctly typed - // value, that would throw immediately while type system validation - // with validateSchema() will produce more actionable results. - const type = getWrappedType(field.type); - inputFieldMap[field.name.value] = { - type, - description: - (_field$description2 = field.description) === null || - _field$description2 === void 0 - ? void 0 - : _field$description2.value, - defaultValue: (0, _valueFromAST.valueFromAST)( - field.defaultValue, - type, - ), - deprecationReason: getDeprecationReason(field), - astNode: field, - }; - } - } + // The queue for creating new sessions. It looks like this: + // QUEUE[NORMALIZED_OPTIONS][NORMALIZED_ORIGIN] = ENTRY_FUNCTION + // + // The entry function has `listeners`, `completed` and `destroyed` properties. + // `listeners` is an array of objects containing `resolve` and `reject` functions. + // `completed` is a boolean. It's set to true after ENTRY_FUNCTION is executed. + // `destroyed` is a boolean. If it's set to true, the session will be destroyed if hasn't connected yet. + this.queue = {}; - return inputFieldMap; - } + // Each session will use this timeout value. + this.timeout = timeout; - function buildEnumValueMap(nodes) { - const enumValueMap = Object.create(null); + // Max sessions in total + this.maxSessions = maxSessions; - for (const node of nodes) { - var _node$values; + // Max free sessions in total + // TODO: decreasing `maxFreeSessions` should close some sessions + this.maxFreeSessions = maxFreeSessions; - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - const valuesNodes = - /* c8 ignore next */ - (_node$values = node.values) !== null && _node$values !== void 0 - ? _node$values - : []; + this._freeSessionsCount = 0; + this._sessionsCount = 0; - for (const value of valuesNodes) { - var _value$description; + // We don't support push streams by default. + this.settings = { + enablePush: false + }; - enumValueMap[value.name.value] = { - description: - (_value$description = value.description) === null || - _value$description === void 0 - ? void 0 - : _value$description.value, - deprecationReason: getDeprecationReason(value), - astNode: value, - }; - } - } + // Reusing TLS sessions increases performance. + this.tlsSessionCache = new QuickLRU({maxSize: maxCachedTlsSessions}); + } - return enumValueMap; - } + static normalizeOrigin(url, servername) { + if (typeof url === 'string') { + url = new URL(url); + } - function buildInterfaces(nodes) { - // Note: While this could make assertions to get the correctly typed - // values below, that would throw immediately while type system - // validation with validateSchema() will produce more actionable results. - // @ts-expect-error - return nodes.flatMap( - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - (node) => { - var _node$interfaces$map, _node$interfaces; + if (servername && url.hostname !== servername) { + url.hostname = servername; + } - return ( - /* c8 ignore next */ - (_node$interfaces$map = - (_node$interfaces = node.interfaces) === null || - _node$interfaces === void 0 - ? void 0 - : _node$interfaces.map(getNamedType)) !== null && - _node$interfaces$map !== void 0 - ? _node$interfaces$map - : [] - ); - }, - ); - } + return url.origin; + } - function buildUnionTypes(nodes) { - // Note: While this could make assertions to get the correctly typed - // values below, that would throw immediately while type system - // validation with validateSchema() will produce more actionable results. - // @ts-expect-error - return nodes.flatMap( - // FIXME: https://github.com/graphql/graphql-js/issues/2203 - (node) => { - var _node$types$map, _node$types; + normalizeOptions(options) { + let normalized = ''; - return ( - /* c8 ignore next */ - (_node$types$map = - (_node$types = node.types) === null || _node$types === void 0 - ? void 0 - : _node$types.map(getNamedType)) !== null && - _node$types$map !== void 0 - ? _node$types$map - : [] - ); - }, - ); - } + if (options) { + for (const key of nameKeys) { + if (options[key]) { + normalized += `:${options[key]}`; + } + } + } - function buildType(astNode) { - var _typeExtensionsMap$na; + return normalized; + } - const name = astNode.name.value; - const extensionASTNodes = - (_typeExtensionsMap$na = typeExtensionsMap[name]) !== null && - _typeExtensionsMap$na !== void 0 - ? _typeExtensionsMap$na - : []; + _tryToCreateNewSession(normalizedOptions, normalizedOrigin) { + if (!(normalizedOptions in this.queue) || !(normalizedOrigin in this.queue[normalizedOptions])) { + return; + } - switch (astNode.kind) { - case _kinds.Kind.OBJECT_TYPE_DEFINITION: { - var _astNode$description; + const item = this.queue[normalizedOptions][normalizedOrigin]; - const allNodes = [astNode, ...extensionASTNodes]; - return new _definition.GraphQLObjectType({ - name, - description: - (_astNode$description = astNode.description) === null || - _astNode$description === void 0 - ? void 0 - : _astNode$description.value, - interfaces: () => buildInterfaces(allNodes), - fields: () => buildFieldMap(allNodes), - astNode, - extensionASTNodes, - }); - } + // The entry function can be run only once. + // BUG: The session may be never created when: + // - the first condition is false AND + // - this function is never called with the same arguments in the future. + if (this._sessionsCount < this.maxSessions && !item.completed) { + item.completed = true; - case _kinds.Kind.INTERFACE_TYPE_DEFINITION: { - var _astNode$description2; + item(); + } + } - const allNodes = [astNode, ...extensionASTNodes]; - return new _definition.GraphQLInterfaceType({ - name, - description: - (_astNode$description2 = astNode.description) === null || - _astNode$description2 === void 0 - ? void 0 - : _astNode$description2.value, - interfaces: () => buildInterfaces(allNodes), - fields: () => buildFieldMap(allNodes), - astNode, - extensionASTNodes, - }); - } + getSession(origin, options, listeners) { + return new Promise((resolve, reject) => { + if (Array.isArray(listeners)) { + listeners = [...listeners]; - case _kinds.Kind.ENUM_TYPE_DEFINITION: { - var _astNode$description3; + // Resolve the current promise ASAP, we're just moving the listeners. + // They will be executed at a different time. + resolve(); + } else { + listeners = [{resolve, reject}]; + } - const allNodes = [astNode, ...extensionASTNodes]; - return new _definition.GraphQLEnumType({ - name, - description: - (_astNode$description3 = astNode.description) === null || - _astNode$description3 === void 0 - ? void 0 - : _astNode$description3.value, - values: buildEnumValueMap(allNodes), - astNode, - extensionASTNodes, - }); - } + const normalizedOptions = this.normalizeOptions(options); + const normalizedOrigin = Agent.normalizeOrigin(origin, options && options.servername); - case _kinds.Kind.UNION_TYPE_DEFINITION: { - var _astNode$description4; + if (normalizedOrigin === undefined) { + for (const {reject} of listeners) { + reject(new TypeError('The `origin` argument needs to be a string or an URL object')); + } - const allNodes = [astNode, ...extensionASTNodes]; - return new _definition.GraphQLUnionType({ - name, - description: - (_astNode$description4 = astNode.description) === null || - _astNode$description4 === void 0 - ? void 0 - : _astNode$description4.value, - types: () => buildUnionTypes(allNodes), - astNode, - extensionASTNodes, - }); - } + return; + } - case _kinds.Kind.SCALAR_TYPE_DEFINITION: { - var _astNode$description5; + if (normalizedOptions in this.sessions) { + const sessions = this.sessions[normalizedOptions]; - return new _definition.GraphQLScalarType({ - name, - description: - (_astNode$description5 = astNode.description) === null || - _astNode$description5 === void 0 - ? void 0 - : _astNode$description5.value, - specifiedByURL: getSpecifiedByURL(astNode), - astNode, - extensionASTNodes, - }); - } + let maxConcurrentStreams = -1; + let currentStreamsCount = -1; + let optimalSession; - case _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION: { - var _astNode$description6; + // We could just do this.sessions[normalizedOptions].find(...) but that isn't optimal. + // Additionally, we are looking for session which has biggest current pending streams count. + for (const session of sessions) { + const sessionMaxConcurrentStreams = session.remoteSettings.maxConcurrentStreams; - const allNodes = [astNode, ...extensionASTNodes]; - return new _definition.GraphQLInputObjectType({ - name, - description: - (_astNode$description6 = astNode.description) === null || - _astNode$description6 === void 0 - ? void 0 - : _astNode$description6.value, - fields: () => buildInputFieldMap(allNodes), - astNode, - extensionASTNodes, - isOneOf: isOneOf(astNode), - }); - } - } - } -} + if (sessionMaxConcurrentStreams < maxConcurrentStreams) { + break; + } -const stdTypeMap = (0, _keyMap.keyMap)( - [..._scalars.specifiedScalarTypes, ..._introspection.introspectionTypes], - (type) => type.name, -); -/** - * Given a field or enum value node, returns the string value for the - * deprecation reason. - */ + if (session[kOriginSet].includes(normalizedOrigin)) { + const sessionCurrentStreamsCount = session[kCurrentStreamsCount]; -function getDeprecationReason(node) { - const deprecated = (0, _values.getDirectiveValues)( - _directives.GraphQLDeprecatedDirective, - node, - ); // @ts-expect-error validated by `getDirectiveValues` + if ( + sessionCurrentStreamsCount >= sessionMaxConcurrentStreams || + session[kGracefullyClosing] || + // Unfortunately the `close` event isn't called immediately, + // so `session.destroyed` is `true`, but `session.closed` is `false`. + session.destroyed + ) { + continue; + } - return deprecated === null || deprecated === void 0 - ? void 0 - : deprecated.reason; -} -/** - * Given a scalar node, returns the string value for the specifiedByURL. - */ + // We only need set this once. + if (!optimalSession) { + maxConcurrentStreams = sessionMaxConcurrentStreams; + } -function getSpecifiedByURL(node) { - const specifiedBy = (0, _values.getDirectiveValues)( - _directives.GraphQLSpecifiedByDirective, - node, - ); // @ts-expect-error validated by `getDirectiveValues` + // We're looking for the session which has biggest current pending stream count, + // in order to minimalize the amount of active sessions. + if (sessionCurrentStreamsCount > currentStreamsCount) { + optimalSession = session; + currentStreamsCount = sessionCurrentStreamsCount; + } + } + } - return specifiedBy === null || specifiedBy === void 0 - ? void 0 - : specifiedBy.url; -} -/** - * Given an input object node, returns if the node should be OneOf. - */ + if (optimalSession) { + /* istanbul ignore next: safety check */ + if (listeners.length !== 1) { + for (const {reject} of listeners) { + const error = new Error( + `Expected the length of listeners to be 1, got ${listeners.length}.\n` + + 'Please report this to https://github.com/szmarczak/http2-wrapper/' + ); -function isOneOf(node) { - return Boolean( - (0, _values.getDirectiveValues)(_directives.GraphQLOneOfDirective, node), - ); -} + reject(error); + } + return; + } -/***/ }), + listeners[0].resolve(optimalSession); + return; + } + } -/***/ 59366: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (normalizedOptions in this.queue) { + if (normalizedOrigin in this.queue[normalizedOptions]) { + // There's already an item in the queue, just attach ourselves to it. + this.queue[normalizedOptions][normalizedOrigin].listeners.push(...listeners); -"use strict"; + // This shouldn't be executed here. + // See the comment inside _tryToCreateNewSession. + this._tryToCreateNewSession(normalizedOptions, normalizedOrigin); + return; + } + } else { + this.queue[normalizedOptions] = {}; + } + // The entry must be removed from the queue IMMEDIATELY when: + // 1. the session connects successfully, + // 2. an error occurs. + const removeFromQueue = () => { + // Our entry can be replaced. We cannot remove the new one. + if (normalizedOptions in this.queue && this.queue[normalizedOptions][normalizedOrigin] === entry) { + delete this.queue[normalizedOptions][normalizedOrigin]; -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.DangerousChangeType = exports.BreakingChangeType = void 0; -exports.findBreakingChanges = findBreakingChanges; -exports.findDangerousChanges = findDangerousChanges; + if (Object.keys(this.queue[normalizedOptions]).length === 0) { + delete this.queue[normalizedOptions]; + } + } + }; -var _inspect = __nccwpck_require__(10102); + // The main logic is here + const entry = () => { + const name = `${normalizedOrigin}:${normalizedOptions}`; + let receivedSettings = false; -var _invariant = __nccwpck_require__(28847); + try { + const session = http2.connect(origin, { + createConnection: this.createConnection, + settings: this.settings, + session: this.tlsSessionCache.get(name), + ...options + }); + session[kCurrentStreamsCount] = 0; + session[kGracefullyClosing] = false; -var _keyMap = __nccwpck_require__(10711); + const isFree = () => session[kCurrentStreamsCount] < session.remoteSettings.maxConcurrentStreams; + let wasFree = true; -var _printer = __nccwpck_require__(68203); + session.socket.once('session', tlsSession => { + this.tlsSessionCache.set(name, tlsSession); + }); -var _definition = __nccwpck_require__(32150); + session.once('error', error => { + // Listeners are empty when the session successfully connected. + for (const {reject} of listeners) { + reject(error); + } -var _scalars = __nccwpck_require__(93145); + // The connection got broken, purge the cache. + this.tlsSessionCache.delete(name); + }); -var _astFromValue = __nccwpck_require__(12653); + session.setTimeout(this.timeout, () => { + // Terminates all streams owned by this session. + // TODO: Maybe the streams should have a "Session timed out" error? + session.destroy(); + }); -var _sortValueNode = __nccwpck_require__(82278); + session.once('close', () => { + if (receivedSettings) { + // 1. If it wasn't free then no need to decrease because + // it has been decreased already in session.request(). + // 2. `stream.once('close')` won't increment the count + // because the session is already closed. + if (wasFree) { + this._freeSessionsCount--; + } -var BreakingChangeType; -exports.BreakingChangeType = BreakingChangeType; + this._sessionsCount--; -(function (BreakingChangeType) { - BreakingChangeType['TYPE_REMOVED'] = 'TYPE_REMOVED'; - BreakingChangeType['TYPE_CHANGED_KIND'] = 'TYPE_CHANGED_KIND'; - BreakingChangeType['TYPE_REMOVED_FROM_UNION'] = 'TYPE_REMOVED_FROM_UNION'; - BreakingChangeType['VALUE_REMOVED_FROM_ENUM'] = 'VALUE_REMOVED_FROM_ENUM'; - BreakingChangeType['REQUIRED_INPUT_FIELD_ADDED'] = - 'REQUIRED_INPUT_FIELD_ADDED'; - BreakingChangeType['IMPLEMENTED_INTERFACE_REMOVED'] = - 'IMPLEMENTED_INTERFACE_REMOVED'; - BreakingChangeType['FIELD_REMOVED'] = 'FIELD_REMOVED'; - BreakingChangeType['FIELD_CHANGED_KIND'] = 'FIELD_CHANGED_KIND'; - BreakingChangeType['REQUIRED_ARG_ADDED'] = 'REQUIRED_ARG_ADDED'; - BreakingChangeType['ARG_REMOVED'] = 'ARG_REMOVED'; - BreakingChangeType['ARG_CHANGED_KIND'] = 'ARG_CHANGED_KIND'; - BreakingChangeType['DIRECTIVE_REMOVED'] = 'DIRECTIVE_REMOVED'; - BreakingChangeType['DIRECTIVE_ARG_REMOVED'] = 'DIRECTIVE_ARG_REMOVED'; - BreakingChangeType['REQUIRED_DIRECTIVE_ARG_ADDED'] = - 'REQUIRED_DIRECTIVE_ARG_ADDED'; - BreakingChangeType['DIRECTIVE_REPEATABLE_REMOVED'] = - 'DIRECTIVE_REPEATABLE_REMOVED'; - BreakingChangeType['DIRECTIVE_LOCATION_REMOVED'] = - 'DIRECTIVE_LOCATION_REMOVED'; -})( - BreakingChangeType || (exports.BreakingChangeType = BreakingChangeType = {}), -); + // This cannot be moved to the stream logic, + // because there may be a session that hadn't made a single request. + const where = this.sessions[normalizedOptions]; + where.splice(where.indexOf(session), 1); -var DangerousChangeType; -exports.DangerousChangeType = DangerousChangeType; + if (where.length === 0) { + delete this.sessions[normalizedOptions]; + } + } else { + // Broken connection + const error = new Error('Session closed without receiving a SETTINGS frame'); + error.code = 'HTTP2WRAPPER_NOSETTINGS'; -(function (DangerousChangeType) { - DangerousChangeType['VALUE_ADDED_TO_ENUM'] = 'VALUE_ADDED_TO_ENUM'; - DangerousChangeType['TYPE_ADDED_TO_UNION'] = 'TYPE_ADDED_TO_UNION'; - DangerousChangeType['OPTIONAL_INPUT_FIELD_ADDED'] = - 'OPTIONAL_INPUT_FIELD_ADDED'; - DangerousChangeType['OPTIONAL_ARG_ADDED'] = 'OPTIONAL_ARG_ADDED'; - DangerousChangeType['IMPLEMENTED_INTERFACE_ADDED'] = - 'IMPLEMENTED_INTERFACE_ADDED'; - DangerousChangeType['ARG_DEFAULT_VALUE_CHANGE'] = 'ARG_DEFAULT_VALUE_CHANGE'; -})( - DangerousChangeType || - (exports.DangerousChangeType = DangerousChangeType = {}), -); + for (const {reject} of listeners) { + reject(error); + } -/** - * Given two schemas, returns an Array containing descriptions of all the types - * of breaking changes covered by the other functions down below. - */ -function findBreakingChanges(oldSchema, newSchema) { - // @ts-expect-error - return findSchemaChanges(oldSchema, newSchema).filter( - (change) => change.type in BreakingChangeType, - ); -} -/** - * Given two schemas, returns an Array containing descriptions of all the types - * of potentially dangerous changes covered by the other functions down below. - */ + removeFromQueue(); + } -function findDangerousChanges(oldSchema, newSchema) { - // @ts-expect-error - return findSchemaChanges(oldSchema, newSchema).filter( - (change) => change.type in DangerousChangeType, - ); -} + // There may be another session awaiting. + this._tryToCreateNewSession(normalizedOptions, normalizedOrigin); + }); -function findSchemaChanges(oldSchema, newSchema) { - return [ - ...findTypeChanges(oldSchema, newSchema), - ...findDirectiveChanges(oldSchema, newSchema), - ]; -} + // Iterates over the queue and processes listeners. + const processListeners = () => { + if (!(normalizedOptions in this.queue) || !isFree()) { + return; + } -function findDirectiveChanges(oldSchema, newSchema) { - const schemaChanges = []; - const directivesDiff = diff( - oldSchema.getDirectives(), - newSchema.getDirectives(), - ); + for (const origin of session[kOriginSet]) { + if (origin in this.queue[normalizedOptions]) { + const {listeners} = this.queue[normalizedOptions][origin]; - for (const oldDirective of directivesDiff.removed) { - schemaChanges.push({ - type: BreakingChangeType.DIRECTIVE_REMOVED, - description: `${oldDirective.name} was removed.`, - }); - } + // Prevents session overloading. + while (listeners.length !== 0 && isFree()) { + // We assume `resolve(...)` calls `request(...)` *directly*, + // otherwise the session will get overloaded. + listeners.shift().resolve(session); + } - for (const [oldDirective, newDirective] of directivesDiff.persisted) { - const argsDiff = diff(oldDirective.args, newDirective.args); + const where = this.queue[normalizedOptions]; + if (where[origin].listeners.length === 0) { + delete where[origin]; - for (const newArg of argsDiff.added) { - if ((0, _definition.isRequiredArgument)(newArg)) { - schemaChanges.push({ - type: BreakingChangeType.REQUIRED_DIRECTIVE_ARG_ADDED, - description: `A required arg ${newArg.name} on directive ${oldDirective.name} was added.`, - }); - } - } + if (Object.keys(where).length === 0) { + delete this.queue[normalizedOptions]; + break; + } + } - for (const oldArg of argsDiff.removed) { - schemaChanges.push({ - type: BreakingChangeType.DIRECTIVE_ARG_REMOVED, - description: `${oldArg.name} was removed from ${oldDirective.name}.`, - }); - } + // We're no longer free, no point in continuing. + if (!isFree()) { + break; + } + } + } + }; - if (oldDirective.isRepeatable && !newDirective.isRepeatable) { - schemaChanges.push({ - type: BreakingChangeType.DIRECTIVE_REPEATABLE_REMOVED, - description: `Repeatable flag was removed from ${oldDirective.name}.`, - }); - } + // The Origin Set cannot shrink. No need to check if it suddenly became covered by another one. + session.on('origin', () => { + session[kOriginSet] = session.originSet; - for (const location of oldDirective.locations) { - if (!newDirective.locations.includes(location)) { - schemaChanges.push({ - type: BreakingChangeType.DIRECTIVE_LOCATION_REMOVED, - description: `${location} was removed from ${oldDirective.name}.`, - }); - } - } - } + if (!isFree()) { + // The session is full. + return; + } - return schemaChanges; -} + processListeners(); -function findTypeChanges(oldSchema, newSchema) { - const schemaChanges = []; - const typesDiff = diff( - Object.values(oldSchema.getTypeMap()), - Object.values(newSchema.getTypeMap()), - ); + // Close covered sessions (if possible). + closeCoveredSessions(this.sessions[normalizedOptions], session); + }); - for (const oldType of typesDiff.removed) { - schemaChanges.push({ - type: BreakingChangeType.TYPE_REMOVED, - description: (0, _scalars.isSpecifiedScalarType)(oldType) - ? `Standard scalar ${oldType.name} was removed because it is not referenced anymore.` - : `${oldType.name} was removed.`, - }); - } + session.once('remoteSettings', () => { + // Fix Node.js bug preventing the process from exiting + session.ref(); + session.unref(); - for (const [oldType, newType] of typesDiff.persisted) { - if ( - (0, _definition.isEnumType)(oldType) && - (0, _definition.isEnumType)(newType) - ) { - schemaChanges.push(...findEnumTypeChanges(oldType, newType)); - } else if ( - (0, _definition.isUnionType)(oldType) && - (0, _definition.isUnionType)(newType) - ) { - schemaChanges.push(...findUnionTypeChanges(oldType, newType)); - } else if ( - (0, _definition.isInputObjectType)(oldType) && - (0, _definition.isInputObjectType)(newType) - ) { - schemaChanges.push(...findInputObjectTypeChanges(oldType, newType)); - } else if ( - (0, _definition.isObjectType)(oldType) && - (0, _definition.isObjectType)(newType) - ) { - schemaChanges.push( - ...findFieldChanges(oldType, newType), - ...findImplementedInterfacesChanges(oldType, newType), - ); - } else if ( - (0, _definition.isInterfaceType)(oldType) && - (0, _definition.isInterfaceType)(newType) - ) { - schemaChanges.push( - ...findFieldChanges(oldType, newType), - ...findImplementedInterfacesChanges(oldType, newType), - ); - } else if (oldType.constructor !== newType.constructor) { - schemaChanges.push({ - type: BreakingChangeType.TYPE_CHANGED_KIND, - description: - `${oldType.name} changed from ` + - `${typeKindName(oldType)} to ${typeKindName(newType)}.`, - }); - } - } + this._sessionsCount++; - return schemaChanges; -} + // The Agent could have been destroyed already. + if (entry.destroyed) { + const error = new Error('Agent has been destroyed'); -function findInputObjectTypeChanges(oldType, newType) { - const schemaChanges = []; - const fieldsDiff = diff( - Object.values(oldType.getFields()), - Object.values(newType.getFields()), - ); + for (const listener of listeners) { + listener.reject(error); + } - for (const newField of fieldsDiff.added) { - if ((0, _definition.isRequiredInputField)(newField)) { - schemaChanges.push({ - type: BreakingChangeType.REQUIRED_INPUT_FIELD_ADDED, - description: `A required field ${newField.name} on input type ${oldType.name} was added.`, - }); - } else { - schemaChanges.push({ - type: DangerousChangeType.OPTIONAL_INPUT_FIELD_ADDED, - description: `An optional field ${newField.name} on input type ${oldType.name} was added.`, - }); - } - } + session.destroy(); + return; + } - for (const oldField of fieldsDiff.removed) { - schemaChanges.push({ - type: BreakingChangeType.FIELD_REMOVED, - description: `${oldType.name}.${oldField.name} was removed.`, - }); - } + session[kOriginSet] = session.originSet; + + { + const where = this.sessions; + + if (normalizedOptions in where) { + const sessions = where[normalizedOptions]; + sessions.splice(getSortedIndex(sessions, session, compareSessions), 0, session); + } else { + where[normalizedOptions] = [session]; + } + } + + this._freeSessionsCount += 1; + receivedSettings = true; + + this.emit('session', session); + + processListeners(); + removeFromQueue(); + + // TODO: Close last recently used (or least used?) session + if (session[kCurrentStreamsCount] === 0 && this._freeSessionsCount > this.maxFreeSessions) { + session.close(); + } + + // Check if we haven't managed to execute all listeners. + if (listeners.length !== 0) { + // Request for a new session with predefined listeners. + this.getSession(normalizedOrigin, options, listeners); + listeners.length = 0; + } - for (const [oldField, newField] of fieldsDiff.persisted) { - const isSafe = isChangeSafeForInputObjectFieldOrFieldArg( - oldField.type, - newField.type, - ); + // `session.remoteSettings.maxConcurrentStreams` might get increased + session.on('remoteSettings', () => { + processListeners(); - if (!isSafe) { - schemaChanges.push({ - type: BreakingChangeType.FIELD_CHANGED_KIND, - description: - `${oldType.name}.${oldField.name} changed type from ` + - `${String(oldField.type)} to ${String(newField.type)}.`, - }); - } - } + // In case the Origin Set changes + closeCoveredSessions(this.sessions[normalizedOptions], session); + }); + }); - return schemaChanges; -} + // Shim `session.request()` in order to catch all streams + session[kRequest] = session.request; + session.request = (headers, streamOptions) => { + if (session[kGracefullyClosing]) { + throw new Error('The session is gracefully closing. No new streams are allowed.'); + } -function findUnionTypeChanges(oldType, newType) { - const schemaChanges = []; - const possibleTypesDiff = diff(oldType.getTypes(), newType.getTypes()); + const stream = session[kRequest](headers, streamOptions); - for (const newPossibleType of possibleTypesDiff.added) { - schemaChanges.push({ - type: DangerousChangeType.TYPE_ADDED_TO_UNION, - description: `${newPossibleType.name} was added to union type ${oldType.name}.`, - }); - } + // The process won't exit until the session is closed or all requests are gone. + session.ref(); - for (const oldPossibleType of possibleTypesDiff.removed) { - schemaChanges.push({ - type: BreakingChangeType.TYPE_REMOVED_FROM_UNION, - description: `${oldPossibleType.name} was removed from union type ${oldType.name}.`, - }); - } + ++session[kCurrentStreamsCount]; - return schemaChanges; -} + if (session[kCurrentStreamsCount] === session.remoteSettings.maxConcurrentStreams) { + this._freeSessionsCount--; + } -function findEnumTypeChanges(oldType, newType) { - const schemaChanges = []; - const valuesDiff = diff(oldType.getValues(), newType.getValues()); + stream.once('close', () => { + wasFree = isFree(); - for (const newValue of valuesDiff.added) { - schemaChanges.push({ - type: DangerousChangeType.VALUE_ADDED_TO_ENUM, - description: `${newValue.name} was added to enum type ${oldType.name}.`, - }); - } + --session[kCurrentStreamsCount]; - for (const oldValue of valuesDiff.removed) { - schemaChanges.push({ - type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM, - description: `${oldValue.name} was removed from enum type ${oldType.name}.`, - }); - } + if (!session.destroyed && !session.closed) { + closeSessionIfCovered(this.sessions[normalizedOptions], session); - return schemaChanges; -} + if (isFree() && !session.closed) { + if (!wasFree) { + this._freeSessionsCount++; -function findImplementedInterfacesChanges(oldType, newType) { - const schemaChanges = []; - const interfacesDiff = diff(oldType.getInterfaces(), newType.getInterfaces()); + wasFree = true; + } - for (const newInterface of interfacesDiff.added) { - schemaChanges.push({ - type: DangerousChangeType.IMPLEMENTED_INTERFACE_ADDED, - description: `${newInterface.name} added to interfaces implemented by ${oldType.name}.`, - }); - } + const isEmpty = session[kCurrentStreamsCount] === 0; - for (const oldInterface of interfacesDiff.removed) { - schemaChanges.push({ - type: BreakingChangeType.IMPLEMENTED_INTERFACE_REMOVED, - description: `${oldType.name} no longer implements interface ${oldInterface.name}.`, - }); - } + if (isEmpty) { + session.unref(); + } - return schemaChanges; -} + if ( + isEmpty && + ( + this._freeSessionsCount > this.maxFreeSessions || + session[kGracefullyClosing] + ) + ) { + session.close(); + } else { + closeCoveredSessions(this.sessions[normalizedOptions], session); + processListeners(); + } + } + } + }); -function findFieldChanges(oldType, newType) { - const schemaChanges = []; - const fieldsDiff = diff( - Object.values(oldType.getFields()), - Object.values(newType.getFields()), - ); + return stream; + }; + } catch (error) { + for (const listener of listeners) { + listener.reject(error); + } - for (const oldField of fieldsDiff.removed) { - schemaChanges.push({ - type: BreakingChangeType.FIELD_REMOVED, - description: `${oldType.name}.${oldField.name} was removed.`, - }); - } + removeFromQueue(); + } + }; - for (const [oldField, newField] of fieldsDiff.persisted) { - schemaChanges.push(...findArgChanges(oldType, oldField, newField)); - const isSafe = isChangeSafeForObjectOrInterfaceField( - oldField.type, - newField.type, - ); + entry.listeners = listeners; + entry.completed = false; + entry.destroyed = false; - if (!isSafe) { - schemaChanges.push({ - type: BreakingChangeType.FIELD_CHANGED_KIND, - description: - `${oldType.name}.${oldField.name} changed type from ` + - `${String(oldField.type)} to ${String(newField.type)}.`, - }); - } - } + this.queue[normalizedOptions][normalizedOrigin] = entry; + this._tryToCreateNewSession(normalizedOptions, normalizedOrigin); + }); + } - return schemaChanges; -} + request(origin, options, headers, streamOptions) { + return new Promise((resolve, reject) => { + this.getSession(origin, options, [{ + reject, + resolve: session => { + try { + resolve(session.request(headers, streamOptions)); + } catch (error) { + reject(error); + } + } + }]); + }); + } -function findArgChanges(oldType, oldField, newField) { - const schemaChanges = []; - const argsDiff = diff(oldField.args, newField.args); + createConnection(origin, options) { + return Agent.connect(origin, options); + } - for (const oldArg of argsDiff.removed) { - schemaChanges.push({ - type: BreakingChangeType.ARG_REMOVED, - description: `${oldType.name}.${oldField.name} arg ${oldArg.name} was removed.`, - }); - } + static connect(origin, options) { + options.ALPNProtocols = ['h2']; - for (const [oldArg, newArg] of argsDiff.persisted) { - const isSafe = isChangeSafeForInputObjectFieldOrFieldArg( - oldArg.type, - newArg.type, - ); + const port = origin.port || 443; + const host = origin.hostname || origin.host; - if (!isSafe) { - schemaChanges.push({ - type: BreakingChangeType.ARG_CHANGED_KIND, - description: - `${oldType.name}.${oldField.name} arg ${oldArg.name} has changed type from ` + - `${String(oldArg.type)} to ${String(newArg.type)}.`, - }); - } else if (oldArg.defaultValue !== undefined) { - if (newArg.defaultValue === undefined) { - schemaChanges.push({ - type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, - description: `${oldType.name}.${oldField.name} arg ${oldArg.name} defaultValue was removed.`, - }); - } else { - // Since we looking only for client's observable changes we should - // compare default values in the same representation as they are - // represented inside introspection. - const oldValueStr = stringifyValue(oldArg.defaultValue, oldArg.type); - const newValueStr = stringifyValue(newArg.defaultValue, newArg.type); + if (typeof options.servername === 'undefined') { + options.servername = host; + } - if (oldValueStr !== newValueStr) { - schemaChanges.push({ - type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, - description: `${oldType.name}.${oldField.name} arg ${oldArg.name} has changed defaultValue from ${oldValueStr} to ${newValueStr}.`, - }); - } - } - } - } + return tls.connect(port, host, options); + } - for (const newArg of argsDiff.added) { - if ((0, _definition.isRequiredArgument)(newArg)) { - schemaChanges.push({ - type: BreakingChangeType.REQUIRED_ARG_ADDED, - description: `A required arg ${newArg.name} on ${oldType.name}.${oldField.name} was added.`, - }); - } else { - schemaChanges.push({ - type: DangerousChangeType.OPTIONAL_ARG_ADDED, - description: `An optional arg ${newArg.name} on ${oldType.name}.${oldField.name} was added.`, - }); - } - } + closeFreeSessions() { + for (const sessions of Object.values(this.sessions)) { + for (const session of sessions) { + if (session[kCurrentStreamsCount] === 0) { + session.close(); + } + } + } + } - return schemaChanges; -} + destroy(reason) { + for (const sessions of Object.values(this.sessions)) { + for (const session of sessions) { + session.destroy(reason); + } + } -function isChangeSafeForObjectOrInterfaceField(oldType, newType) { - if ((0, _definition.isListType)(oldType)) { - return ( - // if they're both lists, make sure the underlying types are compatible - ((0, _definition.isListType)(newType) && - isChangeSafeForObjectOrInterfaceField( - oldType.ofType, - newType.ofType, - )) || // moving from nullable to non-null of the same underlying type is safe - ((0, _definition.isNonNullType)(newType) && - isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType)) - ); - } + for (const entriesOfAuthority of Object.values(this.queue)) { + for (const entry of Object.values(entriesOfAuthority)) { + entry.destroyed = true; + } + } - if ((0, _definition.isNonNullType)(oldType)) { - // if they're both non-null, make sure the underlying types are compatible - return ( - (0, _definition.isNonNullType)(newType) && - isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType) - ); - } + // New requests should NOT attach to destroyed sessions + this.queue = {}; + } - return ( - // if they're both named types, see if their names are equivalent - ((0, _definition.isNamedType)(newType) && oldType.name === newType.name) || // moving from nullable to non-null of the same underlying type is safe - ((0, _definition.isNonNullType)(newType) && - isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType)) - ); + get freeSessions() { + return getSessions({agent: this, isFree: true}); + } + + get busySessions() { + return getSessions({agent: this, isFree: false}); + } } -function isChangeSafeForInputObjectFieldOrFieldArg(oldType, newType) { - if ((0, _definition.isListType)(oldType)) { - // if they're both lists, make sure the underlying types are compatible - return ( - (0, _definition.isListType)(newType) && - isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType) - ); - } +Agent.kCurrentStreamsCount = kCurrentStreamsCount; +Agent.kGracefullyClosing = kGracefullyClosing; - if ((0, _definition.isNonNullType)(oldType)) { - return ( - // if they're both non-null, make sure the underlying types are - // compatible - ((0, _definition.isNonNullType)(newType) && - isChangeSafeForInputObjectFieldOrFieldArg( - oldType.ofType, - newType.ofType, - )) || // moving from non-null to nullable of the same underlying type is safe - (!(0, _definition.isNonNullType)(newType) && - isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType)) - ); - } // if they're both named types, see if their names are equivalent +module.exports = { + Agent, + globalAgent: new Agent() +}; - return (0, _definition.isNamedType)(newType) && oldType.name === newType.name; -} -function typeKindName(type) { - if ((0, _definition.isScalarType)(type)) { - return 'a Scalar type'; - } +/***/ }), - if ((0, _definition.isObjectType)(type)) { - return 'an Object type'; - } +/***/ 97167: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if ((0, _definition.isInterfaceType)(type)) { - return 'an Interface type'; - } +"use strict"; - if ((0, _definition.isUnionType)(type)) { - return 'a Union type'; - } +const http = __nccwpck_require__(13685); +const https = __nccwpck_require__(95687); +const resolveALPN = __nccwpck_require__(46624); +const QuickLRU = __nccwpck_require__(49273); +const Http2ClientRequest = __nccwpck_require__(59632); +const calculateServerName = __nccwpck_require__(51982); +const urlToOptions = __nccwpck_require__(92686); - if ((0, _definition.isEnumType)(type)) { - return 'an Enum type'; - } +const cache = new QuickLRU({maxSize: 100}); +const queue = new Map(); - if ((0, _definition.isInputObjectType)(type)) { - return 'an Input type'; - } - /* c8 ignore next 3 */ - // Not reachable, all possible types have been considered. +const installSocket = (agent, socket, options) => { + socket._httpMessage = {shouldKeepAlive: true}; - false || - (0, _invariant.invariant)( - false, - 'Unexpected type: ' + (0, _inspect.inspect)(type), - ); -} + const onFree = () => { + agent.emit('free', socket, options); + }; -function stringifyValue(value, type) { - const ast = (0, _astFromValue.astFromValue)(value, type); - ast != null || (0, _invariant.invariant)(false); - return (0, _printer.print)((0, _sortValueNode.sortValueNode)(ast)); -} + socket.on('free', onFree); -function diff(oldArray, newArray) { - const added = []; - const removed = []; - const persisted = []; - const oldMap = (0, _keyMap.keyMap)(oldArray, ({ name }) => name); - const newMap = (0, _keyMap.keyMap)(newArray, ({ name }) => name); + const onClose = () => { + agent.removeSocket(socket, options); + }; - for (const oldItem of oldArray) { - const newItem = newMap[oldItem.name]; + socket.on('close', onClose); - if (newItem === undefined) { - removed.push(oldItem); - } else { - persisted.push([oldItem, newItem]); - } - } + const onRemove = () => { + agent.removeSocket(socket, options); + socket.off('close', onClose); + socket.off('free', onFree); + socket.off('agentRemove', onRemove); + }; - for (const newItem of newArray) { - if (oldMap[newItem.name] === undefined) { - added.push(newItem); - } - } + socket.on('agentRemove', onRemove); - return { - added, - persisted, - removed, - }; -} + agent.emit('free', socket, options); +}; +const resolveProtocol = async options => { + const name = `${options.host}:${options.port}:${options.ALPNProtocols.sort()}`; -/***/ }), + if (!cache.has(name)) { + if (queue.has(name)) { + const result = await queue.get(name); + return result.alpnProtocol; + } -/***/ 747: -/***/ ((__unused_webpack_module, exports) => { + const {path, agent} = options; + options.path = options.socketPath; -"use strict"; + const resultPromise = resolveALPN(options); + queue.set(name, resultPromise); + try { + const {socket, alpnProtocol} = await resultPromise; + cache.set(name, alpnProtocol); -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.getIntrospectionQuery = getIntrospectionQuery; + options.path = path; -/** - * Produce the GraphQL query recommended for a full schema introspection. - * Accepts optional IntrospectionOptions. - */ -function getIntrospectionQuery(options) { - const optionsWithDefault = { - descriptions: true, - specifiedByUrl: false, - directiveIsRepeatable: false, - schemaDescription: false, - inputValueDeprecation: false, - oneOf: false, - ...options, - }; - const descriptions = optionsWithDefault.descriptions ? 'description' : ''; - const specifiedByUrl = optionsWithDefault.specifiedByUrl - ? 'specifiedByURL' - : ''; - const directiveIsRepeatable = optionsWithDefault.directiveIsRepeatable - ? 'isRepeatable' - : ''; - const schemaDescription = optionsWithDefault.schemaDescription - ? descriptions - : ''; + if (alpnProtocol === 'h2') { + // https://github.com/nodejs/node/issues/33343 + socket.destroy(); + } else { + const {globalAgent} = https; + const defaultCreateConnection = https.Agent.prototype.createConnection; - function inputDeprecation(str) { - return optionsWithDefault.inputValueDeprecation ? str : ''; - } + if (agent) { + if (agent.createConnection === defaultCreateConnection) { + installSocket(agent, socket, options); + } else { + socket.destroy(); + } + } else if (globalAgent.createConnection === defaultCreateConnection) { + installSocket(globalAgent, socket, options); + } else { + socket.destroy(); + } + } - const oneOf = optionsWithDefault.oneOf ? 'isOneOf' : ''; - return ` - query IntrospectionQuery { - __schema { - ${schemaDescription} - queryType { name kind } - mutationType { name kind } - subscriptionType { name kind } - types { - ...FullType - } - directives { - name - ${descriptions} - ${directiveIsRepeatable} - locations - args${inputDeprecation('(includeDeprecated: true)')} { - ...InputValue - } - } - } - } + queue.delete(name); - fragment FullType on __Type { - kind - name - ${descriptions} - ${specifiedByUrl} - ${oneOf} - fields(includeDeprecated: true) { - name - ${descriptions} - args${inputDeprecation('(includeDeprecated: true)')} { - ...InputValue - } - type { - ...TypeRef - } - isDeprecated - deprecationReason - } - inputFields${inputDeprecation('(includeDeprecated: true)')} { - ...InputValue - } - interfaces { - ...TypeRef - } - enumValues(includeDeprecated: true) { - name - ${descriptions} - isDeprecated - deprecationReason - } - possibleTypes { - ...TypeRef - } - } + return alpnProtocol; + } catch (error) { + queue.delete(name); - fragment InputValue on __InputValue { - name - ${descriptions} - type { ...TypeRef } - defaultValue - ${inputDeprecation('isDeprecated')} - ${inputDeprecation('deprecationReason')} - } + throw error; + } + } - fragment TypeRef on __Type { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - } - } - } - } - } - } - } - } - } - } - `; -} + return cache.get(name); +}; +module.exports = async (input, options, callback) => { + if (typeof input === 'string' || input instanceof URL) { + input = urlToOptions(new URL(input)); + } -/***/ }), + if (typeof options === 'function') { + callback = options; + options = undefined; + } -/***/ 92854: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + options = { + ALPNProtocols: ['h2', 'http/1.1'], + ...input, + ...options, + resolveSocket: true + }; -"use strict"; + if (!Array.isArray(options.ALPNProtocols) || options.ALPNProtocols.length === 0) { + throw new Error('The `ALPNProtocols` option must be an Array with at least one entry'); + } + options.protocol = options.protocol || 'https:'; + const isHttps = options.protocol === 'https:'; -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.getOperationAST = getOperationAST; + options.host = options.hostname || options.host || 'localhost'; + options.session = options.tlsSession; + options.servername = options.servername || calculateServerName(options); + options.port = options.port || (isHttps ? 443 : 80); + options._defaultAgent = isHttps ? https.globalAgent : http.globalAgent; -var _kinds = __nccwpck_require__(11927); + const agents = options.agent; -/** - * Returns an operation AST given a document AST and optionally an operation - * name. If a name is not provided, an operation is only returned if only one is - * provided in the document. - */ -function getOperationAST(documentAST, operationName) { - let operation = null; + if (agents) { + if (agents.addRequest) { + throw new Error('The `options.agent` object can contain only `http`, `https` or `http2` properties'); + } - for (const definition of documentAST.definitions) { - if (definition.kind === _kinds.Kind.OPERATION_DEFINITION) { - var _definition$name; + options.agent = agents[isHttps ? 'https' : 'http']; + } - if (operationName == null) { - // If no operation name was provided, only return an Operation if there - // is one defined in the document. Upon encountering the second, return - // null. - if (operation) { - return null; - } + if (isHttps) { + const protocol = await resolveProtocol(options); - operation = definition; - } else if ( - ((_definition$name = definition.name) === null || - _definition$name === void 0 - ? void 0 - : _definition$name.value) === operationName - ) { - return definition; - } - } - } + if (protocol === 'h2') { + if (agents) { + options.agent = agents.http2; + } - return operation; -} + return new Http2ClientRequest(options, callback); + } + } + return http.request(options, callback); +}; -/***/ }), +module.exports.protocolCache = cache; -/***/ 81605: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +/***/ }), +/***/ 59632: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.getOperationRootType = getOperationRootType; +"use strict"; -var _GraphQLError = __nccwpck_require__(4797); +const http2 = __nccwpck_require__(85158); +const {Writable} = __nccwpck_require__(12781); +const {Agent, globalAgent} = __nccwpck_require__(79898); +const IncomingMessage = __nccwpck_require__(82575); +const urlToOptions = __nccwpck_require__(92686); +const proxyEvents = __nccwpck_require__(81818); +const isRequestPseudoHeader = __nccwpck_require__(11199); +const { + ERR_INVALID_ARG_TYPE, + ERR_INVALID_PROTOCOL, + ERR_HTTP_HEADERS_SENT, + ERR_INVALID_HTTP_TOKEN, + ERR_HTTP_INVALID_HEADER_VALUE, + ERR_INVALID_CHAR +} = __nccwpck_require__(7087); -/** - * Extracts the root type of the operation from the schema. - * - * @deprecated Please use `GraphQLSchema.getRootType` instead. Will be removed in v17 - */ -function getOperationRootType(schema, operation) { - if (operation.operation === 'query') { - const queryType = schema.getQueryType(); +const { + HTTP2_HEADER_STATUS, + HTTP2_HEADER_METHOD, + HTTP2_HEADER_PATH, + HTTP2_METHOD_CONNECT +} = http2.constants; - if (!queryType) { - throw new _GraphQLError.GraphQLError( - 'Schema does not define the required query root type.', - { - nodes: operation, - }, - ); - } +const kHeaders = Symbol('headers'); +const kOrigin = Symbol('origin'); +const kSession = Symbol('session'); +const kOptions = Symbol('options'); +const kFlushedHeaders = Symbol('flushedHeaders'); +const kJobs = Symbol('jobs'); - return queryType; - } +const isValidHttpToken = /^[\^`\-\w!#$%&*+.|~]+$/; +const isInvalidHeaderValue = /[^\t\u0020-\u007E\u0080-\u00FF]/; - if (operation.operation === 'mutation') { - const mutationType = schema.getMutationType(); +class ClientRequest extends Writable { + constructor(input, options, callback) { + super({ + autoDestroy: false + }); - if (!mutationType) { - throw new _GraphQLError.GraphQLError( - 'Schema is not configured for mutations.', - { - nodes: operation, - }, - ); - } + const hasInput = typeof input === 'string' || input instanceof URL; + if (hasInput) { + input = urlToOptions(input instanceof URL ? input : new URL(input)); + } - return mutationType; - } + if (typeof options === 'function' || options === undefined) { + // (options, callback) + callback = options; + options = hasInput ? input : {...input}; + } else { + // (input, options, callback) + options = {...input, ...options}; + } - if (operation.operation === 'subscription') { - const subscriptionType = schema.getSubscriptionType(); + if (options.h2session) { + this[kSession] = options.h2session; + } else if (options.agent === false) { + this.agent = new Agent({maxFreeSessions: 0}); + } else if (typeof options.agent === 'undefined' || options.agent === null) { + if (typeof options.createConnection === 'function') { + // This is a workaround - we don't have to create the session on our own. + this.agent = new Agent({maxFreeSessions: 0}); + this.agent.createConnection = options.createConnection; + } else { + this.agent = globalAgent; + } + } else if (typeof options.agent.request === 'function') { + this.agent = options.agent; + } else { + throw new ERR_INVALID_ARG_TYPE('options.agent', ['Agent-like Object', 'undefined', 'false'], options.agent); + } - if (!subscriptionType) { - throw new _GraphQLError.GraphQLError( - 'Schema is not configured for subscriptions.', - { - nodes: operation, - }, - ); - } + if (options.protocol && options.protocol !== 'https:') { + throw new ERR_INVALID_PROTOCOL(options.protocol, 'https:'); + } - return subscriptionType; - } + const port = options.port || options.defaultPort || (this.agent && this.agent.defaultPort) || 443; + const host = options.hostname || options.host || 'localhost'; - throw new _GraphQLError.GraphQLError( - 'Can only have query, mutation and subscription operations.', - { - nodes: operation, - }, - ); -} + // Don't enforce the origin via options. It may be changed in an Agent. + delete options.hostname; + delete options.host; + delete options.port; + const {timeout} = options; + options.timeout = undefined; -/***/ }), + this[kHeaders] = Object.create(null); + this[kJobs] = []; -/***/ 676: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + this.socket = null; + this.connection = null; -"use strict"; + this.method = options.method || 'GET'; + this.path = options.path; + this.res = null; + this.aborted = false; + this.reusedSocket = false; -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -Object.defineProperty(exports, "BreakingChangeType", ({ - enumerable: true, - get: function () { - return _findBreakingChanges.BreakingChangeType; - }, -})); -Object.defineProperty(exports, "DangerousChangeType", ({ - enumerable: true, - get: function () { - return _findBreakingChanges.DangerousChangeType; - }, -})); -Object.defineProperty(exports, "TypeInfo", ({ - enumerable: true, - get: function () { - return _TypeInfo.TypeInfo; - }, -})); -Object.defineProperty(exports, "assertValidName", ({ - enumerable: true, - get: function () { - return _assertValidName.assertValidName; - }, -})); -Object.defineProperty(exports, "astFromValue", ({ - enumerable: true, - get: function () { - return _astFromValue.astFromValue; - }, -})); -Object.defineProperty(exports, "buildASTSchema", ({ - enumerable: true, - get: function () { - return _buildASTSchema.buildASTSchema; - }, -})); -Object.defineProperty(exports, "buildClientSchema", ({ - enumerable: true, - get: function () { - return _buildClientSchema.buildClientSchema; - }, -})); -Object.defineProperty(exports, "buildSchema", ({ - enumerable: true, - get: function () { - return _buildASTSchema.buildSchema; - }, -})); -Object.defineProperty(exports, "coerceInputValue", ({ - enumerable: true, - get: function () { - return _coerceInputValue.coerceInputValue; - }, -})); -Object.defineProperty(exports, "concatAST", ({ - enumerable: true, - get: function () { - return _concatAST.concatAST; - }, -})); -Object.defineProperty(exports, "doTypesOverlap", ({ - enumerable: true, - get: function () { - return _typeComparators.doTypesOverlap; - }, -})); -Object.defineProperty(exports, "extendSchema", ({ - enumerable: true, - get: function () { - return _extendSchema.extendSchema; - }, -})); -Object.defineProperty(exports, "findBreakingChanges", ({ - enumerable: true, - get: function () { - return _findBreakingChanges.findBreakingChanges; - }, -})); -Object.defineProperty(exports, "findDangerousChanges", ({ - enumerable: true, - get: function () { - return _findBreakingChanges.findDangerousChanges; - }, -})); -Object.defineProperty(exports, "getIntrospectionQuery", ({ - enumerable: true, - get: function () { - return _getIntrospectionQuery.getIntrospectionQuery; - }, -})); -Object.defineProperty(exports, "getOperationAST", ({ - enumerable: true, - get: function () { - return _getOperationAST.getOperationAST; - }, -})); -Object.defineProperty(exports, "getOperationRootType", ({ - enumerable: true, - get: function () { - return _getOperationRootType.getOperationRootType; - }, -})); -Object.defineProperty(exports, "introspectionFromSchema", ({ - enumerable: true, - get: function () { - return _introspectionFromSchema.introspectionFromSchema; - }, -})); -Object.defineProperty(exports, "isEqualType", ({ - enumerable: true, - get: function () { - return _typeComparators.isEqualType; - }, -})); -Object.defineProperty(exports, "isTypeSubTypeOf", ({ - enumerable: true, - get: function () { - return _typeComparators.isTypeSubTypeOf; - }, -})); -Object.defineProperty(exports, "isValidNameError", ({ - enumerable: true, - get: function () { - return _assertValidName.isValidNameError; - }, -})); -Object.defineProperty(exports, "lexicographicSortSchema", ({ - enumerable: true, - get: function () { - return _lexicographicSortSchema.lexicographicSortSchema; - }, -})); -Object.defineProperty(exports, "printIntrospectionSchema", ({ - enumerable: true, - get: function () { - return _printSchema.printIntrospectionSchema; - }, -})); -Object.defineProperty(exports, "printSchema", ({ - enumerable: true, - get: function () { - return _printSchema.printSchema; - }, -})); -Object.defineProperty(exports, "printType", ({ - enumerable: true, - get: function () { - return _printSchema.printType; - }, -})); -Object.defineProperty(exports, "separateOperations", ({ - enumerable: true, - get: function () { - return _separateOperations.separateOperations; - }, -})); -Object.defineProperty(exports, "stripIgnoredCharacters", ({ - enumerable: true, - get: function () { - return _stripIgnoredCharacters.stripIgnoredCharacters; - }, -})); -Object.defineProperty(exports, "typeFromAST", ({ - enumerable: true, - get: function () { - return _typeFromAST.typeFromAST; - }, -})); -Object.defineProperty(exports, "valueFromAST", ({ - enumerable: true, - get: function () { - return _valueFromAST.valueFromAST; - }, -})); -Object.defineProperty(exports, "valueFromASTUntyped", ({ - enumerable: true, - get: function () { - return _valueFromASTUntyped.valueFromASTUntyped; - }, -})); -Object.defineProperty(exports, "visitWithTypeInfo", ({ - enumerable: true, - get: function () { - return _TypeInfo.visitWithTypeInfo; - }, -})); + if (options.headers) { + for (const [header, value] of Object.entries(options.headers)) { + this.setHeader(header, value); + } + } -var _getIntrospectionQuery = __nccwpck_require__(747); + if (options.auth && !('authorization' in this[kHeaders])) { + this[kHeaders].authorization = 'Basic ' + Buffer.from(options.auth).toString('base64'); + } -var _getOperationAST = __nccwpck_require__(92854); + options.session = options.tlsSession; + options.path = options.socketPath; -var _getOperationRootType = __nccwpck_require__(81605); + this[kOptions] = options; -var _introspectionFromSchema = __nccwpck_require__(47371); + // Clients that generate HTTP/2 requests directly SHOULD use the :authority pseudo-header field instead of the Host header field. + if (port === 443) { + this[kOrigin] = `https://${host}`; -var _buildClientSchema = __nccwpck_require__(9352); + if (!(':authority' in this[kHeaders])) { + this[kHeaders][':authority'] = host; + } + } else { + this[kOrigin] = `https://${host}:${port}`; -var _buildASTSchema = __nccwpck_require__(9337); + if (!(':authority' in this[kHeaders])) { + this[kHeaders][':authority'] = `${host}:${port}`; + } + } -var _extendSchema = __nccwpck_require__(51832); + if (timeout) { + this.setTimeout(timeout); + } -var _lexicographicSortSchema = __nccwpck_require__(19447); + if (callback) { + this.once('response', callback); + } -var _printSchema = __nccwpck_require__(84166); + this[kFlushedHeaders] = false; + } -var _typeFromAST = __nccwpck_require__(27664); + get method() { + return this[kHeaders][HTTP2_HEADER_METHOD]; + } -var _valueFromAST = __nccwpck_require__(83181); + set method(value) { + if (value) { + this[kHeaders][HTTP2_HEADER_METHOD] = value.toUpperCase(); + } + } -var _valueFromASTUntyped = __nccwpck_require__(86699); + get path() { + return this[kHeaders][HTTP2_HEADER_PATH]; + } -var _astFromValue = __nccwpck_require__(12653); + set path(value) { + if (value) { + this[kHeaders][HTTP2_HEADER_PATH] = value; + } + } -var _TypeInfo = __nccwpck_require__(76625); + get _mustNotHaveABody() { + return this.method === 'GET' || this.method === 'HEAD' || this.method === 'DELETE'; + } -var _coerceInputValue = __nccwpck_require__(39603); + _write(chunk, encoding, callback) { + // https://github.com/nodejs/node/blob/654df09ae0c5e17d1b52a900a545f0664d8c7627/lib/internal/http2/util.js#L148-L156 + if (this._mustNotHaveABody) { + callback(new Error('The GET, HEAD and DELETE methods must NOT have a body')); + /* istanbul ignore next: Node.js 12 throws directly */ + return; + } -var _concatAST = __nccwpck_require__(17232); + this.flushHeaders(); -var _separateOperations = __nccwpck_require__(29125); + const callWrite = () => this._request.write(chunk, encoding, callback); + if (this._request) { + callWrite(); + } else { + this[kJobs].push(callWrite); + } + } -var _stripIgnoredCharacters = __nccwpck_require__(17766); + _final(callback) { + if (this.destroyed) { + return; + } -var _typeComparators = __nccwpck_require__(10333); + this.flushHeaders(); -var _assertValidName = __nccwpck_require__(25780); + const callEnd = () => { + // For GET, HEAD and DELETE + if (this._mustNotHaveABody) { + callback(); + return; + } -var _findBreakingChanges = __nccwpck_require__(59366); + this._request.end(callback); + }; + if (this._request) { + callEnd(); + } else { + this[kJobs].push(callEnd); + } + } -/***/ }), + abort() { + if (this.res && this.res.complete) { + return; + } -/***/ 47371: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (!this.aborted) { + process.nextTick(() => this.emit('abort')); + } -"use strict"; + this.aborted = true; + this.destroy(); + } -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.introspectionFromSchema = introspectionFromSchema; + _destroy(error, callback) { + if (this.res) { + this.res._dump(); + } -var _invariant = __nccwpck_require__(28847); + if (this._request) { + this._request.destroy(); + } -var _parser = __nccwpck_require__(50655); + callback(error); + } -var _execute = __nccwpck_require__(83677); + async flushHeaders() { + if (this[kFlushedHeaders] || this.destroyed) { + return; + } -var _getIntrospectionQuery = __nccwpck_require__(747); + this[kFlushedHeaders] = true; -/** - * Build an IntrospectionQuery from a GraphQLSchema - * - * IntrospectionQuery is useful for utilities that care about type and field - * relationships, but do not need to traverse through those relationships. - * - * This is the inverse of buildClientSchema. The primary use case is outside - * of the server context, for instance when doing schema comparisons. - */ -function introspectionFromSchema(schema, options) { - const optionsWithDefaults = { - specifiedByUrl: true, - directiveIsRepeatable: true, - schemaDescription: true, - inputValueDeprecation: true, - oneOf: true, - ...options, - }; - const document = (0, _parser.parse)( - (0, _getIntrospectionQuery.getIntrospectionQuery)(optionsWithDefaults), - ); - const result = (0, _execute.executeSync)({ - schema, - document, - }); - (!result.errors && result.data) || (0, _invariant.invariant)(false); - return result.data; -} + const isConnectMethod = this.method === HTTP2_METHOD_CONNECT; + // The real magic is here + const onStream = stream => { + this._request = stream; -/***/ }), + if (this.destroyed) { + stream.destroy(); + return; + } -/***/ 19447: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // Forwards `timeout`, `continue`, `close` and `error` events to this instance. + if (!isConnectMethod) { + proxyEvents(stream, this, ['timeout', 'continue', 'close', 'error']); + } -"use strict"; + // Wait for the `finish` event. We don't want to emit the `response` event + // before `request.end()` is called. + const waitForEnd = fn => { + return (...args) => { + if (!this.writable && !this.destroyed) { + fn(...args); + } else { + this.once('finish', () => { + fn(...args); + }); + } + }; + }; + // This event tells we are ready to listen for the data. + stream.once('response', waitForEnd((headers, flags, rawHeaders) => { + // If we were to emit raw request stream, it would be as fast as the native approach. + // Note that wrapping the raw stream in a Proxy instance won't improve the performance (already tested it). + const response = new IncomingMessage(this.socket, stream.readableHighWaterMark); + this.res = response; -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.lexicographicSortSchema = lexicographicSortSchema; + response.req = this; + response.statusCode = headers[HTTP2_HEADER_STATUS]; + response.headers = headers; + response.rawHeaders = rawHeaders; -var _inspect = __nccwpck_require__(10102); + response.once('end', () => { + if (this.aborted) { + response.aborted = true; + response.emit('aborted'); + } else { + response.complete = true; -var _invariant = __nccwpck_require__(28847); + // Has no effect, just be consistent with the Node.js behavior + response.socket = null; + response.connection = null; + } + }); -var _keyValMap = __nccwpck_require__(49268); + if (isConnectMethod) { + response.upgrade = true; -var _naturalCompare = __nccwpck_require__(20038); + // The HTTP1 API says the socket is detached here, + // but we can't do that so we pass the original HTTP2 request. + if (this.emit('connect', response, stream, Buffer.alloc(0))) { + this.emit('close'); + } else { + // No listeners attached, destroy the original request. + stream.destroy(); + } + } else { + // Forwards data + stream.on('data', chunk => { + if (!response._dumped && !response.push(chunk)) { + stream.pause(); + } + }); -var _definition = __nccwpck_require__(32150); + stream.once('end', () => { + response.push(null); + }); -var _directives = __nccwpck_require__(83614); + if (!this.emit('response', response)) { + // No listeners attached, dump the response. + response._dump(); + } + } + })); -var _introspection = __nccwpck_require__(28344); + // Emits `information` event + stream.once('headers', waitForEnd( + headers => this.emit('information', {statusCode: headers[HTTP2_HEADER_STATUS]}) + )); -var _schema = __nccwpck_require__(8505); + stream.once('trailers', waitForEnd((trailers, flags, rawTrailers) => { + const {res} = this; -/** - * Sort GraphQLSchema. - * - * This function returns a sorted copy of the given GraphQLSchema. - */ -function lexicographicSortSchema(schema) { - const schemaConfig = schema.toConfig(); - const typeMap = (0, _keyValMap.keyValMap)( - sortByName(schemaConfig.types), - (type) => type.name, - sortNamedType, - ); - return new _schema.GraphQLSchema({ - ...schemaConfig, - types: Object.values(typeMap), - directives: sortByName(schemaConfig.directives).map(sortDirective), - query: replaceMaybeType(schemaConfig.query), - mutation: replaceMaybeType(schemaConfig.mutation), - subscription: replaceMaybeType(schemaConfig.subscription), - }); + // Assigns trailers to the response object. + res.trailers = trailers; + res.rawTrailers = rawTrailers; + })); - function replaceType(type) { - if ((0, _definition.isListType)(type)) { - // @ts-expect-error - return new _definition.GraphQLList(replaceType(type.ofType)); - } else if ((0, _definition.isNonNullType)(type)) { - // @ts-expect-error - return new _definition.GraphQLNonNull(replaceType(type.ofType)); - } // @ts-expect-error FIXME: TS Conversion + const {socket} = stream.session; + this.socket = socket; + this.connection = socket; - return replaceNamedType(type); - } + for (const job of this[kJobs]) { + job(); + } - function replaceNamedType(type) { - return typeMap[type.name]; - } + this.emit('socket', this.socket); + }; - function replaceMaybeType(maybeType) { - return maybeType && replaceNamedType(maybeType); - } + // Makes a HTTP2 request + if (this[kSession]) { + try { + onStream(this[kSession].request(this[kHeaders])); + } catch (error) { + this.emit('error', error); + } + } else { + this.reusedSocket = true; - function sortDirective(directive) { - const config = directive.toConfig(); - return new _directives.GraphQLDirective({ - ...config, - locations: sortBy(config.locations, (x) => x), - args: sortArgs(config.args), - }); - } + try { + onStream(await this.agent.request(this[kOrigin], this[kOptions], this[kHeaders])); + } catch (error) { + this.emit('error', error); + } + } + } - function sortArgs(args) { - return sortObjMap(args, (arg) => ({ ...arg, type: replaceType(arg.type) })); - } + getHeader(name) { + if (typeof name !== 'string') { + throw new ERR_INVALID_ARG_TYPE('name', 'string', name); + } - function sortFields(fieldsMap) { - return sortObjMap(fieldsMap, (field) => ({ - ...field, - type: replaceType(field.type), - args: field.args && sortArgs(field.args), - })); - } + return this[kHeaders][name.toLowerCase()]; + } - function sortInputFields(fieldsMap) { - return sortObjMap(fieldsMap, (field) => ({ - ...field, - type: replaceType(field.type), - })); - } + get headersSent() { + return this[kFlushedHeaders]; + } - function sortTypes(array) { - return sortByName(array).map(replaceNamedType); - } + removeHeader(name) { + if (typeof name !== 'string') { + throw new ERR_INVALID_ARG_TYPE('name', 'string', name); + } - function sortNamedType(type) { - if ( - (0, _definition.isScalarType)(type) || - (0, _introspection.isIntrospectionType)(type) - ) { - return type; - } + if (this.headersSent) { + throw new ERR_HTTP_HEADERS_SENT('remove'); + } - if ((0, _definition.isObjectType)(type)) { - const config = type.toConfig(); - return new _definition.GraphQLObjectType({ - ...config, - interfaces: () => sortTypes(config.interfaces), - fields: () => sortFields(config.fields), - }); - } + delete this[kHeaders][name.toLowerCase()]; + } - if ((0, _definition.isInterfaceType)(type)) { - const config = type.toConfig(); - return new _definition.GraphQLInterfaceType({ - ...config, - interfaces: () => sortTypes(config.interfaces), - fields: () => sortFields(config.fields), - }); - } + setHeader(name, value) { + if (this.headersSent) { + throw new ERR_HTTP_HEADERS_SENT('set'); + } - if ((0, _definition.isUnionType)(type)) { - const config = type.toConfig(); - return new _definition.GraphQLUnionType({ - ...config, - types: () => sortTypes(config.types), - }); - } + if (typeof name !== 'string' || (!isValidHttpToken.test(name) && !isRequestPseudoHeader(name))) { + throw new ERR_INVALID_HTTP_TOKEN('Header name', name); + } - if ((0, _definition.isEnumType)(type)) { - const config = type.toConfig(); - return new _definition.GraphQLEnumType({ - ...config, - values: sortObjMap(config.values, (value) => value), - }); - } + if (typeof value === 'undefined') { + throw new ERR_HTTP_INVALID_HEADER_VALUE(value, name); + } - if ((0, _definition.isInputObjectType)(type)) { - const config = type.toConfig(); - return new _definition.GraphQLInputObjectType({ - ...config, - fields: () => sortInputFields(config.fields), - }); - } - /* c8 ignore next 3 */ - // Not reachable, all possible types have been considered. + if (isInvalidHeaderValue.test(value)) { + throw new ERR_INVALID_CHAR('header content', name); + } - false || - (0, _invariant.invariant)( - false, - 'Unexpected type: ' + (0, _inspect.inspect)(type), - ); - } -} + this[kHeaders][name.toLowerCase()] = value; + } -function sortObjMap(map, sortValueFn) { - const sortedMap = Object.create(null); + setNoDelay() { + // HTTP2 sockets cannot be malformed, do nothing. + } - for (const key of Object.keys(map).sort(_naturalCompare.naturalCompare)) { - sortedMap[key] = sortValueFn(map[key]); - } + setSocketKeepAlive() { + // HTTP2 sockets cannot be malformed, do nothing. + } - return sortedMap; -} + setTimeout(ms, callback) { + const applyTimeout = () => this._request.setTimeout(ms, callback); -function sortByName(array) { - return sortBy(array, (obj) => obj.name); -} + if (this._request) { + applyTimeout(); + } else { + this[kJobs].push(applyTimeout); + } -function sortBy(array, mapToKey) { - return array.slice().sort((obj1, obj2) => { - const key1 = mapToKey(obj1); - const key2 = mapToKey(obj2); - return (0, _naturalCompare.naturalCompare)(key1, key2); - }); -} + return this; + } + get maxHeadersCount() { + if (!this.destroyed && this._request) { + return this._request.session.localSettings.maxHeaderListSize; + } -/***/ }), + return undefined; + } -/***/ 84166: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + set maxHeadersCount(_value) { + // Updating HTTP2 settings would affect all requests, do nothing. + } +} -"use strict"; +module.exports = ClientRequest; -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.printIntrospectionSchema = printIntrospectionSchema; -exports.printSchema = printSchema; -exports.printType = printType; +/***/ }), -var _inspect = __nccwpck_require__(10102); +/***/ 82575: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var _invariant = __nccwpck_require__(28847); +"use strict"; -var _blockString = __nccwpck_require__(52671); +const {Readable} = __nccwpck_require__(12781); -var _kinds = __nccwpck_require__(11927); +class IncomingMessage extends Readable { + constructor(socket, highWaterMark) { + super({ + highWaterMark, + autoDestroy: false + }); -var _printer = __nccwpck_require__(68203); + this.statusCode = null; + this.statusMessage = ''; + this.httpVersion = '2.0'; + this.httpVersionMajor = 2; + this.httpVersionMinor = 0; + this.headers = {}; + this.trailers = {}; + this.req = null; -var _definition = __nccwpck_require__(32150); + this.aborted = false; + this.complete = false; + this.upgrade = null; -var _directives = __nccwpck_require__(83614); + this.rawHeaders = []; + this.rawTrailers = []; -var _introspection = __nccwpck_require__(28344); + this.socket = socket; + this.connection = socket; -var _scalars = __nccwpck_require__(93145); + this._dumped = false; + } -var _astFromValue = __nccwpck_require__(12653); + _destroy(error) { + this.req._request.destroy(error); + } -function printSchema(schema) { - return printFilteredSchema( - schema, - (n) => !(0, _directives.isSpecifiedDirective)(n), - isDefinedType, - ); -} + setTimeout(ms, callback) { + this.req.setTimeout(ms, callback); + return this; + } -function printIntrospectionSchema(schema) { - return printFilteredSchema( - schema, - _directives.isSpecifiedDirective, - _introspection.isIntrospectionType, - ); -} + _dump() { + if (!this._dumped) { + this._dumped = true; -function isDefinedType(type) { - return ( - !(0, _scalars.isSpecifiedScalarType)(type) && - !(0, _introspection.isIntrospectionType)(type) - ); -} + this.removeAllListeners('data'); + this.resume(); + } + } -function printFilteredSchema(schema, directiveFilter, typeFilter) { - const directives = schema.getDirectives().filter(directiveFilter); - const types = Object.values(schema.getTypeMap()).filter(typeFilter); - return [ - printSchemaDefinition(schema), - ...directives.map((directive) => printDirective(directive)), - ...types.map((type) => printType(type)), - ] - .filter(Boolean) - .join('\n\n'); + _read() { + if (this.req) { + this.req._request.resume(); + } + } } -function printSchemaDefinition(schema) { - if (schema.description == null && isSchemaOfCommonNames(schema)) { - return; - } +module.exports = IncomingMessage; - const operationTypes = []; - const queryType = schema.getQueryType(); - if (queryType) { - operationTypes.push(` query: ${queryType.name}`); - } +/***/ }), - const mutationType = schema.getMutationType(); +/***/ 54645: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (mutationType) { - operationTypes.push(` mutation: ${mutationType.name}`); - } +"use strict"; - const subscriptionType = schema.getSubscriptionType(); +const http2 = __nccwpck_require__(85158); +const agent = __nccwpck_require__(79898); +const ClientRequest = __nccwpck_require__(59632); +const IncomingMessage = __nccwpck_require__(82575); +const auto = __nccwpck_require__(97167); - if (subscriptionType) { - operationTypes.push(` subscription: ${subscriptionType.name}`); - } +const request = (url, options, callback) => { + return new ClientRequest(url, options, callback); +}; - return printDescription(schema) + `schema {\n${operationTypes.join('\n')}\n}`; -} -/** - * GraphQL schema define root types for each type of operation. These types are - * the same as any other type and can be named in any manner, however there is - * a common naming convention: - * - * ```graphql - * schema { - * query: Query - * mutation: Mutation - * subscription: Subscription - * } - * ``` - * - * When using this naming convention, the schema description can be omitted. - */ +const get = (url, options, callback) => { + // eslint-disable-next-line unicorn/prevent-abbreviations + const req = new ClientRequest(url, options, callback); + req.end(); -function isSchemaOfCommonNames(schema) { - const queryType = schema.getQueryType(); + return req; +}; - if (queryType && queryType.name !== 'Query') { - return false; - } +module.exports = { + ...http2, + ClientRequest, + IncomingMessage, + ...agent, + request, + get, + auto +}; - const mutationType = schema.getMutationType(); - if (mutationType && mutationType.name !== 'Mutation') { - return false; - } +/***/ }), - const subscriptionType = schema.getSubscriptionType(); +/***/ 51982: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (subscriptionType && subscriptionType.name !== 'Subscription') { - return false; - } +"use strict"; - return true; -} +const net = __nccwpck_require__(41808); +/* istanbul ignore file: https://github.com/nodejs/node/blob/v13.0.1/lib/_http_agent.js */ -function printType(type) { - if ((0, _definition.isScalarType)(type)) { - return printScalar(type); - } +module.exports = options => { + let servername = options.host; + const hostHeader = options.headers && options.headers.host; - if ((0, _definition.isObjectType)(type)) { - return printObject(type); - } + if (hostHeader) { + if (hostHeader.startsWith('[')) { + const index = hostHeader.indexOf(']'); + if (index === -1) { + servername = hostHeader; + } else { + servername = hostHeader.slice(1, -1); + } + } else { + servername = hostHeader.split(':', 1)[0]; + } + } - if ((0, _definition.isInterfaceType)(type)) { - return printInterface(type); - } + if (net.isIP(servername)) { + return ''; + } - if ((0, _definition.isUnionType)(type)) { - return printUnion(type); - } + return servername; +}; - if ((0, _definition.isEnumType)(type)) { - return printEnum(type); - } - if ((0, _definition.isInputObjectType)(type)) { - return printInputObject(type); - } - /* c8 ignore next 3 */ - // Not reachable, all possible types have been considered. +/***/ }), - false || - (0, _invariant.invariant)( - false, - 'Unexpected type: ' + (0, _inspect.inspect)(type), - ); -} +/***/ 7087: +/***/ ((module) => { -function printScalar(type) { - return ( - printDescription(type) + `scalar ${type.name}` + printSpecifiedByURL(type) - ); -} +"use strict"; -function printImplementedInterfaces(type) { - const interfaces = type.getInterfaces(); - return interfaces.length - ? ' implements ' + interfaces.map((i) => i.name).join(' & ') - : ''; -} +/* istanbul ignore file: https://github.com/nodejs/node/blob/master/lib/internal/errors.js */ -function printObject(type) { - return ( - printDescription(type) + - `type ${type.name}` + - printImplementedInterfaces(type) + - printFields(type) - ); -} +const makeError = (Base, key, getMessage) => { + module.exports[key] = class NodeError extends Base { + constructor(...args) { + super(typeof getMessage === 'string' ? getMessage : getMessage(args)); + this.name = `${super.name} [${key}]`; + this.code = key; + } + }; +}; -function printInterface(type) { - return ( - printDescription(type) + - `interface ${type.name}` + - printImplementedInterfaces(type) + - printFields(type) - ); -} +makeError(TypeError, 'ERR_INVALID_ARG_TYPE', args => { + const type = args[0].includes('.') ? 'property' : 'argument'; -function printUnion(type) { - const types = type.getTypes(); - const possibleTypes = types.length ? ' = ' + types.join(' | ') : ''; - return printDescription(type) + 'union ' + type.name + possibleTypes; -} + let valid = args[1]; + const isManyTypes = Array.isArray(valid); -function printEnum(type) { - const values = type - .getValues() - .map( - (value, i) => - printDescription(value, ' ', !i) + - ' ' + - value.name + - printDeprecated(value.deprecationReason), - ); - return printDescription(type) + `enum ${type.name}` + printBlock(values); -} + if (isManyTypes) { + valid = `${valid.slice(0, -1).join(', ')} or ${valid.slice(-1)}`; + } -function printInputObject(type) { - const fields = Object.values(type.getFields()).map( - (f, i) => printDescription(f, ' ', !i) + ' ' + printInputValue(f), - ); - return ( - printDescription(type) + - `input ${type.name}` + - (type.isOneOf ? ' @oneOf' : '') + - printBlock(fields) - ); -} + return `The "${args[0]}" ${type} must be ${isManyTypes ? 'one of' : 'of'} type ${valid}. Received ${typeof args[2]}`; +}); -function printFields(type) { - const fields = Object.values(type.getFields()).map( - (f, i) => - printDescription(f, ' ', !i) + - ' ' + - f.name + - printArgs(f.args, ' ') + - ': ' + - String(f.type) + - printDeprecated(f.deprecationReason), - ); - return printBlock(fields); -} +makeError(TypeError, 'ERR_INVALID_PROTOCOL', args => { + return `Protocol "${args[0]}" not supported. Expected "${args[1]}"`; +}); -function printBlock(items) { - return items.length !== 0 ? ' {\n' + items.join('\n') + '\n}' : ''; -} +makeError(Error, 'ERR_HTTP_HEADERS_SENT', args => { + return `Cannot ${args[0]} headers after they are sent to the client`; +}); -function printArgs(args, indentation = '') { - if (args.length === 0) { - return ''; - } // If every arg does not have a description, print them on one line. +makeError(TypeError, 'ERR_INVALID_HTTP_TOKEN', args => { + return `${args[0]} must be a valid HTTP token [${args[1]}]`; +}); - if (args.every((arg) => !arg.description)) { - return '(' + args.map(printInputValue).join(', ') + ')'; - } +makeError(TypeError, 'ERR_HTTP_INVALID_HEADER_VALUE', args => { + return `Invalid value "${args[0]} for header "${args[1]}"`; +}); - return ( - '(\n' + - args - .map( - (arg, i) => - printDescription(arg, ' ' + indentation, !i) + - ' ' + - indentation + - printInputValue(arg), - ) - .join('\n') + - '\n' + - indentation + - ')' - ); -} +makeError(TypeError, 'ERR_INVALID_CHAR', args => { + return `Invalid character in ${args[0]} [${args[1]}]`; +}); -function printInputValue(arg) { - const defaultAST = (0, _astFromValue.astFromValue)( - arg.defaultValue, - arg.type, - ); - let argDecl = arg.name + ': ' + String(arg.type); - if (defaultAST) { - argDecl += ` = ${(0, _printer.print)(defaultAST)}`; - } +/***/ }), - return argDecl + printDeprecated(arg.deprecationReason); -} +/***/ 11199: +/***/ ((module) => { -function printDirective(directive) { - return ( - printDescription(directive) + - 'directive @' + - directive.name + - printArgs(directive.args) + - (directive.isRepeatable ? ' repeatable' : '') + - ' on ' + - directive.locations.join(' | ') - ); -} +"use strict"; -function printDeprecated(reason) { - if (reason == null) { - return ''; - } - if (reason !== _directives.DEFAULT_DEPRECATION_REASON) { - const astValue = (0, _printer.print)({ - kind: _kinds.Kind.STRING, - value: reason, - }); - return ` @deprecated(reason: ${astValue})`; - } +module.exports = header => { + switch (header) { + case ':method': + case ':scheme': + case ':authority': + case ':path': + return true; + default: + return false; + } +}; - return ' @deprecated'; -} -function printSpecifiedByURL(scalar) { - if (scalar.specifiedByURL == null) { - return ''; - } +/***/ }), - const astValue = (0, _printer.print)({ - kind: _kinds.Kind.STRING, - value: scalar.specifiedByURL, - }); - return ` @specifiedBy(url: ${astValue})`; -} +/***/ 81818: +/***/ ((module) => { -function printDescription(def, indentation = '', firstInBlock = true) { - const { description } = def; +"use strict"; - if (description == null) { - return ''; - } - const blockString = (0, _printer.print)({ - kind: _kinds.Kind.STRING, - value: description, - block: (0, _blockString.isPrintableAsBlockString)(description), - }); - const prefix = - indentation && !firstInBlock ? '\n' + indentation : indentation; - return prefix + blockString.replace(/\n/g, '\n' + indentation) + '\n'; -} +module.exports = (from, to, events) => { + for (const event of events) { + from.on(event, (...args) => to.emit(event, ...args)); + } +}; /***/ }), -/***/ 29125: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 92686: +/***/ ((module) => { "use strict"; +/* istanbul ignore file: https://github.com/nodejs/node/blob/a91293d4d9ab403046ab5eb022332e4e3d249bd3/lib/internal/url.js#L1257 */ -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.separateOperations = separateOperations; - -var _kinds = __nccwpck_require__(11927); +module.exports = url => { + const options = { + protocol: url.protocol, + hostname: typeof url.hostname === 'string' && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname, + host: url.host, + hash: url.hash, + search: url.search, + pathname: url.pathname, + href: url.href, + path: `${url.pathname || ''}${url.search || ''}` + }; -var _visitor = __nccwpck_require__(5678); + if (typeof url.port === 'string' && url.port.length !== 0) { + options.port = Number(url.port); + } -/** - * separateOperations accepts a single AST document which may contain many - * operations and fragments and returns a collection of AST documents each of - * which contains a single operation as well the fragment definitions it - * refers to. - */ -function separateOperations(documentAST) { - const operations = []; - const depGraph = Object.create(null); // Populate metadata and build a dependency graph. + if (url.username || url.password) { + options.auth = `${url.username || ''}:${url.password || ''}`; + } - for (const definitionNode of documentAST.definitions) { - switch (definitionNode.kind) { - case _kinds.Kind.OPERATION_DEFINITION: - operations.push(definitionNode); - break; + return options; +}; - case _kinds.Kind.FRAGMENT_DEFINITION: - depGraph[definitionNode.name.value] = collectDependencies( - definitionNode.selectionSet, - ); - break; - default: // ignore non-executable definitions - } - } // For each operation, produce a new synthesized AST which includes only what - // is necessary for completing that operation. +/***/ }), - const separatedDocumentASTs = Object.create(null); +/***/ 28213: +/***/ ((__unused_webpack_module, exports) => { - for (const operation of operations) { - const dependencies = new Set(); +"use strict"; +Object.defineProperty(exports, "__esModule", ({value:true}));exports.SIGNALS=void 0; - for (const fragmentName of collectDependencies(operation.selectionSet)) { - collectTransitiveDependencies(dependencies, depGraph, fragmentName); - } // Provides the empty string for anonymous operations. +const SIGNALS=[ +{ +name:"SIGHUP", +number:1, +action:"terminate", +description:"Terminal closed", +standard:"posix"}, - const operationName = operation.name ? operation.name.value : ''; // The list of definition nodes to be included for this operation, sorted - // to retain the same order as the original document. +{ +name:"SIGINT", +number:2, +action:"terminate", +description:"User interruption with CTRL-C", +standard:"ansi"}, - separatedDocumentASTs[operationName] = { - kind: _kinds.Kind.DOCUMENT, - definitions: documentAST.definitions.filter( - (node) => - node === operation || - (node.kind === _kinds.Kind.FRAGMENT_DEFINITION && - dependencies.has(node.name.value)), - ), - }; - } +{ +name:"SIGQUIT", +number:3, +action:"core", +description:"User interruption with CTRL-\\", +standard:"posix"}, - return separatedDocumentASTs; -} +{ +name:"SIGILL", +number:4, +action:"core", +description:"Invalid machine instruction", +standard:"ansi"}, -// From a dependency graph, collects a list of transitive dependencies by -// recursing through a dependency graph. -function collectTransitiveDependencies(collected, depGraph, fromName) { - if (!collected.has(fromName)) { - collected.add(fromName); - const immediateDeps = depGraph[fromName]; +{ +name:"SIGTRAP", +number:5, +action:"core", +description:"Debugger breakpoint", +standard:"posix"}, - if (immediateDeps !== undefined) { - for (const toName of immediateDeps) { - collectTransitiveDependencies(collected, depGraph, toName); - } - } - } -} +{ +name:"SIGABRT", +number:6, +action:"core", +description:"Aborted", +standard:"ansi"}, -function collectDependencies(selectionSet) { - const dependencies = []; - (0, _visitor.visit)(selectionSet, { - FragmentSpread(node) { - dependencies.push(node.name.value); - }, - }); - return dependencies; -} +{ +name:"SIGIOT", +number:6, +action:"core", +description:"Aborted", +standard:"bsd"}, +{ +name:"SIGBUS", +number:7, +action:"core", +description: +"Bus error due to misaligned, non-existing address or paging error", +standard:"bsd"}, -/***/ }), +{ +name:"SIGEMT", +number:7, +action:"terminate", +description:"Command should be emulated but is not implemented", +standard:"other"}, -/***/ 82278: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +{ +name:"SIGFPE", +number:8, +action:"core", +description:"Floating point arithmetic error", +standard:"ansi"}, -"use strict"; +{ +name:"SIGKILL", +number:9, +action:"terminate", +description:"Forced termination", +standard:"posix", +forced:true}, +{ +name:"SIGUSR1", +number:10, +action:"terminate", +description:"Application-specific signal", +standard:"posix"}, -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.sortValueNode = sortValueNode; +{ +name:"SIGSEGV", +number:11, +action:"core", +description:"Segmentation fault", +standard:"ansi"}, -var _naturalCompare = __nccwpck_require__(20038); +{ +name:"SIGUSR2", +number:12, +action:"terminate", +description:"Application-specific signal", +standard:"posix"}, -var _kinds = __nccwpck_require__(11927); +{ +name:"SIGPIPE", +number:13, +action:"terminate", +description:"Broken pipe or socket", +standard:"posix"}, -/** - * Sort ValueNode. - * - * This function returns a sorted copy of the given ValueNode. - * - * @internal - */ -function sortValueNode(valueNode) { - switch (valueNode.kind) { - case _kinds.Kind.OBJECT: - return { ...valueNode, fields: sortFields(valueNode.fields) }; +{ +name:"SIGALRM", +number:14, +action:"terminate", +description:"Timeout or timer", +standard:"posix"}, - case _kinds.Kind.LIST: - return { ...valueNode, values: valueNode.values.map(sortValueNode) }; +{ +name:"SIGTERM", +number:15, +action:"terminate", +description:"Termination", +standard:"ansi"}, - case _kinds.Kind.INT: - case _kinds.Kind.FLOAT: - case _kinds.Kind.STRING: - case _kinds.Kind.BOOLEAN: - case _kinds.Kind.NULL: - case _kinds.Kind.ENUM: - case _kinds.Kind.VARIABLE: - return valueNode; - } -} +{ +name:"SIGSTKFLT", +number:16, +action:"terminate", +description:"Stack is empty or overflowed", +standard:"other"}, -function sortFields(fields) { - return fields - .map((fieldNode) => ({ - ...fieldNode, - value: sortValueNode(fieldNode.value), - })) - .sort((fieldA, fieldB) => - (0, _naturalCompare.naturalCompare)(fieldA.name.value, fieldB.name.value), - ); -} +{ +name:"SIGCHLD", +number:17, +action:"ignore", +description:"Child process terminated, paused or unpaused", +standard:"posix"}, +{ +name:"SIGCLD", +number:17, +action:"ignore", +description:"Child process terminated, paused or unpaused", +standard:"other"}, -/***/ }), +{ +name:"SIGCONT", +number:18, +action:"unpause", +description:"Unpaused", +standard:"posix", +forced:true}, -/***/ 17766: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +{ +name:"SIGSTOP", +number:19, +action:"pause", +description:"Paused", +standard:"posix", +forced:true}, -"use strict"; +{ +name:"SIGTSTP", +number:20, +action:"pause", +description:"Paused using CTRL-Z or \"suspend\"", +standard:"posix"}, +{ +name:"SIGTTIN", +number:21, +action:"pause", +description:"Background process cannot read terminal input", +standard:"posix"}, -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.stripIgnoredCharacters = stripIgnoredCharacters; +{ +name:"SIGBREAK", +number:21, +action:"terminate", +description:"User interruption with CTRL-BREAK", +standard:"other"}, -var _blockString = __nccwpck_require__(52671); +{ +name:"SIGTTOU", +number:22, +action:"pause", +description:"Background process cannot write to terminal output", +standard:"posix"}, -var _lexer = __nccwpck_require__(24605); +{ +name:"SIGURG", +number:23, +action:"ignore", +description:"Socket received out-of-band data", +standard:"bsd"}, -var _source = __nccwpck_require__(65521); +{ +name:"SIGXCPU", +number:24, +action:"core", +description:"Process timed out", +standard:"bsd"}, -var _tokenKind = __nccwpck_require__(91565); +{ +name:"SIGXFSZ", +number:25, +action:"core", +description:"File too big", +standard:"bsd"}, -/** - * Strips characters that are not significant to the validity or execution - * of a GraphQL document: - * - UnicodeBOM - * - WhiteSpace - * - LineTerminator - * - Comment - * - Comma - * - BlockString indentation - * - * Note: It is required to have a delimiter character between neighboring - * non-punctuator tokens and this function always uses single space as delimiter. - * - * It is guaranteed that both input and output documents if parsed would result - * in the exact same AST except for nodes location. - * - * Warning: It is guaranteed that this function will always produce stable results. - * However, it's not guaranteed that it will stay the same between different - * releases due to bugfixes or changes in the GraphQL specification. - * - * Query example: - * - * ```graphql - * query SomeQuery($foo: String!, $bar: String) { - * someField(foo: $foo, bar: $bar) { - * a - * b { - * c - * d - * } - * } - * } - * ``` - * - * Becomes: - * - * ```graphql - * query SomeQuery($foo:String!$bar:String){someField(foo:$foo bar:$bar){a b{c d}}} - * ``` - * - * SDL example: - * - * ```graphql - * """ - * Type description - * """ - * type Foo { - * """ - * Field description - * """ - * bar: String - * } - * ``` - * - * Becomes: - * - * ```graphql - * """Type description""" type Foo{"""Field description""" bar:String} - * ``` - */ -function stripIgnoredCharacters(source) { - const sourceObj = (0, _source.isSource)(source) - ? source - : new _source.Source(source); - const body = sourceObj.body; - const lexer = new _lexer.Lexer(sourceObj); - let strippedBody = ''; - let wasLastAddedTokenNonPunctuator = false; +{ +name:"SIGVTALRM", +number:26, +action:"terminate", +description:"Timeout or timer", +standard:"bsd"}, - while (lexer.advance().kind !== _tokenKind.TokenKind.EOF) { - const currentToken = lexer.token; - const tokenKind = currentToken.kind; - /** - * Every two non-punctuator tokens should have space between them. - * Also prevent case of non-punctuator token following by spread resulting - * in invalid token (e.g. `1...` is invalid Float token). - */ +{ +name:"SIGPROF", +number:27, +action:"terminate", +description:"Timeout or timer", +standard:"bsd"}, - const isNonPunctuator = !(0, _lexer.isPunctuatorTokenKind)( - currentToken.kind, - ); +{ +name:"SIGWINCH", +number:28, +action:"ignore", +description:"Terminal window size changed", +standard:"bsd"}, - if (wasLastAddedTokenNonPunctuator) { - if ( - isNonPunctuator || - currentToken.kind === _tokenKind.TokenKind.SPREAD - ) { - strippedBody += ' '; - } - } +{ +name:"SIGIO", +number:29, +action:"terminate", +description:"I/O is available", +standard:"other"}, - const tokenBody = body.slice(currentToken.start, currentToken.end); +{ +name:"SIGPOLL", +number:29, +action:"terminate", +description:"Watched event", +standard:"other"}, - if (tokenKind === _tokenKind.TokenKind.BLOCK_STRING) { - strippedBody += (0, _blockString.printBlockString)(currentToken.value, { - minimize: true, - }); - } else { - strippedBody += tokenBody; - } +{ +name:"SIGINFO", +number:29, +action:"ignore", +description:"Request for process information", +standard:"other"}, - wasLastAddedTokenNonPunctuator = isNonPunctuator; - } +{ +name:"SIGPWR", +number:30, +action:"terminate", +description:"Device running out of power", +standard:"systemv"}, - return strippedBody; -} +{ +name:"SIGSYS", +number:31, +action:"core", +description:"Invalid system call", +standard:"other"}, +{ +name:"SIGUNUSED", +number:31, +action:"terminate", +description:"Invalid system call", +standard:"other"}];exports.SIGNALS=SIGNALS; +//# sourceMappingURL=core.js.map /***/ }), -/***/ 10333: +/***/ 2779: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +Object.defineProperty(exports, "__esModule", ({value:true}));exports.signalsByNumber=exports.signalsByName=void 0;var _os=__nccwpck_require__(22037); +var _signals=__nccwpck_require__(86435); +var _realtime=__nccwpck_require__(25295); -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.doTypesOverlap = doTypesOverlap; -exports.isEqualType = isEqualType; -exports.isTypeSubTypeOf = isTypeSubTypeOf; - -var _definition = __nccwpck_require__(32150); -/** - * Provided two types, return true if the types are equal (invariant). - */ -function isEqualType(typeA, typeB) { - // Equivalent types are equal. - if (typeA === typeB) { - return true; - } // If either type is non-null, the other must also be non-null. - if ( - (0, _definition.isNonNullType)(typeA) && - (0, _definition.isNonNullType)(typeB) - ) { - return isEqualType(typeA.ofType, typeB.ofType); - } // If either type is a list, the other must also be a list. +const getSignalsByName=function(){ +const signals=(0,_signals.getSignals)(); +return signals.reduce(getSignalByName,{}); +}; - if ( - (0, _definition.isListType)(typeA) && - (0, _definition.isListType)(typeB) - ) { - return isEqualType(typeA.ofType, typeB.ofType); - } // Otherwise the types are not equal. +const getSignalByName=function( +signalByNameMemo, +{name,number,description,supported,action,forced,standard}) +{ +return{ +...signalByNameMemo, +[name]:{name,number,description,supported,action,forced,standard}}; - return false; -} -/** - * Provided a type and a super type, return true if the first type is either - * equal or a subset of the second super type (covariant). - */ +}; -function isTypeSubTypeOf(schema, maybeSubType, superType) { - // Equivalent type is a valid subtype - if (maybeSubType === superType) { - return true; - } // If superType is non-null, maybeSubType must also be non-null. +const signalsByName=getSignalsByName();exports.signalsByName=signalsByName; - if ((0, _definition.isNonNullType)(superType)) { - if ((0, _definition.isNonNullType)(maybeSubType)) { - return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); - } - return false; - } - if ((0, _definition.isNonNullType)(maybeSubType)) { - // If superType is nullable, maybeSubType may be non-null or nullable. - return isTypeSubTypeOf(schema, maybeSubType.ofType, superType); - } // If superType type is a list, maybeSubType type must also be a list. - if ((0, _definition.isListType)(superType)) { - if ((0, _definition.isListType)(maybeSubType)) { - return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); - } +const getSignalsByNumber=function(){ +const signals=(0,_signals.getSignals)(); +const length=_realtime.SIGRTMAX+1; +const signalsA=Array.from({length},(value,number)=> +getSignalByNumber(number,signals)); - return false; - } +return Object.assign({},...signalsA); +}; - if ((0, _definition.isListType)(maybeSubType)) { - // If superType is not a list, maybeSubType must also be not a list. - return false; - } // If superType type is an abstract type, check if it is super type of maybeSubType. - // Otherwise, the child type is not a valid subtype of the parent type. +const getSignalByNumber=function(number,signals){ +const signal=findSignalByNumber(number,signals); - return ( - (0, _definition.isAbstractType)(superType) && - ((0, _definition.isInterfaceType)(maybeSubType) || - (0, _definition.isObjectType)(maybeSubType)) && - schema.isSubType(superType, maybeSubType) - ); +if(signal===undefined){ +return{}; } -/** - * Provided two composite types, determine if they "overlap". Two composite - * types overlap when the Sets of possible concrete types for each intersect. - * - * This is often used to determine if a fragment of a given type could possibly - * be visited in a context of another type. - * - * This function is commutative. - */ - -function doTypesOverlap(schema, typeA, typeB) { - // Equivalent types overlap - if (typeA === typeB) { - return true; - } - - if ((0, _definition.isAbstractType)(typeA)) { - if ((0, _definition.isAbstractType)(typeB)) { - // If both types are abstract, then determine if there is any intersection - // between possible concrete types of each. - return schema - .getPossibleTypes(typeA) - .some((type) => schema.isSubType(typeB, type)); - } // Determine if the latter type is a possible concrete type of the former. - return schema.isSubType(typeA, typeB); - } +const{name,description,supported,action,forced,standard}=signal; +return{ +[number]:{ +name, +number, +description, +supported, +action, +forced, +standard}}; - if ((0, _definition.isAbstractType)(typeB)) { - // Determine if the former type is a possible concrete type of the latter. - return schema.isSubType(typeB, typeA); - } // Otherwise the types do not overlap. - return false; -} +}; -/***/ }), -/***/ 27664: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +const findSignalByNumber=function(number,signals){ +const signal=signals.find(({name})=>_os.constants.signals[name]===number); -"use strict"; +if(signal!==undefined){ +return signal; +} +return signals.find(signalA=>signalA.number===number); +}; -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.typeFromAST = typeFromAST; +const signalsByNumber=getSignalsByNumber();exports.signalsByNumber=signalsByNumber; +//# sourceMappingURL=main.js.map -var _kinds = __nccwpck_require__(11927); +/***/ }), -var _definition = __nccwpck_require__(32150); +/***/ 25295: +/***/ ((__unused_webpack_module, exports) => { -function typeFromAST(schema, typeNode) { - switch (typeNode.kind) { - case _kinds.Kind.LIST_TYPE: { - const innerType = typeFromAST(schema, typeNode.type); - return innerType && new _definition.GraphQLList(innerType); - } +"use strict"; +Object.defineProperty(exports, "__esModule", ({value:true}));exports.SIGRTMAX=exports.getRealtimeSignals=void 0; +const getRealtimeSignals=function(){ +const length=SIGRTMAX-SIGRTMIN+1; +return Array.from({length},getRealtimeSignal); +};exports.getRealtimeSignals=getRealtimeSignals; - case _kinds.Kind.NON_NULL_TYPE: { - const innerType = typeFromAST(schema, typeNode.type); - return innerType && new _definition.GraphQLNonNull(innerType); - } +const getRealtimeSignal=function(value,index){ +return{ +name:`SIGRT${index+1}`, +number:SIGRTMIN+index, +action:"terminate", +description:"Application-specific signal (realtime)", +standard:"posix"}; - case _kinds.Kind.NAMED_TYPE: - return schema.getType(typeNode.name.value); - } -} +}; +const SIGRTMIN=34; +const SIGRTMAX=64;exports.SIGRTMAX=SIGRTMAX; +//# sourceMappingURL=realtime.js.map /***/ }), -/***/ 83181: +/***/ 86435: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +Object.defineProperty(exports, "__esModule", ({value:true}));exports.getSignals=void 0;var _os=__nccwpck_require__(22037); +var _core=__nccwpck_require__(28213); +var _realtime=__nccwpck_require__(25295); -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.valueFromAST = valueFromAST; - -var _inspect = __nccwpck_require__(10102); -var _invariant = __nccwpck_require__(28847); -var _keyMap = __nccwpck_require__(10711); +const getSignals=function(){ +const realtimeSignals=(0,_realtime.getRealtimeSignals)(); +const signals=[..._core.SIGNALS,...realtimeSignals].map(normalizeSignal); +return signals; +};exports.getSignals=getSignals; -var _kinds = __nccwpck_require__(11927); -var _definition = __nccwpck_require__(32150); -/** - * Produces a JavaScript value given a GraphQL Value AST. - * - * A GraphQL type must be provided, which will be used to interpret different - * GraphQL Value literals. - * - * Returns `undefined` when the value could not be validly coerced according to - * the provided type. - * - * | GraphQL Value | JSON Value | - * | -------------------- | ------------- | - * | Input Object | Object | - * | List | Array | - * | Boolean | Boolean | - * | String | String | - * | Int / Float | Number | - * | Enum Value | Unknown | - * | NullValue | null | - * - */ -function valueFromAST(valueNode, type, variables) { - if (!valueNode) { - // When there is no node, then there is also no value. - // Importantly, this is different from returning the value null. - return; - } - if (valueNode.kind === _kinds.Kind.VARIABLE) { - const variableName = valueNode.name.value; - if (variables == null || variables[variableName] === undefined) { - // No valid return value. - return; - } - const variableValue = variables[variableName]; - if (variableValue === null && (0, _definition.isNonNullType)(type)) { - return; // Invalid: intentionally return no value. - } // Note: This does no further checking that this variable is correct. - // This assumes that this query has been validated and the variable - // usage here is of the correct type. +const normalizeSignal=function({ +name, +number:defaultNumber, +description, +action, +forced=false, +standard}) +{ +const{ +signals:{[name]:constantSignal}}= +_os.constants; +const supported=constantSignal!==undefined; +const number=supported?constantSignal:defaultNumber; +return{name,number,description,supported,action,forced,standard}; +}; +//# sourceMappingURL=signals.js.map - return variableValue; - } +/***/ }), - if ((0, _definition.isNonNullType)(type)) { - if (valueNode.kind === _kinds.Kind.NULL) { - return; // Invalid: intentionally return no value. - } +/***/ 98043: +/***/ ((module) => { - return valueFromAST(valueNode, type.ofType, variables); - } +"use strict"; - if (valueNode.kind === _kinds.Kind.NULL) { - // This is explicitly returning the value null. - return null; - } - if ((0, _definition.isListType)(type)) { - const itemType = type.ofType; +module.exports = (string, count = 1, options) => { + options = { + indent: ' ', + includeEmptyLines: false, + ...options + }; - if (valueNode.kind === _kinds.Kind.LIST) { - const coercedValues = []; + if (typeof string !== 'string') { + throw new TypeError( + `Expected \`input\` to be a \`string\`, got \`${typeof string}\`` + ); + } - for (const itemNode of valueNode.values) { - if (isMissingVariable(itemNode, variables)) { - // If an array contains a missing variable, it is either coerced to - // null or if the item type is non-null, it considered invalid. - if ((0, _definition.isNonNullType)(itemType)) { - return; // Invalid: intentionally return no value. - } + if (typeof count !== 'number') { + throw new TypeError( + `Expected \`count\` to be a \`number\`, got \`${typeof count}\`` + ); + } - coercedValues.push(null); - } else { - const itemValue = valueFromAST(itemNode, itemType, variables); + if (typeof options.indent !== 'string') { + throw new TypeError( + `Expected \`options.indent\` to be a \`string\`, got \`${typeof options.indent}\`` + ); + } - if (itemValue === undefined) { - return; // Invalid: intentionally return no value. - } + if (count === 0) { + return string; + } - coercedValues.push(itemValue); - } - } + const regex = options.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm; - return coercedValues; - } + return string.replace(regex, options.indent.repeat(count)); +}; - const coercedValue = valueFromAST(valueNode, itemType, variables); - if (coercedValue === undefined) { - return; // Invalid: intentionally return no value. - } +/***/ }), - return [coercedValue]; - } +/***/ 52492: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if ((0, _definition.isInputObjectType)(type)) { - if (valueNode.kind !== _kinds.Kind.OBJECT) { - return; // Invalid: intentionally return no value. - } +var wrappy = __nccwpck_require__(62940) +var reqs = Object.create(null) +var once = __nccwpck_require__(1223) - const coercedObj = Object.create(null); - const fieldNodes = (0, _keyMap.keyMap)( - valueNode.fields, - (field) => field.name.value, - ); +module.exports = wrappy(inflight) - for (const field of Object.values(type.getFields())) { - const fieldNode = fieldNodes[field.name]; +function inflight (key, cb) { + if (reqs[key]) { + reqs[key].push(cb) + return null + } else { + reqs[key] = [cb] + return makeres(key) + } +} - if (!fieldNode || isMissingVariable(fieldNode.value, variables)) { - if (field.defaultValue !== undefined) { - coercedObj[field.name] = field.defaultValue; - } else if ((0, _definition.isNonNullType)(field.type)) { - return; // Invalid: intentionally return no value. - } +function makeres (key) { + return once(function RES () { + var cbs = reqs[key] + var len = cbs.length + var args = slice(arguments) - continue; + // XXX It's somewhat ambiguous whether a new callback added in this + // pass should be queued for later execution if something in the + // list of callbacks throws, or if it should just be discarded. + // However, it's such an edge case that it hardly matters, and either + // choice is likely as surprising as the other. + // As it happens, we do go ahead and schedule it for later execution. + try { + for (var i = 0; i < len; i++) { + cbs[i].apply(null, args) } - - const fieldValue = valueFromAST(fieldNode.value, field.type, variables); - - if (fieldValue === undefined) { - return; // Invalid: intentionally return no value. + } finally { + if (cbs.length > len) { + // added more in the interim. + // de-zalgo, just in case, but don't call again. + cbs.splice(0, len) + process.nextTick(function () { + RES.apply(null, args) + }) + } else { + delete reqs[key] } - - coercedObj[field.name] = fieldValue; } + }) +} - if (type.isOneOf) { - const keys = Object.keys(coercedObj); +function slice (args) { + var length = args.length + var array = [] - if (keys.length !== 1) { - return; // Invalid: not exactly one key, intentionally return no value. - } + for (var i = 0; i < length; i++) array[i] = args[i] + return array +} - if (coercedObj[keys[0]] === null) { - return; // Invalid: value not non-null, intentionally return no value. - } - } - return coercedObj; - } +/***/ }), - if ((0, _definition.isLeafType)(type)) { - // Scalars and Enums fulfill parsing a literal value via parseLiteral(). - // Invalid values represent a failure to parse correctly, in which case - // no value is returned. - let result; +/***/ 44124: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - try { - result = type.parseLiteral(valueNode, variables); - } catch (_error) { - return; // Invalid: intentionally return no value. - } +try { + var util = __nccwpck_require__(73837); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = __nccwpck_require__(8544); +} - if (result === undefined) { - return; // Invalid: intentionally return no value. - } - return result; - } - /* c8 ignore next 3 */ - // Not reachable, all possible input types have been considered. +/***/ }), - false || - (0, _invariant.invariant)( - false, - 'Unexpected input type: ' + (0, _inspect.inspect)(type), - ); -} // Returns true if the provided valueNode is a variable which is not defined -// in the set of variables. +/***/ 8544: +/***/ ((module) => { -function isMissingVariable(valueNode, variables) { - return ( - valueNode.kind === _kinds.Kind.VARIABLE && - (variables == null || variables[valueNode.name.value] === undefined) - ); +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } } /***/ }), -/***/ 86699: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 41554: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.valueFromASTUntyped = valueFromASTUntyped; - -var _keyValMap = __nccwpck_require__(49268); - -var _kinds = __nccwpck_require__(11927); - -/** - * Produces a JavaScript value given a GraphQL Value AST. - * - * Unlike `valueFromAST()`, no type is provided. The resulting JavaScript value - * will reflect the provided GraphQL value AST. - * - * | GraphQL Value | JavaScript Value | - * | -------------------- | ---------------- | - * | Input Object | Object | - * | List | Array | - * | Boolean | Boolean | - * | String / Enum | String | - * | Int / Float | Number | - * | Null | null | - * - */ -function valueFromASTUntyped(valueNode, variables) { - switch (valueNode.kind) { - case _kinds.Kind.NULL: - return null; - - case _kinds.Kind.INT: - return parseInt(valueNode.value, 10); +const isStream = stream => + stream !== null && + typeof stream === 'object' && + typeof stream.pipe === 'function'; - case _kinds.Kind.FLOAT: - return parseFloat(valueNode.value); +isStream.writable = stream => + isStream(stream) && + stream.writable !== false && + typeof stream._write === 'function' && + typeof stream._writableState === 'object'; - case _kinds.Kind.STRING: - case _kinds.Kind.ENUM: - case _kinds.Kind.BOOLEAN: - return valueNode.value; +isStream.readable = stream => + isStream(stream) && + stream.readable !== false && + typeof stream._read === 'function' && + typeof stream._readableState === 'object'; - case _kinds.Kind.LIST: - return valueNode.values.map((node) => - valueFromASTUntyped(node, variables), - ); +isStream.duplex = stream => + isStream.writable(stream) && + isStream.readable(stream); - case _kinds.Kind.OBJECT: - return (0, _keyValMap.keyValMap)( - valueNode.fields, - (field) => field.name.value, - (field) => valueFromASTUntyped(field.value, variables), - ); +isStream.transform = stream => + isStream.duplex(stream) && + typeof stream._transform === 'function'; - case _kinds.Kind.VARIABLE: - return variables === null || variables === void 0 - ? void 0 - : variables[valueNode.name.value]; - } -} +module.exports = isStream; /***/ }), -/***/ 28263: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.ValidationContext = - exports.SDLValidationContext = - exports.ASTValidationContext = - void 0; - -var _kinds = __nccwpck_require__(11927); +/***/ 10657: +/***/ ((module) => { -var _visitor = __nccwpck_require__(5678); +module.exports = isTypedArray +isTypedArray.strict = isStrictTypedArray +isTypedArray.loose = isLooseTypedArray -var _TypeInfo = __nccwpck_require__(76625); +var toString = Object.prototype.toString +var names = { + '[object Int8Array]': true + , '[object Int16Array]': true + , '[object Int32Array]': true + , '[object Uint8Array]': true + , '[object Uint8ClampedArray]': true + , '[object Uint16Array]': true + , '[object Uint32Array]': true + , '[object Float32Array]': true + , '[object Float64Array]': true +} -/** - * An instance of this class is passed as the "this" context to all validators, - * allowing access to commonly useful contextual information from within a - * validation rule. - */ -class ASTValidationContext { - constructor(ast, onError) { - this._ast = ast; - this._fragments = undefined; - this._fragmentSpreads = new Map(); - this._recursivelyReferencedFragments = new Map(); - this._onError = onError; - } +function isTypedArray(arr) { + return ( + isStrictTypedArray(arr) + || isLooseTypedArray(arr) + ) +} - get [Symbol.toStringTag]() { - return 'ASTValidationContext'; - } +function isStrictTypedArray(arr) { + return ( + arr instanceof Int8Array + || arr instanceof Int16Array + || arr instanceof Int32Array + || arr instanceof Uint8Array + || arr instanceof Uint8ClampedArray + || arr instanceof Uint16Array + || arr instanceof Uint32Array + || arr instanceof Float32Array + || arr instanceof Float64Array + ) +} - reportError(error) { - this._onError(error); - } +function isLooseTypedArray(arr) { + return names[toString.call(arr)] +} - getDocument() { - return this._ast; - } - getFragment(name) { - let fragments; +/***/ }), - if (this._fragments) { - fragments = this._fragments; - } else { - fragments = Object.create(null); +/***/ 97126: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - for (const defNode of this.getDocument().definitions) { - if (defNode.kind === _kinds.Kind.FRAGMENT_DEFINITION) { - fragments[defNode.name.value] = defNode; - } - } +var fs = __nccwpck_require__(57147) +var core +if (process.platform === 'win32' || global.TESTING_WINDOWS) { + core = __nccwpck_require__(42001) +} else { + core = __nccwpck_require__(9728) +} - this._fragments = fragments; - } +module.exports = isexe +isexe.sync = sync - return fragments[name]; +function isexe (path, options, cb) { + if (typeof options === 'function') { + cb = options + options = {} } - getFragmentSpreads(node) { - let spreads = this._fragmentSpreads.get(node); - - if (!spreads) { - spreads = []; - const setsToVisit = [node]; - let set; - - while ((set = setsToVisit.pop())) { - for (const selection of set.selections) { - if (selection.kind === _kinds.Kind.FRAGMENT_SPREAD) { - spreads.push(selection); - } else if (selection.selectionSet) { - setsToVisit.push(selection.selectionSet); - } - } - } - - this._fragmentSpreads.set(node, spreads); + if (!cb) { + if (typeof Promise !== 'function') { + throw new TypeError('callback not provided') } - return spreads; + return new Promise(function (resolve, reject) { + isexe(path, options || {}, function (er, is) { + if (er) { + reject(er) + } else { + resolve(is) + } + }) + }) } - getRecursivelyReferencedFragments(operation) { - let fragments = this._recursivelyReferencedFragments.get(operation); - - if (!fragments) { - fragments = []; - const collectedNames = Object.create(null); - const nodesToVisit = [operation.selectionSet]; - let node; - - while ((node = nodesToVisit.pop())) { - for (const spread of this.getFragmentSpreads(node)) { - const fragName = spread.name.value; - - if (collectedNames[fragName] !== true) { - collectedNames[fragName] = true; - const fragment = this.getFragment(fragName); - - if (fragment) { - fragments.push(fragment); - nodesToVisit.push(fragment.selectionSet); - } - } - } + core(path, options || {}, function (er, is) { + // ignore EACCES because that just means we aren't allowed to run it + if (er) { + if (er.code === 'EACCES' || options && options.ignoreErrors) { + er = null + is = false } - - this._recursivelyReferencedFragments.set(operation, fragments); } - - return fragments; - } + cb(er, is) + }) } -exports.ASTValidationContext = ASTValidationContext; - -class SDLValidationContext extends ASTValidationContext { - constructor(ast, schema, onError) { - super(ast, onError); - this._schema = schema; +function sync (path, options) { + // my kingdom for a filtered catch + try { + return core.sync(path, options || {}) + } catch (er) { + if (options && options.ignoreErrors || er.code === 'EACCES') { + return false + } else { + throw er + } } +} - get [Symbol.toStringTag]() { - return 'SDLValidationContext'; - } - getSchema() { - return this._schema; - } -} +/***/ }), -exports.SDLValidationContext = SDLValidationContext; +/***/ 9728: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -class ValidationContext extends ASTValidationContext { - constructor(schema, ast, typeInfo, onError) { - super(ast, onError); - this._schema = schema; - this._typeInfo = typeInfo; - this._variableUsages = new Map(); - this._recursiveVariableUsages = new Map(); - } +module.exports = isexe +isexe.sync = sync - get [Symbol.toStringTag]() { - return 'ValidationContext'; - } +var fs = __nccwpck_require__(57147) - getSchema() { - return this._schema; - } +function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, options)) + }) +} - getVariableUsages(node) { - let usages = this._variableUsages.get(node); +function sync (path, options) { + return checkStat(fs.statSync(path), options) +} - if (!usages) { - const newUsages = []; - const typeInfo = new _TypeInfo.TypeInfo(this._schema); - (0, _visitor.visit)( - node, - (0, _TypeInfo.visitWithTypeInfo)(typeInfo, { - VariableDefinition: () => false, +function checkStat (stat, options) { + return stat.isFile() && checkMode(stat, options) +} - Variable(variable) { - newUsages.push({ - node: variable, - type: typeInfo.getInputType(), - defaultValue: typeInfo.getDefaultValue(), - parentType: typeInfo.getParentInputType(), - }); - }, - }), - ); - usages = newUsages; +function checkMode (stat, options) { + var mod = stat.mode + var uid = stat.uid + var gid = stat.gid - this._variableUsages.set(node, usages); - } + var myUid = options.uid !== undefined ? + options.uid : process.getuid && process.getuid() + var myGid = options.gid !== undefined ? + options.gid : process.getgid && process.getgid() - return usages; - } + var u = parseInt('100', 8) + var g = parseInt('010', 8) + var o = parseInt('001', 8) + var ug = u | g - getRecursiveVariableUsages(operation) { - let usages = this._recursiveVariableUsages.get(operation); + var ret = (mod & o) || + (mod & g) && gid === myGid || + (mod & u) && uid === myUid || + (mod & ug) && myUid === 0 - if (!usages) { - usages = this.getVariableUsages(operation); + return ret +} - for (const frag of this.getRecursivelyReferencedFragments(operation)) { - usages = usages.concat(this.getVariableUsages(frag)); - } - this._recursiveVariableUsages.set(operation, usages); - } +/***/ }), - return usages; - } +/***/ 42001: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - getType() { - return this._typeInfo.getType(); - } +module.exports = isexe +isexe.sync = sync - getParentType() { - return this._typeInfo.getParentType(); - } +var fs = __nccwpck_require__(57147) - getInputType() { - return this._typeInfo.getInputType(); - } +function checkPathExt (path, options) { + var pathext = options.pathExt !== undefined ? + options.pathExt : process.env.PATHEXT - getParentInputType() { - return this._typeInfo.getParentInputType(); + if (!pathext) { + return true } - getFieldDef() { - return this._typeInfo.getFieldDef(); + pathext = pathext.split(';') + if (pathext.indexOf('') !== -1) { + return true } - - getDirective() { - return this._typeInfo.getDirective(); + for (var i = 0; i < pathext.length; i++) { + var p = pathext[i].toLowerCase() + if (p && path.substr(-p.length).toLowerCase() === p) { + return true + } } + return false +} - getArgument() { - return this._typeInfo.getArgument(); +function checkStat (stat, path, options) { + if (!stat.isSymbolicLink() && !stat.isFile()) { + return false } + return checkPathExt(path, options) +} - getEnumValue() { - return this._typeInfo.getEnumValue(); - } +function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, path, options)) + }) } -exports.ValidationContext = ValidationContext; +function sync (path, options) { + return checkStat(fs.statSync(path), path, options) +} /***/ }), -/***/ 82201: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 64713: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -Object.defineProperty(exports, "ExecutableDefinitionsRule", ({ - enumerable: true, - get: function () { - return _ExecutableDefinitionsRule.ExecutableDefinitionsRule; - }, -})); -Object.defineProperty(exports, "FieldsOnCorrectTypeRule", ({ - enumerable: true, - get: function () { - return _FieldsOnCorrectTypeRule.FieldsOnCorrectTypeRule; - }, -})); -Object.defineProperty(exports, "FragmentsOnCompositeTypesRule", ({ - enumerable: true, - get: function () { - return _FragmentsOnCompositeTypesRule.FragmentsOnCompositeTypesRule; - }, -})); -Object.defineProperty(exports, "KnownArgumentNamesRule", ({ - enumerable: true, - get: function () { - return _KnownArgumentNamesRule.KnownArgumentNamesRule; - }, -})); -Object.defineProperty(exports, "KnownDirectivesRule", ({ - enumerable: true, - get: function () { - return _KnownDirectivesRule.KnownDirectivesRule; - }, -})); -Object.defineProperty(exports, "KnownFragmentNamesRule", ({ - enumerable: true, - get: function () { - return _KnownFragmentNamesRule.KnownFragmentNamesRule; - }, -})); -Object.defineProperty(exports, "KnownTypeNamesRule", ({ - enumerable: true, - get: function () { - return _KnownTypeNamesRule.KnownTypeNamesRule; - }, -})); -Object.defineProperty(exports, "LoneAnonymousOperationRule", ({ - enumerable: true, - get: function () { - return _LoneAnonymousOperationRule.LoneAnonymousOperationRule; - }, -})); -Object.defineProperty(exports, "LoneSchemaDefinitionRule", ({ - enumerable: true, - get: function () { - return _LoneSchemaDefinitionRule.LoneSchemaDefinitionRule; - }, -})); -Object.defineProperty(exports, "MaxIntrospectionDepthRule", ({ - enumerable: true, - get: function () { - return _MaxIntrospectionDepthRule.MaxIntrospectionDepthRule; - }, -})); -Object.defineProperty(exports, "NoDeprecatedCustomRule", ({ - enumerable: true, - get: function () { - return _NoDeprecatedCustomRule.NoDeprecatedCustomRule; - }, -})); -Object.defineProperty(exports, "NoFragmentCyclesRule", ({ - enumerable: true, - get: function () { - return _NoFragmentCyclesRule.NoFragmentCyclesRule; - }, -})); -Object.defineProperty(exports, "NoSchemaIntrospectionCustomRule", ({ - enumerable: true, - get: function () { - return _NoSchemaIntrospectionCustomRule.NoSchemaIntrospectionCustomRule; - }, -})); -Object.defineProperty(exports, "NoUndefinedVariablesRule", ({ - enumerable: true, - get: function () { - return _NoUndefinedVariablesRule.NoUndefinedVariablesRule; - }, -})); -Object.defineProperty(exports, "NoUnusedFragmentsRule", ({ - enumerable: true, - get: function () { - return _NoUnusedFragmentsRule.NoUnusedFragmentsRule; - }, -})); -Object.defineProperty(exports, "NoUnusedVariablesRule", ({ - enumerable: true, - get: function () { - return _NoUnusedVariablesRule.NoUnusedVariablesRule; - }, -})); -Object.defineProperty(exports, "OverlappingFieldsCanBeMergedRule", ({ - enumerable: true, - get: function () { - return _OverlappingFieldsCanBeMergedRule.OverlappingFieldsCanBeMergedRule; - }, -})); -Object.defineProperty(exports, "PossibleFragmentSpreadsRule", ({ - enumerable: true, - get: function () { - return _PossibleFragmentSpreadsRule.PossibleFragmentSpreadsRule; - }, -})); -Object.defineProperty(exports, "PossibleTypeExtensionsRule", ({ - enumerable: true, - get: function () { - return _PossibleTypeExtensionsRule.PossibleTypeExtensionsRule; - }, -})); -Object.defineProperty(exports, "ProvidedRequiredArgumentsRule", ({ - enumerable: true, - get: function () { - return _ProvidedRequiredArgumentsRule.ProvidedRequiredArgumentsRule; - }, -})); -Object.defineProperty(exports, "ScalarLeafsRule", ({ - enumerable: true, - get: function () { - return _ScalarLeafsRule.ScalarLeafsRule; - }, -})); -Object.defineProperty(exports, "SingleFieldSubscriptionsRule", ({ - enumerable: true, - get: function () { - return _SingleFieldSubscriptionsRule.SingleFieldSubscriptionsRule; - }, -})); -Object.defineProperty(exports, "UniqueArgumentDefinitionNamesRule", ({ - enumerable: true, - get: function () { - return _UniqueArgumentDefinitionNamesRule.UniqueArgumentDefinitionNamesRule; - }, -})); -Object.defineProperty(exports, "UniqueArgumentNamesRule", ({ - enumerable: true, - get: function () { - return _UniqueArgumentNamesRule.UniqueArgumentNamesRule; - }, -})); -Object.defineProperty(exports, "UniqueDirectiveNamesRule", ({ - enumerable: true, - get: function () { - return _UniqueDirectiveNamesRule.UniqueDirectiveNamesRule; - }, -})); -Object.defineProperty(exports, "UniqueDirectivesPerLocationRule", ({ - enumerable: true, - get: function () { - return _UniqueDirectivesPerLocationRule.UniqueDirectivesPerLocationRule; - }, -})); -Object.defineProperty(exports, "UniqueEnumValueNamesRule", ({ - enumerable: true, - get: function () { - return _UniqueEnumValueNamesRule.UniqueEnumValueNamesRule; - }, -})); -Object.defineProperty(exports, "UniqueFieldDefinitionNamesRule", ({ - enumerable: true, - get: function () { - return _UniqueFieldDefinitionNamesRule.UniqueFieldDefinitionNamesRule; - }, -})); -Object.defineProperty(exports, "UniqueFragmentNamesRule", ({ - enumerable: true, - get: function () { - return _UniqueFragmentNamesRule.UniqueFragmentNamesRule; - }, -})); -Object.defineProperty(exports, "UniqueInputFieldNamesRule", ({ - enumerable: true, - get: function () { - return _UniqueInputFieldNamesRule.UniqueInputFieldNamesRule; - }, -})); -Object.defineProperty(exports, "UniqueOperationNamesRule", ({ - enumerable: true, - get: function () { - return _UniqueOperationNamesRule.UniqueOperationNamesRule; - }, -})); -Object.defineProperty(exports, "UniqueOperationTypesRule", ({ - enumerable: true, - get: function () { - return _UniqueOperationTypesRule.UniqueOperationTypesRule; - }, -})); -Object.defineProperty(exports, "UniqueTypeNamesRule", ({ - enumerable: true, - get: function () { - return _UniqueTypeNamesRule.UniqueTypeNamesRule; - }, -})); -Object.defineProperty(exports, "UniqueVariableNamesRule", ({ - enumerable: true, - get: function () { - return _UniqueVariableNamesRule.UniqueVariableNamesRule; - }, -})); -Object.defineProperty(exports, "ValidationContext", ({ - enumerable: true, - get: function () { - return _ValidationContext.ValidationContext; - }, -})); -Object.defineProperty(exports, "ValuesOfCorrectTypeRule", ({ - enumerable: true, - get: function () { - return _ValuesOfCorrectTypeRule.ValuesOfCorrectTypeRule; - }, -})); -Object.defineProperty(exports, "VariablesAreInputTypesRule", ({ - enumerable: true, - get: function () { - return _VariablesAreInputTypesRule.VariablesAreInputTypesRule; - }, -})); -Object.defineProperty(exports, "VariablesInAllowedPositionRule", ({ - enumerable: true, - get: function () { - return _VariablesInAllowedPositionRule.VariablesInAllowedPositionRule; - }, -})); -Object.defineProperty(exports, "recommendedRules", ({ - enumerable: true, - get: function () { - return _specifiedRules.recommendedRules; - }, -})); -Object.defineProperty(exports, "specifiedRules", ({ - enumerable: true, - get: function () { - return _specifiedRules.specifiedRules; - }, -})); -Object.defineProperty(exports, "validate", ({ - enumerable: true, - get: function () { - return _validate.validate; - }, -})); +module.exports = __nccwpck_require__(88867); -var _validate = __nccwpck_require__(14193); +/***/ }), -var _ValidationContext = __nccwpck_require__(28263); +/***/ 83362: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var _specifiedRules = __nccwpck_require__(61556); +var stream = __nccwpck_require__(12781) -var _ExecutableDefinitionsRule = __nccwpck_require__(89199); -var _FieldsOnCorrectTypeRule = __nccwpck_require__(63016); +function isStream (obj) { + return obj instanceof stream.Stream +} -var _FragmentsOnCompositeTypesRule = __nccwpck_require__(60381); -var _KnownArgumentNamesRule = __nccwpck_require__(67147); +function isReadable (obj) { + return isStream(obj) && typeof obj._read == 'function' && typeof obj._readableState == 'object' +} -var _KnownDirectivesRule = __nccwpck_require__(85303); -var _KnownFragmentNamesRule = __nccwpck_require__(15166); +function isWritable (obj) { + return isStream(obj) && typeof obj._write == 'function' && typeof obj._writableState == 'object' +} -var _KnownTypeNamesRule = __nccwpck_require__(42509); -var _LoneAnonymousOperationRule = __nccwpck_require__(45726); +function isDuplex (obj) { + return isReadable(obj) && isWritable(obj) +} -var _NoFragmentCyclesRule = __nccwpck_require__(62564); -var _NoUndefinedVariablesRule = __nccwpck_require__(61671); +module.exports = isStream +module.exports.isReadable = isReadable +module.exports.isWritable = isWritable +module.exports.isDuplex = isDuplex -var _NoUnusedFragmentsRule = __nccwpck_require__(192); -var _NoUnusedVariablesRule = __nccwpck_require__(40242); +/***/ }), -var _OverlappingFieldsCanBeMergedRule = __nccwpck_require__(23577); +/***/ 52973: +/***/ ((module) => { -var _PossibleFragmentSpreadsRule = __nccwpck_require__(62450); +const CODES = { + JOSEAlgNotWhitelisted: 'ERR_JOSE_ALG_NOT_WHITELISTED', + JOSECritNotUnderstood: 'ERR_JOSE_CRIT_NOT_UNDERSTOOD', + JOSEInvalidEncoding: 'ERR_JOSE_INVALID_ENCODING', + JOSEMultiError: 'ERR_JOSE_MULTIPLE_ERRORS', + JOSENotSupported: 'ERR_JOSE_NOT_SUPPORTED', + JWEDecryptionFailed: 'ERR_JWE_DECRYPTION_FAILED', + JWEInvalid: 'ERR_JWE_INVALID', + JWKImportFailed: 'ERR_JWK_IMPORT_FAILED', + JWKInvalid: 'ERR_JWK_INVALID', + JWKKeySupport: 'ERR_JWK_KEY_SUPPORT', + JWKSNoMatchingKey: 'ERR_JWKS_NO_MATCHING_KEY', + JWSInvalid: 'ERR_JWS_INVALID', + JWSVerificationFailed: 'ERR_JWS_VERIFICATION_FAILED', + JWTClaimInvalid: 'ERR_JWT_CLAIM_INVALID', + JWTExpired: 'ERR_JWT_EXPIRED', + JWTMalformed: 'ERR_JWT_MALFORMED' +} -var _ProvidedRequiredArgumentsRule = __nccwpck_require__(57669); +const DEFAULT_MESSAGES = { + JWEDecryptionFailed: 'decryption operation failed', + JWEInvalid: 'JWE invalid', + JWKSNoMatchingKey: 'no matching key found in the KeyStore', + JWSInvalid: 'JWS invalid', + JWSVerificationFailed: 'signature verification failed' +} -var _ScalarLeafsRule = __nccwpck_require__(16830); +class JOSEError extends Error { + constructor (message) { + super(message) + if (message === undefined) { + this.message = DEFAULT_MESSAGES[this.constructor.name] + } + this.name = this.constructor.name + this.code = CODES[this.constructor.name] + Error.captureStackTrace(this, this.constructor) + } +} -var _SingleFieldSubscriptionsRule = __nccwpck_require__(4365); +const isMulti = e => e instanceof JOSEMultiError +class JOSEMultiError extends JOSEError { + constructor (errors) { + super() + let i + while ((i = errors.findIndex(isMulti)) && i !== -1) { + errors.splice(i, 1, ...errors[i]) + } + Object.defineProperty(this, 'errors', { value: errors }) + } -var _UniqueArgumentNamesRule = __nccwpck_require__(45799); + * [Symbol.iterator] () { + for (const error of this.errors) { + yield error + } + } +} +module.exports.JOSEError = JOSEError -var _UniqueDirectivesPerLocationRule = __nccwpck_require__(61944); +module.exports.JOSEAlgNotWhitelisted = class JOSEAlgNotWhitelisted extends JOSEError {} +module.exports.JOSECritNotUnderstood = class JOSECritNotUnderstood extends JOSEError {} +module.exports.JOSEInvalidEncoding = class JOSEInvalidEncoding extends JOSEError {} +module.exports.JOSEMultiError = JOSEMultiError +module.exports.JOSENotSupported = class JOSENotSupported extends JOSEError {} -var _UniqueFragmentNamesRule = __nccwpck_require__(79402); +module.exports.JWEDecryptionFailed = class JWEDecryptionFailed extends JOSEError {} +module.exports.JWEInvalid = class JWEInvalid extends JOSEError {} -var _UniqueInputFieldNamesRule = __nccwpck_require__(83552); +module.exports.JWKImportFailed = class JWKImportFailed extends JOSEError {} +module.exports.JWKInvalid = class JWKInvalid extends JOSEError {} +module.exports.JWKKeySupport = class JWKKeySupport extends JOSEError {} -var _UniqueOperationNamesRule = __nccwpck_require__(94865); +module.exports.JWKSNoMatchingKey = class JWKSNoMatchingKey extends JOSEError {} -var _UniqueVariableNamesRule = __nccwpck_require__(65931); +module.exports.JWSInvalid = class JWSInvalid extends JOSEError {} +module.exports.JWSVerificationFailed = class JWSVerificationFailed extends JOSEError {} -var _ValuesOfCorrectTypeRule = __nccwpck_require__(85189); +class JWTClaimInvalid extends JOSEError { + constructor (message, claim = 'unspecified', reason = 'unspecified') { + super(message) + this.claim = claim + this.reason = reason + } +} +module.exports.JWTClaimInvalid = JWTClaimInvalid +module.exports.JWTExpired = class JWTExpired extends JWTClaimInvalid {} +module.exports.JWTMalformed = class JWTMalformed extends JOSEError {} -var _VariablesAreInputTypesRule = __nccwpck_require__(99506); -var _VariablesInAllowedPositionRule = __nccwpck_require__(8815); +/***/ }), -var _MaxIntrospectionDepthRule = __nccwpck_require__(53318); +/***/ 68207: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var _LoneSchemaDefinitionRule = __nccwpck_require__(48307); +const oids = __nccwpck_require__(72967) -var _UniqueOperationTypesRule = __nccwpck_require__(31492); +module.exports = function () { + this.seq().obj( + this.key('algorithm').objid(oids), + this.key('parameters').optional().choice({ namedCurve: this.objid(oids), null: this.null_() }) + ) +} -var _UniqueTypeNamesRule = __nccwpck_require__(24316); -var _UniqueEnumValueNamesRule = __nccwpck_require__(44437); +/***/ }), -var _UniqueFieldDefinitionNamesRule = __nccwpck_require__(9502); +/***/ 37707: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var _UniqueArgumentDefinitionNamesRule = __nccwpck_require__(55104); +const oids = __nccwpck_require__(72967) -var _UniqueDirectiveNamesRule = __nccwpck_require__(17074); +module.exports = function () { + this.seq().obj( + this.key('version').int(), + this.key('privateKey').octstr(), + this.key('parameters').explicit(0).optional().choice({ namedCurve: this.objid(oids) }), + this.key('publicKey').explicit(1).optional().bitstr() + ) +} -var _PossibleTypeExtensionsRule = __nccwpck_require__(70075); -var _NoDeprecatedCustomRule = __nccwpck_require__(33915); +/***/ }), -var _NoSchemaIntrospectionCustomRule = __nccwpck_require__(39478); +/***/ 16416: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const asn1 = __nccwpck_require__(39436) -/***/ }), +const types = new Map() -/***/ 89199: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +const AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', __nccwpck_require__(68207)) +types.set('AlgorithmIdentifier', AlgorithmIdentifier) -"use strict"; +const ECPrivateKey = asn1.define('ECPrivateKey', __nccwpck_require__(37707)) +types.set('ECPrivateKey', ECPrivateKey) +const PrivateKeyInfo = asn1.define('PrivateKeyInfo', __nccwpck_require__(58570)(AlgorithmIdentifier)) +types.set('PrivateKeyInfo', PrivateKeyInfo) -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.ExecutableDefinitionsRule = ExecutableDefinitionsRule; +const PublicKeyInfo = asn1.define('PublicKeyInfo', __nccwpck_require__(5641)(AlgorithmIdentifier)) +types.set('PublicKeyInfo', PublicKeyInfo) -var _GraphQLError = __nccwpck_require__(4797); +const PrivateKey = asn1.define('PrivateKey', __nccwpck_require__(62624)) +types.set('PrivateKey', PrivateKey) -var _kinds = __nccwpck_require__(11927); +const OneAsymmetricKey = asn1.define('OneAsymmetricKey', __nccwpck_require__(30424)(AlgorithmIdentifier, PrivateKey)) +types.set('OneAsymmetricKey', OneAsymmetricKey) -var _predicates = __nccwpck_require__(20535); +const RSAPrivateKey = asn1.define('RSAPrivateKey', __nccwpck_require__(29822)) +types.set('RSAPrivateKey', RSAPrivateKey) -/** - * Executable definitions - * - * A GraphQL document is only valid for execution if all definitions are either - * operation or fragment definitions. - * - * See https://spec.graphql.org/draft/#sec-Executable-Definitions - */ -function ExecutableDefinitionsRule(context) { - return { - Document(node) { - for (const definition of node.definitions) { - if (!(0, _predicates.isExecutableDefinitionNode)(definition)) { - const defName = - definition.kind === _kinds.Kind.SCHEMA_DEFINITION || - definition.kind === _kinds.Kind.SCHEMA_EXTENSION - ? 'schema' - : '"' + definition.name.value + '"'; - context.reportError( - new _GraphQLError.GraphQLError( - `The ${defName} definition is not executable.`, - { - nodes: definition, - }, - ), - ); - } - } +const RSAPublicKey = asn1.define('RSAPublicKey', __nccwpck_require__(39542)) +types.set('RSAPublicKey', RSAPublicKey) - return false; - }, - }; -} +module.exports = types /***/ }), -/***/ 63016: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 72967: +/***/ ((module) => { -"use strict"; +const oids = { + '1 2 840 10045 3 1 7': 'P-256', + '1 3 132 0 10': 'secp256k1', + '1 3 132 0 34': 'P-384', + '1 3 132 0 35': 'P-521', + '1 2 840 10045 2 1': 'ecPublicKey', + '1 2 840 113549 1 1 1': 'rsaEncryption', + '1 3 101 110': 'X25519', + '1 3 101 111': 'X448', + '1 3 101 112': 'Ed25519', + '1 3 101 113': 'Ed448' +} +module.exports = oids -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.FieldsOnCorrectTypeRule = FieldsOnCorrectTypeRule; -var _didYouMean = __nccwpck_require__(42878); +/***/ }), -var _naturalCompare = __nccwpck_require__(20038); +/***/ 30424: +/***/ ((module) => { -var _suggestionList = __nccwpck_require__(57704); +module.exports = (AlgorithmIdentifier, PrivateKey) => function () { + this.seq().obj( + this.key('version').int(), + this.key('algorithm').use(AlgorithmIdentifier), + this.key('privateKey').use(PrivateKey) + ) +} -var _GraphQLError = __nccwpck_require__(4797); -var _definition = __nccwpck_require__(32150); +/***/ }), -/** - * Fields on correct type - * - * A GraphQL document is only valid if all fields selected are defined by the - * parent type, or are an allowed meta field such as __typename. - * - * See https://spec.graphql.org/draft/#sec-Field-Selections - */ -function FieldsOnCorrectTypeRule(context) { - return { - Field(node) { - const type = context.getParentType(); +/***/ 62624: +/***/ ((module) => { - if (type) { - const fieldDef = context.getFieldDef(); +module.exports = function () { + this.octstr().contains().obj( + this.key('privateKey').octstr() + ) +} - if (!fieldDef) { - // This field doesn't exist, lets look for suggestions. - const schema = context.getSchema(); - const fieldName = node.name.value; // First determine if there are any suggested types to condition on. - let suggestion = (0, _didYouMean.didYouMean)( - 'to use an inline fragment on', - getSuggestedTypeNames(schema, type, fieldName), - ); // If there are no suggested types, then perhaps this was a typo? +/***/ }), - if (suggestion === '') { - suggestion = (0, _didYouMean.didYouMean)( - getSuggestedFieldNames(type, fieldName), - ); - } // Report an error, including helpful suggestions. +/***/ 58570: +/***/ ((module) => { - context.reportError( - new _GraphQLError.GraphQLError( - `Cannot query field "${fieldName}" on type "${type.name}".` + - suggestion, - { - nodes: node, - }, - ), - ); - } - } - }, - }; +module.exports = (AlgorithmIdentifier) => function () { + this.seq().obj( + this.key('version').int(), + this.key('algorithm').use(AlgorithmIdentifier), + this.key('privateKey').octstr() + ) } -/** - * Go through all of the implementations of type, as well as the interfaces that - * they implement. If any of those types include the provided field, suggest them, - * sorted by how often the type is referenced. - */ - -function getSuggestedTypeNames(schema, type, fieldName) { - if (!(0, _definition.isAbstractType)(type)) { - // Must be an Object type, which does not have possible fields. - return []; - } - - const suggestedTypes = new Set(); - const usageCount = Object.create(null); - for (const possibleType of schema.getPossibleTypes(type)) { - if (!possibleType.getFields()[fieldName]) { - continue; - } // This object type defines this field. - suggestedTypes.add(possibleType); - usageCount[possibleType.name] = 1; +/***/ }), - for (const possibleInterface of possibleType.getInterfaces()) { - var _usageCount$possibleI; +/***/ 5641: +/***/ ((module) => { - if (!possibleInterface.getFields()[fieldName]) { - continue; - } // This interface type defines this field. +module.exports = AlgorithmIdentifier => function () { + this.seq().obj( + this.key('algorithm').use(AlgorithmIdentifier), + this.key('publicKey').bitstr() + ) +} - suggestedTypes.add(possibleInterface); - usageCount[possibleInterface.name] = - ((_usageCount$possibleI = usageCount[possibleInterface.name]) !== - null && _usageCount$possibleI !== void 0 - ? _usageCount$possibleI - : 0) + 1; - } - } - return [...suggestedTypes] - .sort((typeA, typeB) => { - // Suggest both interface and object types based on how common they are. - const usageCountDiff = usageCount[typeB.name] - usageCount[typeA.name]; +/***/ }), - if (usageCountDiff !== 0) { - return usageCountDiff; - } // Suggest super types first followed by subtypes +/***/ 29822: +/***/ ((module) => { - if ( - (0, _definition.isInterfaceType)(typeA) && - schema.isSubType(typeA, typeB) - ) { - return -1; - } +module.exports = function () { + this.seq().obj( + this.key('version').int({ 0: 'two-prime', 1: 'multi' }), + this.key('n').int(), + this.key('e').int(), + this.key('d').int(), + this.key('p').int(), + this.key('q').int(), + this.key('dp').int(), + this.key('dq').int(), + this.key('qi').int() + ) +} - if ( - (0, _definition.isInterfaceType)(typeB) && - schema.isSubType(typeB, typeA) - ) { - return 1; - } - return (0, _naturalCompare.naturalCompare)(typeA.name, typeB.name); - }) - .map((x) => x.name); -} -/** - * For the field name provided, determine if there are any similar field names - * that may be the result of a typo. - */ +/***/ }), -function getSuggestedFieldNames(type, fieldName) { - if ( - (0, _definition.isObjectType)(type) || - (0, _definition.isInterfaceType)(type) - ) { - const possibleFieldNames = Object.keys(type.getFields()); - return (0, _suggestionList.suggestionList)(fieldName, possibleFieldNames); - } // Otherwise, must be a Union type, which does not define fields. +/***/ 39542: +/***/ ((module) => { - return []; +module.exports = function () { + this.seq().obj( + this.key('n').int(), + this.key('e').int() + ) } /***/ }), -/***/ 60381: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 73385: +/***/ ((module) => { -"use strict"; +let encode +let encodeBuffer +if (Buffer.isEncoding('base64url')) { + encode = (input, encoding = 'utf8') => Buffer.from(input, encoding).toString('base64url') + encodeBuffer = (buf) => buf.toString('base64url') +} else { + const fromBase64 = (base64) => base64.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_') + encode = (input, encoding = 'utf8') => fromBase64(Buffer.from(input, encoding).toString('base64')) + encodeBuffer = (buf) => fromBase64(buf.toString('base64')) +} +const decodeToBuffer = (input) => { + return Buffer.from(input, 'base64') +} -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.FragmentsOnCompositeTypesRule = FragmentsOnCompositeTypesRule; +const decode = (input, encoding = 'utf8') => { + return decodeToBuffer(input).toString(encoding) +} -var _GraphQLError = __nccwpck_require__(4797); +const b64uJSON = { + encode: (input) => { + return encode(JSON.stringify(input)) + }, + decode: (input, encoding = 'utf8') => { + return JSON.parse(decode(input, encoding)) + } +} -var _printer = __nccwpck_require__(68203); +b64uJSON.decode.try = (input, encoding = 'utf8') => { + try { + return b64uJSON.decode(input, encoding) + } catch (err) { + return decode(input, encoding) + } +} -var _definition = __nccwpck_require__(32150); +const bnToBuf = (bn) => { + let hex = BigInt(bn).toString(16) + if (hex.length % 2) { + hex = `0${hex}` + } -var _typeFromAST = __nccwpck_require__(27664); + const len = hex.length / 2 + const u8 = new Uint8Array(len) -/** - * Fragments on composite type - * - * Fragments use a type condition to determine if they apply, since fragments - * can only be spread into a composite type (object, interface, or union), the - * type condition must also be a composite type. - * - * See https://spec.graphql.org/draft/#sec-Fragments-On-Composite-Types - */ -function FragmentsOnCompositeTypesRule(context) { - return { - InlineFragment(node) { - const typeCondition = node.typeCondition; + let i = 0 + let j = 0 + while (i < len) { + u8[i] = parseInt(hex.slice(j, j + 2), 16) + i += 1 + j += 2 + } - if (typeCondition) { - const type = (0, _typeFromAST.typeFromAST)( - context.getSchema(), - typeCondition, - ); + return u8 +} - if (type && !(0, _definition.isCompositeType)(type)) { - const typeStr = (0, _printer.print)(typeCondition); - context.reportError( - new _GraphQLError.GraphQLError( - `Fragment cannot condition on non composite type "${typeStr}".`, - { - nodes: typeCondition, - }, - ), - ); - } - } - }, +const encodeBigInt = (bn) => encodeBuffer(Buffer.from(bnToBuf(bn))) + +module.exports.decode = decode +module.exports.decodeToBuffer = decodeToBuffer +module.exports.encode = encode +module.exports.encodeBuffer = encodeBuffer +module.exports.JSON = b64uJSON +module.exports.encodeBigInt = encodeBigInt - FragmentDefinition(node) { - const type = (0, _typeFromAST.typeFromAST)( - context.getSchema(), - node.typeCondition, - ); - if (type && !(0, _definition.isCompositeType)(type)) { - const typeStr = (0, _printer.print)(node.typeCondition); - context.reportError( - new _GraphQLError.GraphQLError( - `Fragment "${node.name.value}" cannot condition on non composite type "${typeStr}".`, - { - nodes: node.typeCondition, - }, - ), - ); - } - }, - }; +/***/ }), + +/***/ 15010: +/***/ ((module) => { + +module.exports.KEYOBJECT = Symbol('KEYOBJECT') +module.exports.PRIVATE_MEMBERS = Symbol('PRIVATE_MEMBERS') +module.exports.PUBLIC_MEMBERS = Symbol('PUBLIC_MEMBERS') +module.exports.THUMBPRINT_MATERIAL = Symbol('THUMBPRINT_MATERIAL') +module.exports.JWK_MEMBERS = Symbol('JWK_MEMBERS') +module.exports.KEY_MANAGEMENT_ENCRYPT = Symbol('KEY_MANAGEMENT_ENCRYPT') +module.exports.KEY_MANAGEMENT_DECRYPT = Symbol('KEY_MANAGEMENT_DECRYPT') + +const USES_MAPPING = { + sig: new Set(['sign', 'verify']), + enc: new Set(['encrypt', 'decrypt', 'wrapKey', 'unwrapKey', 'deriveKey']) } +const OPS = new Set([...USES_MAPPING.sig, ...USES_MAPPING.enc]) +const USES = new Set(Object.keys(USES_MAPPING)) + +module.exports.USES_MAPPING = USES_MAPPING +module.exports.OPS = OPS +module.exports.USES = USES /***/ }), -/***/ 67147: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; +/***/ 43653: +/***/ ((module) => { +module.exports = obj => JSON.parse(JSON.stringify(obj)) -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.KnownArgumentNamesOnDirectivesRule = KnownArgumentNamesOnDirectivesRule; -exports.KnownArgumentNamesRule = KnownArgumentNamesRule; -var _didYouMean = __nccwpck_require__(42878); +/***/ }), -var _suggestionList = __nccwpck_require__(57704); +/***/ 14451: +/***/ ((module) => { -var _GraphQLError = __nccwpck_require__(4797); +const MAX_OCTET = 0x80 +const CLASS_UNIVERSAL = 0 +const PRIMITIVE_BIT = 0x20 +const TAG_SEQ = 0x10 +const TAG_INT = 0x02 +const ENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6) +const ENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6) -var _kinds = __nccwpck_require__(11927); +const getParamSize = keySize => ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1) -var _directives = __nccwpck_require__(83614); +const paramBytesForAlg = { + ES256: getParamSize(256), + ES256K: getParamSize(256), + ES384: getParamSize(384), + ES512: getParamSize(521) +} -/** - * Known argument names - * - * A GraphQL field is only valid if all supplied arguments are defined by - * that field. - * - * See https://spec.graphql.org/draft/#sec-Argument-Names - * See https://spec.graphql.org/draft/#sec-Directives-Are-In-Valid-Locations - */ -function KnownArgumentNamesRule(context) { - return { - // eslint-disable-next-line new-cap - ...KnownArgumentNamesOnDirectivesRule(context), +const countPadding = (buf, start, stop) => { + let padding = 0 + while (start + padding < stop && buf[start + padding] === 0) { + ++padding + } - Argument(argNode) { - const argDef = context.getArgument(); - const fieldDef = context.getFieldDef(); - const parentType = context.getParentType(); + const needsSign = buf[start + padding] >= MAX_OCTET + if (needsSign) { + --padding + } - if (!argDef && fieldDef && parentType) { - const argName = argNode.name.value; - const knownArgsNames = fieldDef.args.map((arg) => arg.name); - const suggestions = (0, _suggestionList.suggestionList)( - argName, - knownArgsNames, - ); - context.reportError( - new _GraphQLError.GraphQLError( - `Unknown argument "${argName}" on field "${parentType.name}.${fieldDef.name}".` + - (0, _didYouMean.didYouMean)(suggestions), - { - nodes: argNode, - }, - ), - ); - } - }, - }; + return padding } -/** - * @internal - */ -function KnownArgumentNamesOnDirectivesRule(context) { - const directiveArgs = Object.create(null); - const schema = context.getSchema(); - const definedDirectives = schema - ? schema.getDirectives() - : _directives.specifiedDirectives; +module.exports.derToJose = (signature, alg) => { + if (!Buffer.isBuffer(signature)) { + throw new TypeError('ECDSA signature must be a Buffer') + } - for (const directive of definedDirectives) { - directiveArgs[directive.name] = directive.args.map((arg) => arg.name); + if (!paramBytesForAlg[alg]) { + throw new Error(`Unknown algorithm "${alg}"`) } - const astDefinitions = context.getDocument().definitions; + const paramBytes = paramBytesForAlg[alg] - for (const def of astDefinitions) { - if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { - var _def$arguments; + // the DER encoded param should at most be the param size, plus a padding + // zero, since due to being a signed integer + const maxEncodedParamLength = paramBytes + 1 - // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const inputLength = signature.length - /* c8 ignore next */ - const argsNodes = - (_def$arguments = def.arguments) !== null && _def$arguments !== void 0 - ? _def$arguments - : []; - directiveArgs[def.name.value] = argsNodes.map((arg) => arg.name.value); - } + let offset = 0 + if (signature[offset++] !== ENCODED_TAG_SEQ) { + throw new Error('Could not find expected "seq"') } - return { - Directive(directiveNode) { - const directiveName = directiveNode.name.value; - const knownArgs = directiveArgs[directiveName]; + let seqLength = signature[offset++] + if (seqLength === (MAX_OCTET | 1)) { + seqLength = signature[offset++] + } - if (directiveNode.arguments && knownArgs) { - for (const argNode of directiveNode.arguments) { - const argName = argNode.name.value; + if (inputLength - offset < seqLength) { + throw new Error(`"seq" specified length of ${seqLength}", only ${inputLength - offset}" remaining`) + } - if (!knownArgs.includes(argName)) { - const suggestions = (0, _suggestionList.suggestionList)( - argName, - knownArgs, - ); - context.reportError( - new _GraphQLError.GraphQLError( - `Unknown argument "${argName}" on directive "@${directiveName}".` + - (0, _didYouMean.didYouMean)(suggestions), - { - nodes: argNode, - }, - ), - ); - } - } - } + if (signature[offset++] !== ENCODED_TAG_INT) { + throw new Error('Could not find expected "int" for "r"') + } - return false; - }, - }; -} + const rLength = signature[offset++] + if (inputLength - offset - 2 < rLength) { + throw new Error(`"r" specified length of "${rLength}", only "${inputLength - offset - 2}" available`) + } -/***/ }), + if (maxEncodedParamLength < rLength) { + throw new Error(`"r" specified length of "${rLength}", max of "${maxEncodedParamLength}" is acceptable`) + } -/***/ 85303: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + const rOffset = offset + offset += rLength -"use strict"; + if (signature[offset++] !== ENCODED_TAG_INT) { + throw new Error('Could not find expected "int" for "s"') + } + const sLength = signature[offset++] -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.KnownDirectivesRule = KnownDirectivesRule; + if (inputLength - offset !== sLength) { + throw new Error(`"s" specified length of "${sLength}", expected "${inputLength - offset}"`) + } -var _inspect = __nccwpck_require__(10102); + if (maxEncodedParamLength < sLength) { + throw new Error(`"s" specified length of "${sLength}", max of "${maxEncodedParamLength}" is acceptable`) + } -var _invariant = __nccwpck_require__(28847); + const sOffset = offset + offset += sLength -var _GraphQLError = __nccwpck_require__(4797); + if (offset !== inputLength) { + throw new Error(`Expected to consume entire buffer, but "${inputLength - offset}" bytes remain`) + } -var _ast = __nccwpck_require__(45494); + const rPadding = paramBytes - rLength -var _directiveLocation = __nccwpck_require__(71553); + const sPadding = paramBytes - sLength -var _kinds = __nccwpck_require__(11927); + const dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength) -var _directives = __nccwpck_require__(83614); + for (offset = 0; offset < rPadding; ++offset) { + dst[offset] = 0 + } + signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength) -/** - * Known directives - * - * A GraphQL document is only valid if all `@directives` are known by the - * schema and legally positioned. - * - * See https://spec.graphql.org/draft/#sec-Directives-Are-Defined - */ -function KnownDirectivesRule(context) { - const locationsMap = Object.create(null); - const schema = context.getSchema(); - const definedDirectives = schema - ? schema.getDirectives() - : _directives.specifiedDirectives; + offset = paramBytes - for (const directive of definedDirectives) { - locationsMap[directive.name] = directive.locations; + for (const o = offset; offset < o + sPadding; ++offset) { + dst[offset] = 0 } + signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength) - const astDefinitions = context.getDocument().definitions; + return dst +} - for (const def of astDefinitions) { - if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { - locationsMap[def.name.value] = def.locations.map((name) => name.value); - } +module.exports.joseToDer = (signature, alg) => { + if (!Buffer.isBuffer(signature)) { + throw new TypeError('ECDSA signature must be a Buffer') } - return { - Directive(node, _key, _parent, _path, ancestors) { - const name = node.name.value; - const locations = locationsMap[name]; + if (!paramBytesForAlg[alg]) { + throw new TypeError(`Unknown algorithm "${alg}"`) + } - if (!locations) { - context.reportError( - new _GraphQLError.GraphQLError(`Unknown directive "@${name}".`, { - nodes: node, - }), - ); - return; - } + const paramBytes = paramBytesForAlg[alg] - const candidateLocation = getDirectiveLocationForASTPath(ancestors); + const signatureBytes = signature.length + if (signatureBytes !== paramBytes * 2) { + throw new Error(`"${alg}" signatures must be "${paramBytes * 2}" bytes, saw "${signatureBytes}"`) + } - if (candidateLocation && !locations.includes(candidateLocation)) { - context.reportError( - new _GraphQLError.GraphQLError( - `Directive "@${name}" may not be used on ${candidateLocation}.`, - { - nodes: node, - }, - ), - ); - } - }, - }; -} + const rPadding = countPadding(signature, 0, paramBytes) + const sPadding = countPadding(signature, paramBytes, signature.length) + const rLength = paramBytes - rPadding + const sLength = paramBytes - sPadding -function getDirectiveLocationForASTPath(ancestors) { - const appliedTo = ancestors[ancestors.length - 1]; - 'kind' in appliedTo || (0, _invariant.invariant)(false); + const rsBytes = 1 + 1 + rLength + 1 + 1 + sLength - switch (appliedTo.kind) { - case _kinds.Kind.OPERATION_DEFINITION: - return getDirectiveLocationForOperation(appliedTo.operation); + const shortLength = rsBytes < MAX_OCTET - case _kinds.Kind.FIELD: - return _directiveLocation.DirectiveLocation.FIELD; + const dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes) - case _kinds.Kind.FRAGMENT_SPREAD: - return _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD; + let offset = 0 + dst[offset++] = ENCODED_TAG_SEQ + if (shortLength) { + // Bit 8 has value "0" + // bits 7-1 give the length. + dst[offset++] = rsBytes + } else { + // Bit 8 of first octet has value "1" + // bits 7-1 give the number of additional length octets. + dst[offset++] = MAX_OCTET | 1 // eslint-disable-line no-tabs + // length, base 256 + dst[offset++] = rsBytes & 0xff + } + dst[offset++] = ENCODED_TAG_INT + dst[offset++] = rLength + if (rPadding < 0) { + dst[offset++] = 0 + offset += signature.copy(dst, offset, 0, paramBytes) + } else { + offset += signature.copy(dst, offset, rPadding, paramBytes) + } + dst[offset++] = ENCODED_TAG_INT + dst[offset++] = sLength + if (sPadding < 0) { + dst[offset++] = 0 + signature.copy(dst, offset, paramBytes) + } else { + signature.copy(dst, offset, paramBytes + sPadding) + } - case _kinds.Kind.INLINE_FRAGMENT: - return _directiveLocation.DirectiveLocation.INLINE_FRAGMENT; + return dst +} - case _kinds.Kind.FRAGMENT_DEFINITION: - return _directiveLocation.DirectiveLocation.FRAGMENT_DEFINITION; - case _kinds.Kind.VARIABLE_DEFINITION: - return _directiveLocation.DirectiveLocation.VARIABLE_DEFINITION; +/***/ }), - case _kinds.Kind.SCHEMA_DEFINITION: - case _kinds.Kind.SCHEMA_EXTENSION: - return _directiveLocation.DirectiveLocation.SCHEMA; +/***/ 47396: +/***/ ((module) => { - case _kinds.Kind.SCALAR_TYPE_DEFINITION: - case _kinds.Kind.SCALAR_TYPE_EXTENSION: - return _directiveLocation.DirectiveLocation.SCALAR; +module.exports = (date) => Math.floor(date.getTime() / 1000) - case _kinds.Kind.OBJECT_TYPE_DEFINITION: - case _kinds.Kind.OBJECT_TYPE_EXTENSION: - return _directiveLocation.DirectiveLocation.OBJECT; - case _kinds.Kind.FIELD_DEFINITION: - return _directiveLocation.DirectiveLocation.FIELD_DEFINITION; +/***/ }), - case _kinds.Kind.INTERFACE_TYPE_DEFINITION: - case _kinds.Kind.INTERFACE_TYPE_EXTENSION: - return _directiveLocation.DirectiveLocation.INTERFACE; +/***/ 93137: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - case _kinds.Kind.UNION_TYPE_DEFINITION: - case _kinds.Kind.UNION_TYPE_EXTENSION: - return _directiveLocation.DirectiveLocation.UNION; +const { randomBytes } = __nccwpck_require__(6113) - case _kinds.Kind.ENUM_TYPE_DEFINITION: - case _kinds.Kind.ENUM_TYPE_EXTENSION: - return _directiveLocation.DirectiveLocation.ENUM; +const { IVLENGTHS } = __nccwpck_require__(15501) - case _kinds.Kind.ENUM_VALUE_DEFINITION: - return _directiveLocation.DirectiveLocation.ENUM_VALUE; +module.exports = alg => randomBytes(IVLENGTHS.get(alg) / 8) - case _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION: - case _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION: - return _directiveLocation.DirectiveLocation.INPUT_OBJECT; - case _kinds.Kind.INPUT_VALUE_DEFINITION: { - const parentNode = ancestors[ancestors.length - 3]; - 'kind' in parentNode || (0, _invariant.invariant)(false); - return parentNode.kind === _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION - ? _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION - : _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION; - } - // Not reachable, all possible types have been considered. +/***/ }), - /* c8 ignore next */ +/***/ 31308: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - default: - false || - (0, _invariant.invariant)( - false, - 'Unexpected kind: ' + (0, _inspect.inspect)(appliedTo.kind), - ); +const errors = __nccwpck_require__(52973) +const Key = __nccwpck_require__(57841) +const importKey = __nccwpck_require__(13468) +const { KeyStore } = __nccwpck_require__(24998) + +module.exports = (input, keyStoreAllowed = false) => { + if (input instanceof Key) { + return input } -} -function getDirectiveLocationForOperation(operation) { - switch (operation) { - case _ast.OperationTypeNode.QUERY: - return _directiveLocation.DirectiveLocation.QUERY; + if (input instanceof KeyStore) { + if (!keyStoreAllowed) { + throw new TypeError('key argument for this operation must not be a JWKS.KeyStore instance') + } - case _ast.OperationTypeNode.MUTATION: - return _directiveLocation.DirectiveLocation.MUTATION; + return input + } - case _ast.OperationTypeNode.SUBSCRIPTION: - return _directiveLocation.DirectiveLocation.SUBSCRIPTION; + try { + return importKey(input) + } catch (err) { + if (err instanceof errors.JOSEError && !(err instanceof errors.JWKImportFailed)) { + throw err + } + + let msg + if (keyStoreAllowed) { + msg = 'key must be an instance of a key instantiated by JWK.asKey, a valid JWK.asKey input, or a JWKS.KeyStore instance' + } else { + msg = 'key must be an instance of a key instantiated by JWK.asKey, or a valid JWK.asKey input' + } + + throw new TypeError(msg) } } /***/ }), -/***/ 15166: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; +/***/ 29024: +/***/ ((module) => { +module.exports = (a = {}, b = {}) => { + const keysA = Object.keys(a) + const keysB = new Set(Object.keys(b)) + return !keysA.some((ka) => keysB.has(ka)) +} -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.KnownFragmentNamesRule = KnownFragmentNamesRule; -var _GraphQLError = __nccwpck_require__(4797); +/***/ }), -/** - * Known fragment names - * - * A GraphQL document is only valid if all `...Fragment` fragment spreads refer - * to fragments defined in the same document. - * - * See https://spec.graphql.org/draft/#sec-Fragment-spread-target-defined - */ -function KnownFragmentNamesRule(context) { - return { - FragmentSpread(node) { - const fragmentName = node.name.value; - const fragment = context.getFragment(fragmentName); +/***/ 41805: +/***/ ((module) => { - if (!fragment) { - context.reportError( - new _GraphQLError.GraphQLError( - `Unknown fragment "${fragmentName}".`, - { - nodes: node.name, - }, - ), - ); - } - }, - }; -} +module.exports = a => !!a && a.constructor === Object /***/ }), -/***/ 42509: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 98921: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const { keyObjectSupported } = __nccwpck_require__(32457) +let createPublicKey +let createPrivateKey +let createSecretKey +let KeyObject +let asInput -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.KnownTypeNamesRule = KnownTypeNamesRule; +if (keyObjectSupported) { + ({ createPublicKey, createPrivateKey, createSecretKey, KeyObject } = __nccwpck_require__(6113)) + asInput = (input) => input +} else { + const { EOL } = __nccwpck_require__(22037) -var _didYouMean = __nccwpck_require__(42878); + const errors = __nccwpck_require__(52973) + const isObject = __nccwpck_require__(41805) + const asn1 = __nccwpck_require__(16416) + const toInput = Symbol('toInput') -var _suggestionList = __nccwpck_require__(57704); + const namedCurve = Symbol('namedCurve') -var _GraphQLError = __nccwpck_require__(4797); + asInput = (keyObject, needsPublic) => { + if (keyObject instanceof KeyObject) { + return keyObject[toInput](needsPublic) + } -var _predicates = __nccwpck_require__(20535); + return createSecretKey(keyObject)[toInput](needsPublic) + } -var _introspection = __nccwpck_require__(28344); + const pemToDer = pem => Buffer.from(pem.replace(/(?:-----(?:BEGIN|END)(?: (?:RSA|EC))? (?:PRIVATE|PUBLIC) KEY-----|\s)/g, ''), 'base64') + const derToPem = (der, label) => `-----BEGIN ${label}-----${EOL}${(der.toString('base64').match(/.{1,64}/g) || []).join(EOL)}${EOL}-----END ${label}-----` + const unsupported = (input) => { + const label = typeof input === 'string' ? input : `OID ${input.join('.')}` + throw new errors.JOSENotSupported(`${label} is not supported in your Node.js runtime version`) + } -var _scalars = __nccwpck_require__(93145); + KeyObject = class KeyObject { + export ({ cipher, passphrase, type, format } = {}) { + if (this._type === 'secret') { + return this._buffer + } -/** - * Known type names - * - * A GraphQL document is only valid if referenced types (specifically - * variable definitions and fragment conditions) are defined by the type schema. - * - * See https://spec.graphql.org/draft/#sec-Fragment-Spread-Type-Existence - */ -function KnownTypeNamesRule(context) { - const schema = context.getSchema(); - const existingTypesMap = schema ? schema.getTypeMap() : Object.create(null); - const definedTypes = Object.create(null); + if (this._type === 'public') { + if (this.asymmetricKeyType === 'rsa') { + switch (type) { + case 'pkcs1': + if (format === 'pem') { + return this._pem + } - for (const def of context.getDocument().definitions) { - if ((0, _predicates.isTypeDefinitionNode)(def)) { - definedTypes[def.name.value] = true; - } - } + return pemToDer(this._pem) + case 'spki': { + const PublicKeyInfo = asn1.get('PublicKeyInfo') + const pem = PublicKeyInfo.encode({ + algorithm: { + algorithm: 'rsaEncryption', + parameters: { type: 'null' } + }, + publicKey: { + unused: 0, + data: pemToDer(this._pem) + } + }, 'pem', { label: 'PUBLIC KEY' }) - const typeNames = [ - ...Object.keys(existingTypesMap), - ...Object.keys(definedTypes), - ]; - return { - NamedType(node, _1, parent, _2, ancestors) { - const typeName = node.name.value; + return format === 'pem' ? pem : pemToDer(pem) + } + default: + throw new TypeError(`The value ${type} is invalid for option "type"`) + } + } - if (!existingTypesMap[typeName] && !definedTypes[typeName]) { - var _ancestors$; + if (this.asymmetricKeyType === 'ec') { + if (type !== 'spki') { + throw new TypeError(`The value ${type} is invalid for option "type"`) + } - const definitionNode = - (_ancestors$ = ancestors[2]) !== null && _ancestors$ !== void 0 - ? _ancestors$ - : parent; - const isSDL = definitionNode != null && isSDLNode(definitionNode); + if (format === 'pem') { + return this._pem + } - if (isSDL && standardTypeNames.includes(typeName)) { - return; + return pemToDer(this._pem) } - - const suggestedTypes = (0, _suggestionList.suggestionList)( - typeName, - isSDL ? standardTypeNames.concat(typeNames) : typeNames, - ); - context.reportError( - new _GraphQLError.GraphQLError( - `Unknown type "${typeName}".` + - (0, _didYouMean.didYouMean)(suggestedTypes), - { - nodes: node, - }, - ), - ); } - }, - }; -} -const standardTypeNames = [ - ..._scalars.specifiedScalarTypes, - ..._introspection.introspectionTypes, -].map((type) => type.name); + if (this._type === 'private') { + if (passphrase !== undefined || cipher !== undefined) { + throw new errors.JOSENotSupported('encrypted private keys are not supported in your Node.js runtime version') + } -function isSDLNode(value) { - return ( - 'kind' in value && - ((0, _predicates.isTypeSystemDefinitionNode)(value) || - (0, _predicates.isTypeSystemExtensionNode)(value)) - ); -} + if (type === 'pkcs8') { + if (this._pkcs8) { + if (format === 'der' && typeof this._pkcs8 === 'string') { + return pemToDer(this._pkcs8) + } + if (format === 'pem' && Buffer.isBuffer(this._pkcs8)) { + return derToPem(this._pkcs8, 'PRIVATE KEY') + } -/***/ }), + return this._pkcs8 + } -/***/ 45726: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (this.asymmetricKeyType === 'rsa') { + const parsed = this._asn1 + const RSAPrivateKey = asn1.get('RSAPrivateKey') + const privateKey = RSAPrivateKey.encode(parsed) + const PrivateKeyInfo = asn1.get('PrivateKeyInfo') + const pkcs8 = PrivateKeyInfo.encode({ + version: 0, + privateKey, + algorithm: { + algorithm: 'rsaEncryption', + parameters: { type: 'null' } + } + }) -"use strict"; + this._pkcs8 = pkcs8 + return this.export({ type, format }) + } -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.LoneAnonymousOperationRule = LoneAnonymousOperationRule; + if (this.asymmetricKeyType === 'ec') { + const parsed = this._asn1 + const ECPrivateKey = asn1.get('ECPrivateKey') + const privateKey = ECPrivateKey.encode({ + version: parsed.version, + privateKey: parsed.privateKey, + publicKey: parsed.publicKey + }) + const PrivateKeyInfo = asn1.get('PrivateKeyInfo') + const pkcs8 = PrivateKeyInfo.encode({ + version: 0, + privateKey, + algorithm: { + algorithm: 'ecPublicKey', + parameters: this._asn1.parameters + } + }) -var _GraphQLError = __nccwpck_require__(4797); + this._pkcs8 = pkcs8 -var _kinds = __nccwpck_require__(11927); + return this.export({ type, format }) + } + } -/** - * Lone anonymous operation - * - * A GraphQL document is only valid if when it contains an anonymous operation - * (the query short-hand) that it contains only that one operation definition. - * - * See https://spec.graphql.org/draft/#sec-Lone-Anonymous-Operation - */ -function LoneAnonymousOperationRule(context) { - let operationCount = 0; - return { - Document(node) { - operationCount = node.definitions.filter( - (definition) => definition.kind === _kinds.Kind.OPERATION_DEFINITION, - ).length; - }, + if (this.asymmetricKeyType === 'rsa' && type === 'pkcs1') { + if (format === 'pem') { + return this._pem + } - OperationDefinition(node) { - if (!node.name && operationCount > 1) { - context.reportError( - new _GraphQLError.GraphQLError( - 'This anonymous operation must be the only defined operation.', - { - nodes: node, - }, - ), - ); + return pemToDer(this._pem) + } else if (this.asymmetricKeyType === 'ec' && type === 'sec1') { + if (format === 'pem') { + return this._pem + } + + return pemToDer(this._pem) + } else { + throw new TypeError(`The value ${type} is invalid for option "type"`) + } } - }, - }; -} + } + get type () { + return this._type + } -/***/ }), + get asymmetricKeyType () { + return this._asymmetricKeyType + } -/***/ 48307: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + get symmetricKeySize () { + return this._symmetricKeySize + } -"use strict"; + [toInput] (needsPublic) { + switch (this._type) { + case 'secret': + return this._buffer + case 'public': + return this._pem + default: + if (needsPublic) { + if (!('_pub' in this)) { + this._pub = createPublicKey(this) + } + return this._pub[toInput](false) + } -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.LoneSchemaDefinitionRule = LoneSchemaDefinitionRule; + return this._pem + } + } + } -var _GraphQLError = __nccwpck_require__(4797); + createSecretKey = (buffer) => { + if (!Buffer.isBuffer(buffer) || !buffer.length) { + throw new TypeError('input must be a non-empty Buffer instance') + } -/** - * Lone Schema definition - * - * A GraphQL document is only valid if it contains only one schema definition. - */ -function LoneSchemaDefinitionRule(context) { - var _ref, _ref2, _oldSchema$astNode; + const keyObject = new KeyObject() + keyObject._buffer = Buffer.from(buffer) + keyObject._symmetricKeySize = buffer.length + keyObject._type = 'secret' - const oldSchema = context.getSchema(); - const alreadyDefined = - (_ref = - (_ref2 = - (_oldSchema$astNode = - oldSchema === null || oldSchema === void 0 - ? void 0 - : oldSchema.astNode) !== null && _oldSchema$astNode !== void 0 - ? _oldSchema$astNode - : oldSchema === null || oldSchema === void 0 - ? void 0 - : oldSchema.getQueryType()) !== null && _ref2 !== void 0 - ? _ref2 - : oldSchema === null || oldSchema === void 0 - ? void 0 - : oldSchema.getMutationType()) !== null && _ref !== void 0 - ? _ref - : oldSchema === null || oldSchema === void 0 - ? void 0 - : oldSchema.getSubscriptionType(); - let schemaDefinitionsCount = 0; - return { - SchemaDefinition(node) { - if (alreadyDefined) { - context.reportError( - new _GraphQLError.GraphQLError( - 'Cannot define a new schema within a schema extension.', - { - nodes: node, - }, - ), - ); - return; + return keyObject + } + + createPublicKey = (input) => { + if (input instanceof KeyObject) { + if (input.type !== 'private') { + throw new TypeError(`Invalid key object type ${input.type}, expected private.`) } - if (schemaDefinitionsCount > 0) { - context.reportError( - new _GraphQLError.GraphQLError( - 'Must provide only one schema definition.', - { - nodes: node, + switch (input.asymmetricKeyType) { + case 'ec': { + const PublicKeyInfo = asn1.get('PublicKeyInfo') + const key = PublicKeyInfo.encode({ + algorithm: { + algorithm: 'ecPublicKey', + parameters: input._asn1.parameters }, - ), - ); + publicKey: input._asn1.publicKey + }) + + return createPublicKey({ key, format: 'der', type: 'spki' }) + } + case 'rsa': { + const RSAPublicKey = asn1.get('RSAPublicKey') + const key = RSAPublicKey.encode(input._asn1) + return createPublicKey({ key, format: 'der', type: 'pkcs1' }) + } } + } - ++schemaDefinitionsCount; - }, - }; -} + if (typeof input === 'string' || Buffer.isBuffer(input)) { + input = { key: input, format: 'pem' } + } + if (!isObject(input)) { + throw new TypeError('input must be a string, Buffer or an object') + } -/***/ }), + const { format, passphrase } = input + let { key, type } = input -/***/ 53318: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (typeof key !== 'string' && !Buffer.isBuffer(key)) { + throw new TypeError('key must be a string or Buffer') + } -"use strict"; + if (format !== 'pem' && format !== 'der') { + throw new TypeError('format must be one of "pem" or "der"') + } + let label + if (format === 'pem') { + key = key.toString() + switch (key.split(/\r?\n/g)[0].toString()) { + case '-----BEGIN PUBLIC KEY-----': + type = 'spki' + label = 'PUBLIC KEY' + break + case '-----BEGIN RSA PUBLIC KEY-----': + type = 'pkcs1' + label = 'RSA PUBLIC KEY' + break + case '-----BEGIN CERTIFICATE-----': + throw new errors.JOSENotSupported('X.509 certificates are not supported in your Node.js runtime version') + case '-----BEGIN PRIVATE KEY-----': + case '-----BEGIN EC PRIVATE KEY-----': + case '-----BEGIN RSA PRIVATE KEY-----': + return createPublicKey(createPrivateKey(key)) + default: + throw new TypeError('unknown/unsupported PEM type') + } + } -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.MaxIntrospectionDepthRule = MaxIntrospectionDepthRule; + switch (type) { + case 'spki': { + const PublicKeyInfo = asn1.get('PublicKeyInfo') + const parsed = PublicKeyInfo.decode(key, format, { label }) -var _GraphQLError = __nccwpck_require__(4797); + let type, keyObject + switch (parsed.algorithm.algorithm) { + case 'ecPublicKey': { + keyObject = new KeyObject() + keyObject._asn1 = parsed + keyObject._asymmetricKeyType = 'ec' + keyObject._type = 'public' + keyObject._pem = PublicKeyInfo.encode(parsed, 'pem', { label: 'PUBLIC KEY' }) -var _kinds = __nccwpck_require__(11927); + break + } + case 'rsaEncryption': { + type = 'pkcs1' + keyObject = createPublicKey({ type, key: parsed.publicKey.data, format: 'der' }) + break + } + default: + unsupported(parsed.algorithm.algorithm) + } -const MAX_LISTS_DEPTH = 3; + return keyObject + } + case 'pkcs1': { + const RSAPublicKey = asn1.get('RSAPublicKey') + const parsed = RSAPublicKey.decode(key, format, { label }) -function MaxIntrospectionDepthRule(context) { - /** - * Counts the depth of list fields in "__Type" recursively and - * returns `true` if the limit has been reached. - */ - function checkDepth(node, visitedFragments = Object.create(null), depth = 0) { - if (node.kind === _kinds.Kind.FRAGMENT_SPREAD) { - const fragmentName = node.name.value; + // special case when private pkcs1 PEM / DER is used with createPublicKey + if (parsed.n === BigInt(0)) { + return createPublicKey(createPrivateKey({ key, format, type, passphrase })) + } - if (visitedFragments[fragmentName] === true) { - // Fragment cycles are handled by `NoFragmentCyclesRule`. - return false; + const keyObject = new KeyObject() + keyObject._asn1 = parsed + keyObject._asymmetricKeyType = 'rsa' + keyObject._type = 'public' + keyObject._pem = RSAPublicKey.encode(parsed, 'pem', { label: 'RSA PUBLIC KEY' }) + + return keyObject } + case 'pkcs8': + case 'sec1': + return createPublicKey(createPrivateKey({ format, key, type, passphrase })) + default: + throw new TypeError(`The value ${type} is invalid for option "type"`) + } + } - const fragment = context.getFragment(fragmentName); + createPrivateKey = (input, hints) => { + if (typeof input === 'string' || Buffer.isBuffer(input)) { + input = { key: input, format: 'pem' } + } - if (!fragment) { - // Missing fragments checks are handled by `KnownFragmentNamesRule`. - return false; - } // Rather than following an immutable programming pattern which has - // significant memory and garbage collection overhead, we've opted to - // take a mutable approach for efficiency's sake. Importantly visiting a - // fragment twice is fine, so long as you don't do one visit inside the - // other. + if (!isObject(input)) { + throw new TypeError('input must be a string, Buffer or an object') + } + + const { format, passphrase } = input + let { key, type } = input + + if (typeof key !== 'string' && !Buffer.isBuffer(key)) { + throw new TypeError('key must be a string or Buffer') + } + + if (passphrase !== undefined) { + throw new errors.JOSENotSupported('encrypted private keys are not supported in your Node.js runtime version') + } + + if (format !== 'pem' && format !== 'der') { + throw new TypeError('format must be one of "pem" or "der"') + } + + let label + if (format === 'pem') { + key = key.toString() + switch (key.split(/\r?\n/g)[0].toString()) { + case '-----BEGIN PRIVATE KEY-----': + type = 'pkcs8' + label = 'PRIVATE KEY' + break + case '-----BEGIN EC PRIVATE KEY-----': + type = 'sec1' + label = 'EC PRIVATE KEY' + break + case '-----BEGIN RSA PRIVATE KEY-----': + type = 'pkcs1' + label = 'RSA PRIVATE KEY' + break + default: + throw new TypeError('unknown/unsupported PEM type') + } + } + + switch (type) { + case 'pkcs8': { + const PrivateKeyInfo = asn1.get('PrivateKeyInfo') + const parsed = PrivateKeyInfo.decode(key, format, { label }) + + let type, keyObject + switch (parsed.algorithm.algorithm) { + case 'ecPublicKey': { + type = 'sec1' + keyObject = createPrivateKey({ type, key: parsed.privateKey, format: 'der' }, { [namedCurve]: parsed.algorithm.parameters.value }) + break + } + case 'rsaEncryption': { + type = 'pkcs1' + keyObject = createPrivateKey({ type, key: parsed.privateKey, format: 'der' }) + break + } + default: + unsupported(parsed.algorithm.algorithm) + } - try { - visitedFragments[fragmentName] = true; - return checkDepth(fragment, visitedFragments, depth); - } finally { - visitedFragments[fragmentName] = undefined; + keyObject._pkcs8 = key + return keyObject } - } + case 'pkcs1': { + const RSAPrivateKey = asn1.get('RSAPrivateKey') + const parsed = RSAPrivateKey.decode(key, format, { label }) - if ( - node.kind === _kinds.Kind.FIELD && // check all introspection lists - (node.name.value === 'fields' || - node.name.value === 'interfaces' || - node.name.value === 'possibleTypes' || - node.name.value === 'inputFields') - ) { - // eslint-disable-next-line no-param-reassign - depth++; + const keyObject = new KeyObject() + keyObject._asn1 = parsed + keyObject._asymmetricKeyType = 'rsa' + keyObject._type = 'private' + keyObject._pem = RSAPrivateKey.encode(parsed, 'pem', { label: 'RSA PRIVATE KEY' }) - if (depth >= MAX_LISTS_DEPTH) { - return true; + return keyObject } - } // handles fields and inline fragments + case 'sec1': { + const ECPrivateKey = asn1.get('ECPrivateKey') + let parsed = ECPrivateKey.decode(key, format, { label }) - if ('selectionSet' in node && node.selectionSet) { - for (const child of node.selectionSet.selections) { - if (checkDepth(child, visitedFragments, depth)) { - return true; + if (!('parameters' in parsed) && !hints[namedCurve]) { + throw new Error('invalid sec1') + } else if (!('parameters' in parsed)) { + parsed = { ...parsed, parameters: { type: 'namedCurve', value: hints[namedCurve] } } } - } - } - return false; - } + const keyObject = new KeyObject() + keyObject._asn1 = parsed + keyObject._asymmetricKeyType = 'ec' + keyObject._type = 'private' + keyObject._pem = ECPrivateKey.encode(parsed, 'pem', { label: 'EC PRIVATE KEY' }) - return { - Field(node) { - if (node.name.value === '__schema' || node.name.value === '__type') { - if (checkDepth(node)) { - context.reportError( - new _GraphQLError.GraphQLError( - 'Maximum introspection depth exceeded', - { - nodes: [node], - }, - ), - ); - return false; - } + return keyObject } - }, - }; + default: + throw new TypeError(`The value ${type} is invalid for option "type"`) + } + } } +module.exports = { createPublicKey, createPrivateKey, createSecretKey, KeyObject, asInput } + /***/ }), -/***/ 62564: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 69693: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const { EOL } = __nccwpck_require__(22037) +const errors = __nccwpck_require__(52973) -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.NoFragmentCyclesRule = NoFragmentCyclesRule; +const { keyObjectSupported } = __nccwpck_require__(32457) +const { createPublicKey } = __nccwpck_require__(98921) +const base64url = __nccwpck_require__(73385) +const asn1 = __nccwpck_require__(16416) +const computePrimes = __nccwpck_require__(53141) +const { OKP_CURVES, EC_CURVES } = __nccwpck_require__(15501) -var _GraphQLError = __nccwpck_require__(4797); +const formatPem = (base64pem, descriptor) => `-----BEGIN ${descriptor} KEY-----${EOL}${(base64pem.match(/.{1,64}/g) || []).join(EOL)}${EOL}-----END ${descriptor} KEY-----` -/** - * No fragment cycles - * - * The graph of fragment spreads must not form any cycles including spreading itself. - * Otherwise an operation could infinitely spread or infinitely execute on cycles in the underlying data. - * - * See https://spec.graphql.org/draft/#sec-Fragment-spreads-must-not-form-cycles - */ -function NoFragmentCyclesRule(context) { - // Tracks already visited fragments to maintain O(N) and to ensure that cycles - // are not redundantly reported. - const visitedFrags = Object.create(null); // Array of AST nodes used to produce meaningful errors +const okpToJWK = { + private (crv, keyObject) { + const der = keyObject.export({ type: 'pkcs8', format: 'der' }) + const OneAsymmetricKey = asn1.get('OneAsymmetricKey') + const { privateKey: { privateKey: d } } = OneAsymmetricKey.decode(der) - const spreadPath = []; // Position in the spread path + return { + ...okpToJWK.public(crv, createPublicKey(keyObject)), + d: base64url.encodeBuffer(d) + } + }, + public (crv, keyObject) { + const der = keyObject.export({ type: 'spki', format: 'der' }) - const spreadPathIndexByName = Object.create(null); - return { - OperationDefinition: () => false, + const PublicKeyInfo = asn1.get('PublicKeyInfo') - FragmentDefinition(node) { - detectCycleRecursive(node); - return false; - }, - }; // This does a straight-forward DFS to find cycles. - // It does not terminate when a cycle was found but continues to explore - // the graph to find all possible cycles. + const { publicKey: { data: x } } = PublicKeyInfo.decode(der) - function detectCycleRecursive(fragment) { - if (visitedFrags[fragment.name.value]) { - return; + return { + kty: 'OKP', + crv, + x: base64url.encodeBuffer(x) } + } +} - const fragmentName = fragment.name.value; - visitedFrags[fragmentName] = true; - const spreadNodes = context.getFragmentSpreads(fragment.selectionSet); - - if (spreadNodes.length === 0) { - return; - } +const keyObjectToJWK = { + rsa: { + private (keyObject) { + const der = keyObject.export({ type: 'pkcs8', format: 'der' }) - spreadPathIndexByName[fragmentName] = spreadPath.length; + const PrivateKeyInfo = asn1.get('PrivateKeyInfo') + const RSAPrivateKey = asn1.get('RSAPrivateKey') - for (const spreadNode of spreadNodes) { - const spreadName = spreadNode.name.value; - const cycleIndex = spreadPathIndexByName[spreadName]; - spreadPath.push(spreadNode); + const { privateKey } = PrivateKeyInfo.decode(der) + const { version, n, e, d, p, q, dp, dq, qi } = RSAPrivateKey.decode(privateKey) - if (cycleIndex === undefined) { - const spreadFragment = context.getFragment(spreadName); + if (version !== 'two-prime') { + throw new errors.JOSENotSupported('Private RSA keys with more than two primes are not supported') + } - if (spreadFragment) { - detectCycleRecursive(spreadFragment); - } - } else { - const cyclePath = spreadPath.slice(cycleIndex); - const viaPath = cyclePath - .slice(0, -1) - .map((s) => '"' + s.name.value + '"') - .join(', '); - context.reportError( - new _GraphQLError.GraphQLError( - `Cannot spread fragment "${spreadName}" within itself` + - (viaPath !== '' ? ` via ${viaPath}.` : '.'), - { - nodes: cyclePath, - }, - ), - ); + return { + kty: 'RSA', + n: base64url.encodeBigInt(n), + e: base64url.encodeBigInt(e), + d: base64url.encodeBigInt(d), + p: base64url.encodeBigInt(p), + q: base64url.encodeBigInt(q), + dp: base64url.encodeBigInt(dp), + dq: base64url.encodeBigInt(dq), + qi: base64url.encodeBigInt(qi) } + }, + public (keyObject) { + const der = keyObject.export({ type: 'spki', format: 'der' }) - spreadPath.pop(); - } + const PublicKeyInfo = asn1.get('PublicKeyInfo') + const RSAPublicKey = asn1.get('RSAPublicKey') - spreadPathIndexByName[fragmentName] = undefined; - } -} + const { publicKey: { data: publicKey } } = PublicKeyInfo.decode(der) + const { n, e } = RSAPublicKey.decode(publicKey) + return { + kty: 'RSA', + n: base64url.encodeBigInt(n), + e: base64url.encodeBigInt(e) + } + } + }, + ec: { + private (keyObject) { + const der = keyObject.export({ type: 'pkcs8', format: 'der' }) -/***/ }), + const PrivateKeyInfo = asn1.get('PrivateKeyInfo') + const ECPrivateKey = asn1.get('ECPrivateKey') -/***/ 61671: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + const { privateKey, algorithm: { parameters: { value: crv } } } = PrivateKeyInfo.decode(der) + const { privateKey: d, publicKey } = ECPrivateKey.decode(privateKey) -"use strict"; + if (typeof publicKey === 'undefined') { + if (keyObjectSupported) { + return { + ...keyObjectToJWK.ec.public(createPublicKey(keyObject)), + d: base64url.encodeBuffer(d) + } + } + throw new errors.JOSENotSupported('Private EC keys without the public key embedded are not supported in your Node.js runtime version') + } -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.NoUndefinedVariablesRule = NoUndefinedVariablesRule; + const x = publicKey.data.slice(1, ((publicKey.data.length - 1) / 2) + 1) + const y = publicKey.data.slice(((publicKey.data.length - 1) / 2) + 1) -var _GraphQLError = __nccwpck_require__(4797); + return { + kty: 'EC', + crv, + d: base64url.encodeBuffer(d), + x: base64url.encodeBuffer(x), + y: base64url.encodeBuffer(y) + } + }, + public (keyObject) { + const der = keyObject.export({ type: 'spki', format: 'der' }) -/** - * No undefined variables - * - * A GraphQL operation is only valid if all variables encountered, both directly - * and via fragment spreads, are defined by that operation. - * - * See https://spec.graphql.org/draft/#sec-All-Variable-Uses-Defined - */ -function NoUndefinedVariablesRule(context) { - let variableNameDefined = Object.create(null); - return { - OperationDefinition: { - enter() { - variableNameDefined = Object.create(null); - }, + const PublicKeyInfo = asn1.get('PublicKeyInfo') - leave(operation) { - const usages = context.getRecursiveVariableUsages(operation); + const { publicKey: { data: publicKey }, algorithm: { parameters: { value: crv } } } = PublicKeyInfo.decode(der) - for (const { node } of usages) { - const varName = node.name.value; + const x = publicKey.slice(1, ((publicKey.length - 1) / 2) + 1) + const y = publicKey.slice(((publicKey.length - 1) / 2) + 1) - if (variableNameDefined[varName] !== true) { - context.reportError( - new _GraphQLError.GraphQLError( - operation.name - ? `Variable "$${varName}" is not defined by operation "${operation.name.value}".` - : `Variable "$${varName}" is not defined.`, - { - nodes: [node, operation], - }, - ), - ); - } - } - }, + return { + kty: 'EC', + crv, + x: base64url.encodeBuffer(x), + y: base64url.encodeBuffer(y) + } + } + }, + ed25519: { + private (keyObject) { + return okpToJWK.private('Ed25519', keyObject) }, - - VariableDefinition(node) { - variableNameDefined[node.variable.name.value] = true; + public (keyObject) { + return okpToJWK.public('Ed25519', keyObject) + } + }, + ed448: { + private (keyObject) { + return okpToJWK.private('Ed448', keyObject) }, - }; + public (keyObject) { + return okpToJWK.public('Ed448', keyObject) + } + }, + x25519: { + private (keyObject) { + return okpToJWK.private('X25519', keyObject) + }, + public (keyObject) { + return okpToJWK.public('X25519', keyObject) + } + }, + x448: { + private (keyObject) { + return okpToJWK.private('X448', keyObject) + }, + public (keyObject) { + return okpToJWK.public('X448', keyObject) + } + } } +module.exports.keyObjectToJWK = (keyObject) => { + if (keyObject.type === 'private') { + return keyObjectToJWK[keyObject.asymmetricKeyType].private(keyObject) + } -/***/ }), - -/***/ 192: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return keyObjectToJWK[keyObject.asymmetricKeyType].public(keyObject) +} -"use strict"; +const concatEcPublicKey = (x, y) => ({ + unused: 0, + data: Buffer.concat([ + Buffer.alloc(1, 4), + base64url.decodeToBuffer(x), + base64url.decodeToBuffer(y) + ]) +}) +const jwkToPem = { + RSA: { + private (jwk, { calculateMissingRSAPrimes }) { + const RSAPrivateKey = asn1.get('RSAPrivateKey') -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.NoUnusedFragmentsRule = NoUnusedFragmentsRule; + if ('oth' in jwk) { + throw new errors.JOSENotSupported('Private RSA keys with more than two primes are not supported') + } -var _GraphQLError = __nccwpck_require__(4797); + if (jwk.p || jwk.q || jwk.dp || jwk.dq || jwk.qi) { + if (!(jwk.p && jwk.q && jwk.dp && jwk.dq && jwk.qi)) { + throw new errors.JWKInvalid('all other private key parameters must be present when any one of them is present') + } + } else if (calculateMissingRSAPrimes) { + jwk = computePrimes(jwk) + } else if (!calculateMissingRSAPrimes) { + throw new errors.JOSENotSupported('importing private RSA keys without all other private key parameters is not enabled, see documentation and its advisory on how and when its ok to enable it') + } -/** - * No unused fragments - * - * A GraphQL document is only valid if all fragment definitions are spread - * within operations, or spread within other fragments spread within operations. - * - * See https://spec.graphql.org/draft/#sec-Fragments-Must-Be-Used - */ -function NoUnusedFragmentsRule(context) { - const operationDefs = []; - const fragmentDefs = []; - return { - OperationDefinition(node) { - operationDefs.push(node); - return false; + return RSAPrivateKey.encode({ + version: 0, + n: BigInt(`0x${base64url.decodeToBuffer(jwk.n).toString('hex')}`), + e: BigInt(`0x${base64url.decodeToBuffer(jwk.e).toString('hex')}`), + d: BigInt(`0x${base64url.decodeToBuffer(jwk.d).toString('hex')}`), + p: BigInt(`0x${base64url.decodeToBuffer(jwk.p).toString('hex')}`), + q: BigInt(`0x${base64url.decodeToBuffer(jwk.q).toString('hex')}`), + dp: BigInt(`0x${base64url.decodeToBuffer(jwk.dp).toString('hex')}`), + dq: BigInt(`0x${base64url.decodeToBuffer(jwk.dq).toString('hex')}`), + qi: BigInt(`0x${base64url.decodeToBuffer(jwk.qi).toString('hex')}`) + }, 'pem', { label: 'RSA PRIVATE KEY' }) }, + public (jwk) { + const RSAPublicKey = asn1.get('RSAPublicKey') - FragmentDefinition(node) { - fragmentDefs.push(node); - return false; + return RSAPublicKey.encode({ + version: 0, + n: BigInt(`0x${base64url.decodeToBuffer(jwk.n).toString('hex')}`), + e: BigInt(`0x${base64url.decodeToBuffer(jwk.e).toString('hex')}`) + }, 'pem', { label: 'RSA PUBLIC KEY' }) + } + }, + EC: { + private (jwk) { + const ECPrivateKey = asn1.get('ECPrivateKey') + + return ECPrivateKey.encode({ + version: 1, + privateKey: base64url.decodeToBuffer(jwk.d), + parameters: { type: 'namedCurve', value: jwk.crv }, + publicKey: concatEcPublicKey(jwk.x, jwk.y) + }, 'pem', { label: 'EC PRIVATE KEY' }) }, + public (jwk) { + const PublicKeyInfo = asn1.get('PublicKeyInfo') - Document: { - leave() { - const fragmentNameUsed = Object.create(null); + return PublicKeyInfo.encode({ + algorithm: { + algorithm: 'ecPublicKey', + parameters: { type: 'namedCurve', value: jwk.crv } + }, + publicKey: concatEcPublicKey(jwk.x, jwk.y) + }, 'pem', { label: 'PUBLIC KEY' }) + } + }, + OKP: { + private (jwk) { + const OneAsymmetricKey = asn1.get('OneAsymmetricKey') - for (const operation of operationDefs) { - for (const fragment of context.getRecursivelyReferencedFragments( - operation, - )) { - fragmentNameUsed[fragment.name.value] = true; - } - } + const b64 = OneAsymmetricKey.encode({ + version: 0, + privateKey: { privateKey: base64url.decodeToBuffer(jwk.d) }, + algorithm: { algorithm: jwk.crv } + }, 'der') - for (const fragmentDef of fragmentDefs) { - const fragName = fragmentDef.name.value; + // TODO: WHYYY? https://github.com/indutny/asn1.js/issues/110 + b64.write('04', 12, 1, 'hex') - if (fragmentNameUsed[fragName] !== true) { - context.reportError( - new _GraphQLError.GraphQLError( - `Fragment "${fragName}" is never used.`, - { - nodes: fragmentDef, - }, - ), - ); - } - } - }, + return formatPem(b64.toString('base64'), 'PRIVATE') }, - }; + public (jwk) { + const PublicKeyInfo = asn1.get('PublicKeyInfo') + + return PublicKeyInfo.encode({ + algorithm: { algorithm: jwk.crv }, + publicKey: { + unused: 0, + data: base64url.decodeToBuffer(jwk.x) + } + }, 'pem', { label: 'PUBLIC KEY' }) + } + } +} + +module.exports.jwkToPem = (jwk, { calculateMissingRSAPrimes = false } = {}) => { + switch (jwk.kty) { + case 'EC': + if (!EC_CURVES.has(jwk.crv)) { + throw new errors.JOSENotSupported(`unsupported EC key curve: ${jwk.crv}`) + } + break + case 'OKP': + if (!OKP_CURVES.has(jwk.crv)) { + throw new errors.JOSENotSupported(`unsupported OKP key curve: ${jwk.crv}`) + } + break + case 'RSA': + break + default: + throw new errors.JOSENotSupported(`unsupported key type: ${jwk.kty}`) + } + + if (jwk.d) { + return jwkToPem[jwk.kty].private(jwk, { calculateMissingRSAPrimes }) + } + + return jwkToPem[jwk.kty].public(jwk) } /***/ }), -/***/ 40242: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 20125: +/***/ ((module) => { -"use strict"; +module.exports = alg => `sha${alg.substr(2, 3)}` -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.NoUnusedVariablesRule = NoUnusedVariablesRule; +/***/ }), -var _GraphQLError = __nccwpck_require__(4797); +/***/ 53141: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * No unused variables - * - * A GraphQL operation is only valid if all variables defined by an operation - * are used, either directly or within a spread fragment. - * - * See https://spec.graphql.org/draft/#sec-All-Variables-Used - */ -function NoUnusedVariablesRule(context) { - let variableDefs = []; - return { - OperationDefinition: { - enter() { - variableDefs = []; - }, +const { randomBytes } = __nccwpck_require__(6113) - leave(operation) { - const variableNameUsed = Object.create(null); - const usages = context.getRecursiveVariableUsages(operation); +const base64url = __nccwpck_require__(73385) +const errors = __nccwpck_require__(52973) - for (const { node } of usages) { - variableNameUsed[node.name.value] = true; - } +const ZERO = BigInt(0) +const ONE = BigInt(1) +const TWO = BigInt(2) - for (const variableDef of variableDefs) { - const variableName = variableDef.variable.name.value; +const toJWKParameter = (n) => { + const hex = n.toString(16) + return base64url.encodeBuffer(Buffer.from(hex.length % 2 ? `0${hex}` : hex, 'hex')) +} +const fromBuffer = buf => BigInt(`0x${buf.toString('hex')}`) +const bitLength = n => n.toString(2).length - if (variableNameUsed[variableName] !== true) { - context.reportError( - new _GraphQLError.GraphQLError( - operation.name - ? `Variable "$${variableName}" is never used in operation "${operation.name.value}".` - : `Variable "$${variableName}" is never used.`, - { - nodes: variableDef, - }, - ), - ); - } - } - }, - }, +const eGcdX = (a, b) => { + let x = ZERO + let y = ONE + let u = ONE + let v = ZERO - VariableDefinition(def) { - variableDefs.push(def); - }, - }; + while (a !== ZERO) { + const q = b / a + const r = b % a + const m = x - (u * q) + const n = y - (v * q) + b = a + a = r + x = u + y = v + u = m + v = n + } + return x } +const gcd = (a, b) => { + let shift = ZERO + while (!((a | b) & ONE)) { + a >>= ONE + b >>= ONE + shift++ + } + while (!(a & ONE)) { + a >>= ONE + } + do { + while (!(b & ONE)) { + b >>= ONE + } + if (a > b) { + const x = a + a = b + b = x + } + b -= a + } while (b) -/***/ }), + return a << shift +} -/***/ 23577: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +const modPow = (a, b, n) => { + a = toZn(a, n) + let result = ONE + let x = a + while (b > 0) { + const leastSignificantBit = b % TWO + b = b / TWO + if (leastSignificantBit === ONE) { + result = result * x + result = result % n + } + x = x * x + x = x % n + } + return result +} -"use strict"; +const randBetween = (min, max) => { + const interval = max - min + const bitLen = bitLength(interval) + let rnd + do { + rnd = fromBuffer(randBits(bitLen)) + } while (rnd > interval) + return rnd + min +} +const randBits = (bitLength) => { + const byteLength = Math.ceil(bitLength / 8) + const rndBytes = randomBytes(byteLength) + // Fill with 0's the extra bits + rndBytes[0] = rndBytes[0] & (2 ** (bitLength % 8) - 1) + return rndBytes +} -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.OverlappingFieldsCanBeMergedRule = OverlappingFieldsCanBeMergedRule; +const toZn = (a, n) => { + a = a % n + return (a < 0) ? a + n : a +} -var _inspect = __nccwpck_require__(10102); +const odd = (n) => { + let r = n + while (r % TWO === ZERO) { + r = r / TWO + } + return r +} -var _GraphQLError = __nccwpck_require__(4797); +// not sold on these values +const maxCountWhileNoY = 30 +const maxCountWhileInot0 = 22 -var _kinds = __nccwpck_require__(11927); +const getPrimeFactors = (e, d, n) => { + const r = odd(e * d - ONE) -var _printer = __nccwpck_require__(68203); + let countWhileNoY = 0 + let y + do { + countWhileNoY++ + if (countWhileNoY === maxCountWhileNoY) { + throw new errors.JWKImportFailed('failed to calculate missing primes') + } -var _definition = __nccwpck_require__(32150); + let countWhileInot0 = 0 + let i = modPow(randBetween(TWO, n), r, n) + let o = ZERO + while (i !== ONE) { + countWhileInot0++ + if (countWhileInot0 === maxCountWhileInot0) { + throw new errors.JWKImportFailed('failed to calculate missing primes') + } + o = i + i = (i * i) % n + } + if (o !== (n - ONE)) { + y = o + } + } while (!y) -var _sortValueNode = __nccwpck_require__(82278); + const p = gcd(y - ONE, n) + const q = n / p -var _typeFromAST = __nccwpck_require__(27664); + return p > q ? { p, q } : { p: q, q: p } +} -function reasonMessage(reason) { - if (Array.isArray(reason)) { - return reason - .map( - ([responseName, subReason]) => - `subfields "${responseName}" conflict because ` + - reasonMessage(subReason), - ) - .join(' and '); +module.exports = (jwk) => { + const e = fromBuffer(base64url.decodeToBuffer(jwk.e)) + const d = fromBuffer(base64url.decodeToBuffer(jwk.d)) + const n = fromBuffer(base64url.decodeToBuffer(jwk.n)) + + if (d >= n) { + throw new errors.JWKInvalid('invalid RSA private exponent') } - return reason; + const { p, q } = getPrimeFactors(e, d, n) + const dp = d % (p - ONE) + const dq = d % (q - ONE) + const qi = toZn(eGcdX(toZn(q, p), p), p) + + return { + ...jwk, + p: toJWKParameter(p), + q: toJWKParameter(q), + dp: toJWKParameter(dp), + dq: toJWKParameter(dq), + qi: toJWKParameter(qi) + } } -/** - * Overlapping fields can be merged - * - * A selection set is only valid if all fields (including spreading any - * fragments) either correspond to distinct response names or can be merged - * without ambiguity. - * - * See https://spec.graphql.org/draft/#sec-Field-Selection-Merging - */ -function OverlappingFieldsCanBeMergedRule(context) { - // A memoization for when fields and a fragment or two fragments are compared - // "between" each other for conflicts. Comparisons made be made many times, - // so memoizing this can dramatically improve the performance of this validator. - const comparedFieldsAndFragmentPairs = new OrderedPairSet(); - const comparedFragmentPairs = new PairSet(); // A cache for the "field map" and list of fragment names found in any given - // selection set. Selection sets may be asked for this information multiple - // times, so this improves the performance of this validator. - const cachedFieldsAndFragmentNames = new Map(); - return { - SelectionSet(selectionSet) { - const conflicts = findConflictsWithinSelectionSet( - context, - cachedFieldsAndFragmentNames, - comparedFieldsAndFragmentPairs, - comparedFragmentPairs, - context.getParentType(), - selectionSet, - ); +/***/ }), - for (const [[responseName, reason], fields1, fields2] of conflicts) { - const reasonMsg = reasonMessage(reason); - context.reportError( - new _GraphQLError.GraphQLError( - `Fields "${responseName}" conflict because ${reasonMsg}. Use different aliases on the fields to fetch both if this was intentional.`, - { - nodes: fields1.concat(fields2), - }, - ), - ); - } - }, - }; +/***/ 32457: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const { diffieHellman, KeyObject, sign, verify } = __nccwpck_require__(6113) + +const [major, minor] = process.version.substr(1).split('.').map(x => parseInt(x, 10)) + +module.exports = { + oaepHashSupported: major > 12 || (major === 12 && minor >= 9), + keyObjectSupported: !!KeyObject && major >= 12, + edDSASupported: !!sign && !!verify, + dsaEncodingSupported: major > 13 || (major === 13 && minor >= 2) || (major === 12 && minor >= 16), + improvedDH: !!diffieHellman } -/** - * Algorithm: - * - * Conflicts occur when two fields exist in a query which will produce the same - * response name, but represent differing values, thus creating a conflict. - * The algorithm below finds all conflicts via making a series of comparisons - * between fields. In order to compare as few fields as possible, this makes - * a series of comparisons "within" sets of fields and "between" sets of fields. - * - * Given any selection set, a collection produces both a set of fields by - * also including all inline fragments, as well as a list of fragments - * referenced by fragment spreads. - * - * A) Each selection set represented in the document first compares "within" its - * collected set of fields, finding any conflicts between every pair of - * overlapping fields. - * Note: This is the *only time* that a the fields "within" a set are compared - * to each other. After this only fields "between" sets are compared. - * - * B) Also, if any fragment is referenced in a selection set, then a - * comparison is made "between" the original set of fields and the - * referenced fragment. - * - * C) Also, if multiple fragments are referenced, then comparisons - * are made "between" each referenced fragment. - * - * D) When comparing "between" a set of fields and a referenced fragment, first - * a comparison is made between each field in the original set of fields and - * each field in the the referenced set of fields. - * - * E) Also, if any fragment is referenced in the referenced selection set, - * then a comparison is made "between" the original set of fields and the - * referenced fragment (recursively referring to step D). - * - * F) When comparing "between" two fragments, first a comparison is made between - * each field in the first referenced set of fields and each field in the the - * second referenced set of fields. - * - * G) Also, any fragments referenced by the first must be compared to the - * second, and any fragments referenced by the second must be compared to the - * first (recursively referring to step F). - * - * H) When comparing two fields, if both have selection sets, then a comparison - * is made "between" both selection sets, first comparing the set of fields in - * the first selection set with the set of fields in the second. - * - * I) Also, if any fragment is referenced in either selection set, then a - * comparison is made "between" the other set of fields and the - * referenced fragment. - * - * J) Also, if two fragments are referenced in both selection sets, then a - * comparison is made "between" the two fragments. - * - */ -// Find all conflicts found "within" a selection set, including those found -// via spreading in fragments. Called when visiting each SelectionSet in the -// GraphQL Document. -function findConflictsWithinSelectionSet( - context, - cachedFieldsAndFragmentNames, - comparedFieldsAndFragmentPairs, - comparedFragmentPairs, - parentType, - selectionSet, -) { - const conflicts = []; - const [fieldMap, fragmentNames] = getFieldsAndFragmentNames( - context, - cachedFieldsAndFragmentNames, - parentType, - selectionSet, - ); // (A) Find find all conflicts "within" the fields of this selection set. - // Note: this is the *only place* `collectConflictsWithin` is called. - collectConflictsWithin( - context, - conflicts, - cachedFieldsAndFragmentNames, - comparedFieldsAndFragmentPairs, - comparedFragmentPairs, - fieldMap, - ); +/***/ }), - if (fragmentNames.length !== 0) { - // (B) Then collect conflicts between these fields and those represented by - // each spread fragment name found. - for (let i = 0; i < fragmentNames.length; i++) { - collectConflictsBetweenFieldsAndFragment( - context, - conflicts, - cachedFieldsAndFragmentNames, - comparedFieldsAndFragmentPairs, - comparedFragmentPairs, - false, - fieldMap, - fragmentNames[i], - ); // (C) Then compare this fragment with all other fragments found in this - // selection set to collect conflicts between fragments spread together. - // This compares each item in the list of fragment names to every other - // item in that same list (except for itself). +/***/ 97305: +/***/ ((module) => { - for (let j = i + 1; j < fragmentNames.length; j++) { - collectConflictsBetweenFragments( - context, - conflicts, - cachedFieldsAndFragmentNames, - comparedFieldsAndFragmentPairs, - comparedFragmentPairs, - false, - fragmentNames[i], - fragmentNames[j], - ); - } - } - } +const minute = 60 +const hour = minute * 60 +const day = hour * 24 +const week = day * 7 +const year = day * 365.25 - return conflicts; -} // Collect all conflicts found between a set of fields and a fragment reference -// including via spreading in any nested fragments. +const REGEX = /^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i -function collectConflictsBetweenFieldsAndFragment( - context, - conflicts, - cachedFieldsAndFragmentNames, - comparedFieldsAndFragmentPairs, - comparedFragmentPairs, - areMutuallyExclusive, - fieldMap, - fragmentName, -) { - // Memoize so the fields and fragments are not compared for conflicts more - // than once. - if ( - comparedFieldsAndFragmentPairs.has( - fieldMap, - fragmentName, - areMutuallyExclusive, - ) - ) { - return; +module.exports = (str) => { + const matched = REGEX.exec(str) + + if (!matched) { + throw new TypeError(`invalid time period format ("${str}")`) } - comparedFieldsAndFragmentPairs.add( - fieldMap, - fragmentName, - areMutuallyExclusive, - ); - const fragment = context.getFragment(fragmentName); + const value = parseFloat(matched[1]) + const unit = matched[2].toLowerCase() - if (!fragment) { - return; + switch (unit) { + case 'sec': + case 'secs': + case 'second': + case 'seconds': + case 's': + return Math.round(value) + case 'minute': + case 'minutes': + case 'min': + case 'mins': + case 'm': + return Math.round(value * minute) + case 'hour': + case 'hours': + case 'hr': + case 'hrs': + case 'h': + return Math.round(value * hour) + case 'day': + case 'days': + case 'd': + return Math.round(value * day) + case 'week': + case 'weeks': + case 'w': + return Math.round(value * week) + case 'year': + case 'years': + case 'yr': + case 'yrs': + case 'y': + return Math.round(value * year) } +} - const [fieldMap2, referencedFragmentNames] = - getReferencedFieldsAndFragmentNames( - context, - cachedFieldsAndFragmentNames, - fragment, - ); // Do not compare a fragment's fieldMap to itself. - - if (fieldMap === fieldMap2) { - return; - } // (D) First collect any conflicts between the provided collection of fields - // and the collection of fields represented by the given fragment. - collectConflictsBetween( - context, - conflicts, - cachedFieldsAndFragmentNames, - comparedFieldsAndFragmentPairs, - comparedFragmentPairs, - areMutuallyExclusive, - fieldMap, - fieldMap2, - ); // (E) Then collect any conflicts between the provided collection of fields - // and any fragment names found in the given fragment. +/***/ }), - for (const referencedFragmentName of referencedFragmentNames) { - collectConflictsBetweenFieldsAndFragment( - context, - conflicts, - cachedFieldsAndFragmentNames, - comparedFieldsAndFragmentPairs, - comparedFragmentPairs, - areMutuallyExclusive, - fieldMap, - referencedFragmentName, - ); - } -} // Collect all conflicts found between two fragments, including via spreading in -// any nested fragments. +/***/ 80820: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function collectConflictsBetweenFragments( - context, - conflicts, - cachedFieldsAndFragmentNames, - comparedFieldsAndFragmentPairs, - comparedFragmentPairs, - areMutuallyExclusive, - fragmentName1, - fragmentName2, -) { - // No need to compare a fragment to itself. - if (fragmentName1 === fragmentName2) { - return; - } // Memoize so two fragments are not compared for conflicts more than once. +const { timingSafeEqual: TSE } = __nccwpck_require__(6113) - if ( - comparedFragmentPairs.has( - fragmentName1, - fragmentName2, - areMutuallyExclusive, - ) - ) { - return; +const paddedBuffer = (input, length) => { + if (input.length === length) { + return input } - comparedFragmentPairs.add(fragmentName1, fragmentName2, areMutuallyExclusive); - const fragment1 = context.getFragment(fragmentName1); - const fragment2 = context.getFragment(fragmentName2); + const buffer = Buffer.alloc(length) + input.copy(buffer) + return buffer +} - if (!fragment1 || !fragment2) { - return; - } +const timingSafeEqual = (a, b) => { + const length = Math.max(a.length, b.length) + return TSE(paddedBuffer(a, length), paddedBuffer(b, length)) +} - const [fieldMap1, referencedFragmentNames1] = - getReferencedFieldsAndFragmentNames( - context, - cachedFieldsAndFragmentNames, - fragment1, - ); - const [fieldMap2, referencedFragmentNames2] = - getReferencedFieldsAndFragmentNames( - context, - cachedFieldsAndFragmentNames, - fragment2, - ); // (F) First, collect all conflicts between these two collections of fields - // (not including any nested fragments). +module.exports = timingSafeEqual - collectConflictsBetween( - context, - conflicts, - cachedFieldsAndFragmentNames, - comparedFieldsAndFragmentPairs, - comparedFragmentPairs, - areMutuallyExclusive, - fieldMap1, - fieldMap2, - ); // (G) Then collect conflicts between the first fragment and any nested - // fragments spread in the second fragment. - for (const referencedFragmentName2 of referencedFragmentNames2) { - collectConflictsBetweenFragments( - context, - conflicts, - cachedFieldsAndFragmentNames, - comparedFieldsAndFragmentPairs, - comparedFragmentPairs, - areMutuallyExclusive, - fragmentName1, - referencedFragmentName2, - ); - } // (G) Then collect conflicts between the second fragment and any nested - // fragments spread in the first fragment. +/***/ }), - for (const referencedFragmentName1 of referencedFragmentNames1) { - collectConflictsBetweenFragments( - context, - conflicts, - cachedFieldsAndFragmentNames, - comparedFieldsAndFragmentPairs, - comparedFragmentPairs, - areMutuallyExclusive, - referencedFragmentName1, - fragmentName2, - ); - } -} // Find all conflicts found between two selection sets, including those found -// via spreading in fragments. Called when determining if conflicts exist -// between the sub-fields of two overlapping fields. +/***/ 4520: +/***/ ((module) => { -function findConflictsBetweenSubSelectionSets( - context, - cachedFieldsAndFragmentNames, - comparedFieldsAndFragmentPairs, - comparedFragmentPairs, - areMutuallyExclusive, - parentType1, - selectionSet1, - parentType2, - selectionSet2, -) { - const conflicts = []; - const [fieldMap1, fragmentNames1] = getFieldsAndFragmentNames( - context, - cachedFieldsAndFragmentNames, - parentType1, - selectionSet1, - ); - const [fieldMap2, fragmentNames2] = getFieldsAndFragmentNames( - context, - cachedFieldsAndFragmentNames, - parentType2, - selectionSet2, - ); // (H) First, collect all conflicts between these two collections of field. +const MAX_INT32 = Math.pow(2, 32) - collectConflictsBetween( - context, - conflicts, - cachedFieldsAndFragmentNames, - comparedFieldsAndFragmentPairs, - comparedFragmentPairs, - areMutuallyExclusive, - fieldMap1, - fieldMap2, - ); // (I) Then collect conflicts between the first collection of fields and - // those referenced by each fragment name associated with the second. +module.exports = (value, buf = Buffer.allocUnsafe(8)) => { + const high = Math.floor(value / MAX_INT32) + const low = value % MAX_INT32 - for (const fragmentName2 of fragmentNames2) { - collectConflictsBetweenFieldsAndFragment( - context, - conflicts, - cachedFieldsAndFragmentNames, - comparedFieldsAndFragmentPairs, - comparedFragmentPairs, - areMutuallyExclusive, - fieldMap1, - fragmentName2, - ); - } // (I) Then collect conflicts between the second collection of fields and - // those referenced by each fragment name associated with the first. + buf.writeUInt32BE(high, 0) + buf.writeUInt32BE(low, 4) + return buf +} - for (const fragmentName1 of fragmentNames1) { - collectConflictsBetweenFieldsAndFragment( - context, - conflicts, - cachedFieldsAndFragmentNames, - comparedFieldsAndFragmentPairs, - comparedFragmentPairs, - areMutuallyExclusive, - fieldMap2, - fragmentName1, - ); - } // (J) Also collect conflicts between any fragment names by the first and - // fragment names by the second. This compares each item in the first set of - // names to each item in the second set of names. - for (const fragmentName1 of fragmentNames1) { - for (const fragmentName2 of fragmentNames2) { - collectConflictsBetweenFragments( - context, - conflicts, - cachedFieldsAndFragmentNames, - comparedFieldsAndFragmentPairs, - comparedFragmentPairs, - areMutuallyExclusive, - fragmentName1, - fragmentName2, - ); - } - } +/***/ }), - return conflicts; -} // Collect all Conflicts "within" one collection of fields. +/***/ 530: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function collectConflictsWithin( - context, - conflicts, - cachedFieldsAndFragmentNames, - comparedFieldsAndFragmentPairs, - comparedFragmentPairs, - fieldMap, -) { - // A field map is a keyed collection, where each key represents a response - // name and the value at that key is a list of all fields which provide that - // response name. For every response name, if there are multiple fields, they - // must be compared to find a potential conflict. - for (const [responseName, fields] of Object.entries(fieldMap)) { - // This compares every field in the list to every other field in this list - // (except to itself). If the list only has one item, nothing needs to - // be compared. - if (fields.length > 1) { - for (let i = 0; i < fields.length; i++) { - for (let j = i + 1; j < fields.length; j++) { - const conflict = findConflict( - context, - cachedFieldsAndFragmentNames, - comparedFieldsAndFragmentPairs, - comparedFragmentPairs, - false, // within one collection is never mutually exclusive - responseName, - fields[i], - fields[j], - ); +const { JOSECritNotUnderstood, JWSInvalid } = __nccwpck_require__(52973) - if (conflict) { - conflicts.push(conflict); - } +const DEFINED = new Set([ + 'alg', 'jku', 'jwk', 'kid', 'x5u', 'x5c', 'x5t', 'x5t#S256', 'typ', 'cty', + 'crit', 'enc', 'zip', 'epk', 'apu', 'apv', 'iv', 'tag', 'p2s', 'p2c' +]) + +module.exports = function validateCrit (Err, protectedHeader, unprotectedHeader, understood) { + if (protectedHeader && 'crit' in protectedHeader) { + if ( + !Array.isArray(protectedHeader.crit) || + protectedHeader.crit.length === 0 || + protectedHeader.crit.some(s => typeof s !== 'string' || !s) + ) { + throw new Err('"crit" Header Parameter MUST be an array of non-empty strings when present') + } + const whitelisted = new Set(understood) + const combined = { ...protectedHeader, ...unprotectedHeader } + protectedHeader.crit.forEach((parameter) => { + if (DEFINED.has(parameter)) { + throw new Err(`The critical list contains a non-extension Header Parameter ${parameter}`) + } + if (!whitelisted.has(parameter)) { + throw new JOSECritNotUnderstood(`critical "${parameter}" is not understood`) + } + if (parameter === 'b64') { + if (!('b64' in protectedHeader)) { + throw new JWSInvalid('"b64" critical parameter must be integrity protected') } + if (typeof protectedHeader.b64 !== 'boolean') { + throw new JWSInvalid('"b64" critical parameter must be a boolean') + } + } else if (!(parameter in combined)) { + throw new Err(`critical parameter "${parameter}" is missing`) } - } + }) } -} // Collect all Conflicts between two collections of fields. This is similar to, -// but different from the `collectConflictsWithin` function above. This check -// assumes that `collectConflictsWithin` has already been called on each -// provided collection of fields. This is true because this validator traverses -// each individual selection set. + if (unprotectedHeader && 'crit' in unprotectedHeader) { + throw new Err('"crit" Header Parameter MUST be integrity protected when present') + } +} -function collectConflictsBetween( - context, - conflicts, - cachedFieldsAndFragmentNames, - comparedFieldsAndFragmentPairs, - comparedFragmentPairs, - parentFieldsAreMutuallyExclusive, - fieldMap1, - fieldMap2, -) { - // A field map is a keyed collection, where each key represents a response - // name and the value at that key is a list of all fields which provide that - // response name. For any response name which appears in both provided field - // maps, each field from the first field map must be compared to every field - // in the second field map to find potential conflicts. - for (const [responseName, fields1] of Object.entries(fieldMap1)) { - const fields2 = fieldMap2[responseName]; - if (fields2) { - for (const field1 of fields1) { - for (const field2 of fields2) { - const conflict = findConflict( - context, - cachedFieldsAndFragmentNames, - comparedFieldsAndFragmentPairs, - comparedFragmentPairs, - parentFieldsAreMutuallyExclusive, - responseName, - field1, - field2, - ); +/***/ }), - if (conflict) { - conflicts.push(conflict); - } - } - } - } - } -} // Determines if there is a conflict between two particular fields, including -// comparing their sub-fields. +/***/ 16425: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function findConflict( - context, - cachedFieldsAndFragmentNames, - comparedFieldsAndFragmentPairs, - comparedFragmentPairs, - parentFieldsAreMutuallyExclusive, - responseName, - field1, - field2, -) { - const [parentType1, node1, def1] = field1; - const [parentType2, node2, def2] = field2; // If it is known that two fields could not possibly apply at the same - // time, due to the parent types, then it is safe to permit them to diverge - // in aliased field or arguments used as they will not present any ambiguity - // by differing. - // It is known that two parent types could never overlap if they are - // different Object types. Interface or Union types might overlap - if not - // in the current state of the schema, then perhaps in some future version, - // thus may not safely diverge. +module.exports = { + JWE: __nccwpck_require__(72851), + JWK: __nccwpck_require__(67894), + JWKS: __nccwpck_require__(42896), + JWS: __nccwpck_require__(36518), + JWT: __nccwpck_require__(18138), + errors: __nccwpck_require__(52973) +} - const areMutuallyExclusive = - parentFieldsAreMutuallyExclusive || - (parentType1 !== parentType2 && - (0, _definition.isObjectType)(parentType1) && - (0, _definition.isObjectType)(parentType2)); - if (!areMutuallyExclusive) { - // Two aliases must refer to the same field. - const name1 = node1.name.value; - const name2 = node2.name.value; +/***/ }), - if (name1 !== name2) { - return [ - [responseName, `"${name1}" and "${name2}" are different fields`], - [node1], - [node2], - ]; - } // Two field calls must have the same arguments. +/***/ 49651: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (!sameArguments(node1, node2)) { - return [ - [responseName, 'they have differing arguments'], - [node1], - [node2], - ]; +const { createCipheriv, createDecipheriv, getCiphers } = __nccwpck_require__(6113) + +const uint64be = __nccwpck_require__(4520) +const timingSafeEqual = __nccwpck_require__(80820) +const { KEYOBJECT } = __nccwpck_require__(15010) +const { JWEInvalid, JWEDecryptionFailed } = __nccwpck_require__(52973) + +const checkInput = function (size, iv, tag) { + if (iv.length !== 16) { + throw new JWEInvalid('invalid iv') + } + if (arguments.length === 3) { + if (tag.length !== size / 8) { + throw new JWEInvalid('invalid tag') } - } // The return type for each field. + } +} - const type1 = def1 === null || def1 === void 0 ? void 0 : def1.type; - const type2 = def2 === null || def2 === void 0 ? void 0 : def2.type; +const encrypt = (size, sign, { [KEYOBJECT]: keyObject }, cleartext, { iv, aad = Buffer.alloc(0) }) => { + const key = keyObject.export() + checkInput(size, iv) - if (type1 && type2 && doTypesConflict(type1, type2)) { - return [ - [ - responseName, - `they return conflicting types "${(0, _inspect.inspect)( - type1, - )}" and "${(0, _inspect.inspect)(type2)}"`, - ], - [node1], - [node2], - ]; - } // Collect and compare sub-fields. Use the same "visited fragment names" list - // for both collections so fields in a fragment reference are never - // compared to themselves. + const keySize = size / 8 + const encKey = key.slice(keySize) + const cipher = createCipheriv(`aes-${size}-cbc`, encKey, iv) + const ciphertext = Buffer.concat([cipher.update(cleartext), cipher.final()]) + const macData = Buffer.concat([aad, iv, ciphertext, uint64be(aad.length * 8)]) - const selectionSet1 = node1.selectionSet; - const selectionSet2 = node2.selectionSet; + const macKey = key.slice(0, keySize) + const tag = sign({ [KEYOBJECT]: macKey }, macData).slice(0, keySize) - if (selectionSet1 && selectionSet2) { - const conflicts = findConflictsBetweenSubSelectionSets( - context, - cachedFieldsAndFragmentNames, - comparedFieldsAndFragmentPairs, - comparedFragmentPairs, - areMutuallyExclusive, - (0, _definition.getNamedType)(type1), - selectionSet1, - (0, _definition.getNamedType)(type2), - selectionSet2, - ); - return subfieldConflicts(conflicts, responseName, node1, node2); - } + return { ciphertext, tag } } -function sameArguments(node1, node2) { - const args1 = node1.arguments; - const args2 = node2.arguments; +const decrypt = (size, sign, { [KEYOBJECT]: keyObject }, ciphertext, { iv, tag = Buffer.alloc(0), aad = Buffer.alloc(0) }) => { + checkInput(size, iv, tag) - if (args1 === undefined || args1.length === 0) { - return args2 === undefined || args2.length === 0; - } + const keySize = size / 8 + const key = keyObject.export() + const encKey = key.slice(keySize) + const macKey = key.slice(0, keySize) - if (args2 === undefined || args2.length === 0) { - return false; + const macData = Buffer.concat([aad, iv, ciphertext, uint64be(aad.length * 8)]) + const expectedTag = sign({ [KEYOBJECT]: macKey }, macData, tag).slice(0, keySize) + const macCheckPassed = timingSafeEqual(tag, expectedTag) + + if (!macCheckPassed) { + throw new JWEDecryptionFailed() } - /* c8 ignore next */ - if (args1.length !== args2.length) { - /* c8 ignore next */ - return false; - /* c8 ignore next */ + let cleartext + try { + const cipher = createDecipheriv(`aes-${size}-cbc`, encKey, iv) + cleartext = Buffer.concat([cipher.update(ciphertext), cipher.final()]) + } catch (err) {} + + if (!cleartext) { + throw new JWEDecryptionFailed() } - const values2 = new Map(args2.map(({ name, value }) => [name.value, value])); - return args1.every((arg1) => { - const value1 = arg1.value; - const value2 = values2.get(arg1.name.value); + return cleartext +} - if (value2 === undefined) { - return false; +module.exports = (JWA, JWK) => { + ['A128CBC-HS256', 'A192CBC-HS384', 'A256CBC-HS512'].forEach((jwaAlg) => { + const size = parseInt(jwaAlg.substr(1, 3), 10) + const sign = JWA.sign.get(`HS${size * 2}`) + if (getCiphers().includes(`aes-${size}-cbc`)) { + JWA.encrypt.set(jwaAlg, encrypt.bind(undefined, size, sign)) + JWA.decrypt.set(jwaAlg, decrypt.bind(undefined, size, sign)) + JWK.oct.encrypt[jwaAlg] = JWK.oct.decrypt[jwaAlg] = key => (key.use === 'enc' || key.use === undefined) && key.length / 2 === size } - - return stringifyValue(value1) === stringifyValue(value2); - }); + }) } -function stringifyValue(value) { - return (0, _printer.print)((0, _sortValueNode.sortValueNode)(value)); -} // Two types conflict if both types could not apply to a value simultaneously. -// Composite types are ignored as their individual field types will be compared -// later recursively. However List and Non-Null types must match. -function doTypesConflict(type1, type2) { - if ((0, _definition.isListType)(type1)) { - return (0, _definition.isListType)(type2) - ? doTypesConflict(type1.ofType, type2.ofType) - : true; - } +/***/ }), - if ((0, _definition.isListType)(type2)) { - return true; - } +/***/ 21239: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if ((0, _definition.isNonNullType)(type1)) { - return (0, _definition.isNonNullType)(type2) - ? doTypesConflict(type1.ofType, type2.ofType) - : true; - } +const { createCipheriv, createDecipheriv, getCiphers } = __nccwpck_require__(6113) - if ((0, _definition.isNonNullType)(type2)) { - return true; - } +const { KEYOBJECT } = __nccwpck_require__(15010) +const { JWEInvalid, JWEDecryptionFailed } = __nccwpck_require__(52973) +const { asInput } = __nccwpck_require__(98921) - if ( - (0, _definition.isLeafType)(type1) || - (0, _definition.isLeafType)(type2) - ) { - return type1 !== type2; +const checkInput = function (size, iv, tag) { + if (iv.length !== 12) { + throw new JWEInvalid('invalid iv') } + if (arguments.length === 3) { + if (tag.length !== 16) { + throw new JWEInvalid('invalid tag') + } + } +} - return false; -} // Given a selection set, return the collection of fields (a mapping of response -// name to field nodes and definitions) as well as a list of fragment names -// referenced via fragment spreads. - -function getFieldsAndFragmentNames( - context, - cachedFieldsAndFragmentNames, - parentType, - selectionSet, -) { - const cached = cachedFieldsAndFragmentNames.get(selectionSet); +const encrypt = (size, { [KEYOBJECT]: keyObject }, cleartext, { iv, aad = Buffer.alloc(0) }) => { + const key = asInput(keyObject, false) + checkInput(size, iv) - if (cached) { - return cached; - } + const cipher = createCipheriv(`aes-${size}-gcm`, key, iv, { authTagLength: 16 }) + cipher.setAAD(aad) - const nodeAndDefs = Object.create(null); - const fragmentNames = Object.create(null); + const ciphertext = Buffer.concat([cipher.update(cleartext), cipher.final()]) + const tag = cipher.getAuthTag() - _collectFieldsAndFragmentNames( - context, - parentType, - selectionSet, - nodeAndDefs, - fragmentNames, - ); + return { ciphertext, tag } +} - const result = [nodeAndDefs, Object.keys(fragmentNames)]; - cachedFieldsAndFragmentNames.set(selectionSet, result); - return result; -} // Given a reference to a fragment, return the represented collection of fields -// as well as a list of nested fragment names referenced via fragment spreads. +const decrypt = (size, { [KEYOBJECT]: keyObject }, ciphertext, { iv, tag = Buffer.alloc(0), aad = Buffer.alloc(0) }) => { + const key = asInput(keyObject, false) + checkInput(size, iv, tag) -function getReferencedFieldsAndFragmentNames( - context, - cachedFieldsAndFragmentNames, - fragment, -) { - // Short-circuit building a type from the node if possible. - const cached = cachedFieldsAndFragmentNames.get(fragment.selectionSet); + try { + const cipher = createDecipheriv(`aes-${size}-gcm`, key, iv, { authTagLength: 16 }) + cipher.setAuthTag(tag) + cipher.setAAD(aad) - if (cached) { - return cached; + return Buffer.concat([cipher.update(ciphertext), cipher.final()]) + } catch (err) { + throw new JWEDecryptionFailed() } +} - const fragmentType = (0, _typeFromAST.typeFromAST)( - context.getSchema(), - fragment.typeCondition, - ); - return getFieldsAndFragmentNames( - context, - cachedFieldsAndFragmentNames, - fragmentType, - fragment.selectionSet, - ); +module.exports = (JWA, JWK) => { + ['A128GCM', 'A192GCM', 'A256GCM'].forEach((jwaAlg) => { + const size = parseInt(jwaAlg.substr(1, 3), 10) + if (getCiphers().includes(`aes-${size}-gcm`)) { + JWA.encrypt.set(jwaAlg, encrypt.bind(undefined, size)) + JWA.decrypt.set(jwaAlg, decrypt.bind(undefined, size)) + JWK.oct.encrypt[jwaAlg] = JWK.oct.decrypt[jwaAlg] = key => (key.use === 'enc' || key.use === undefined) && key.length === size + } + }) } -function _collectFieldsAndFragmentNames( - context, - parentType, - selectionSet, - nodeAndDefs, - fragmentNames, -) { - for (const selection of selectionSet.selections) { - switch (selection.kind) { - case _kinds.Kind.FIELD: { - const fieldName = selection.name.value; - let fieldDef; - if ( - (0, _definition.isObjectType)(parentType) || - (0, _definition.isInterfaceType)(parentType) - ) { - fieldDef = parentType.getFields()[fieldName]; - } +/***/ }), - const responseName = selection.alias - ? selection.alias.value - : fieldName; +/***/ 37813: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (!nodeAndDefs[responseName]) { - nodeAndDefs[responseName] = []; +const generateIV = __nccwpck_require__(93137) +const base64url = __nccwpck_require__(73385) + +module.exports = (JWA, JWK) => { + ['A128GCMKW', 'A192GCMKW', 'A256GCMKW'].forEach((jwaAlg) => { + const encAlg = jwaAlg.substr(0, 7) + const size = parseInt(jwaAlg.substr(1, 3), 10) + const encrypt = JWA.encrypt.get(encAlg) + const decrypt = JWA.decrypt.get(encAlg) + + if (encrypt && decrypt) { + JWA.keyManagementEncrypt.set(jwaAlg, (key, payload) => { + const iv = generateIV(jwaAlg) + const { ciphertext, tag } = encrypt(key, payload, { iv }) + return { + wrapped: ciphertext, + header: { tag: base64url.encodeBuffer(tag), iv: base64url.encodeBuffer(iv) } } + }) + JWA.keyManagementDecrypt.set(jwaAlg, decrypt) + JWK.oct.wrapKey[jwaAlg] = JWK.oct.unwrapKey[jwaAlg] = key => (key.use === 'enc' || key.use === undefined) && key.length === size + } + }) +} - nodeAndDefs[responseName].push([parentType, selection, fieldDef]); - break; - } - case _kinds.Kind.FRAGMENT_SPREAD: - fragmentNames[selection.name.value] = true; - break; +/***/ }), - case _kinds.Kind.INLINE_FRAGMENT: { - const typeCondition = selection.typeCondition; - const inlineFragmentType = typeCondition - ? (0, _typeFromAST.typeFromAST)(context.getSchema(), typeCondition) - : parentType; +/***/ 80477: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _collectFieldsAndFragmentNames( - context, - inlineFragmentType, - selection.selectionSet, - nodeAndDefs, - fragmentNames, - ); +const { createCipheriv, createDecipheriv, getCiphers } = __nccwpck_require__(6113) - break; - } - } - } -} // Given a series of Conflicts which occurred between two sub-fields, generate -// a single Conflict. +const { KEYOBJECT } = __nccwpck_require__(15010) +const { asInput } = __nccwpck_require__(98921) -function subfieldConflicts(conflicts, responseName, node1, node2) { - if (conflicts.length > 0) { - return [ - [responseName, conflicts.map(([reason]) => reason)], - [node1, ...conflicts.map(([, fields1]) => fields1).flat()], - [node2, ...conflicts.map(([, , fields2]) => fields2).flat()], - ]; +const checkInput = (data) => { + if (data !== undefined && data.length % 8 !== 0) { + throw new Error('invalid data length') } } -/** - * A way to keep track of pairs of things where the ordering of the pair - * matters. - * - * Provides a third argument for has/set to allow flagging the pair as - * weakly or strongly present within the collection. - */ -class OrderedPairSet { - constructor() { - this._data = new Map(); - } +const wrapKey = (alg, { [KEYOBJECT]: keyObject }, payload) => { + const key = asInput(keyObject, false) + const cipher = createCipheriv(alg, key, Buffer.alloc(8, 'a6', 'hex')) - has(a, b, weaklyPresent) { - var _this$_data$get; + return { wrapped: Buffer.concat([cipher.update(payload), cipher.final()]) } +} - const result = - (_this$_data$get = this._data.get(a)) === null || - _this$_data$get === void 0 - ? void 0 - : _this$_data$get.get(b); +const unwrapKey = (alg, { [KEYOBJECT]: keyObject }, payload) => { + const key = asInput(keyObject, false) + checkInput(payload) + const cipher = createDecipheriv(alg, key, Buffer.alloc(8, 'a6', 'hex')) - if (result === undefined) { - return false; + return Buffer.concat([cipher.update(payload), cipher.final()]) +} + +module.exports = (JWA, JWK) => { + ['A128KW', 'A192KW', 'A256KW'].forEach((jwaAlg) => { + const size = parseInt(jwaAlg.substr(1, 3), 10) + const alg = `aes${size}-wrap` + if (getCiphers().includes(alg)) { + JWA.keyManagementEncrypt.set(jwaAlg, wrapKey.bind(undefined, alg)) + JWA.keyManagementDecrypt.set(jwaAlg, unwrapKey.bind(undefined, alg)) + JWK.oct.wrapKey[jwaAlg] = JWK.oct.unwrapKey[jwaAlg] = key => (key.use === 'enc' || key.use === undefined) && key.length === size } + }) +} - return weaklyPresent ? true : weaklyPresent === result; - } - add(a, b, weaklyPresent) { - const map = this._data.get(a); +/***/ }), - if (map === undefined) { - this._data.set(a, new Map([[b, weaklyPresent]])); - } else { - map.set(b, weaklyPresent); +/***/ 94563: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const { improvedDH } = __nccwpck_require__(32457) + +if (improvedDH) { + const { diffieHellman } = __nccwpck_require__(6113) + + const { KeyObject } = __nccwpck_require__(98921) + const importKey = __nccwpck_require__(13468) + + module.exports = ({ keyObject: privateKey }, publicKey) => { + if (!(publicKey instanceof KeyObject)) { + ({ keyObject: publicKey } = importKey(publicKey)) } - } -} -/** - * A way to keep track of pairs of similar things when the ordering of the pair - * does not matter. - */ -class PairSet { - constructor() { - this._orderedPairSet = new OrderedPairSet(); + return diffieHellman({ privateKey, publicKey }) } +} else { + const { createECDH, constants: { POINT_CONVERSION_UNCOMPRESSED } } = __nccwpck_require__(6113) - has(a, b, weaklyPresent) { - return a < b - ? this._orderedPairSet.has(a, b, weaklyPresent) - : this._orderedPairSet.has(b, a, weaklyPresent); - } + const base64url = __nccwpck_require__(73385) - add(a, b, weaklyPresent) { - if (a < b) { - this._orderedPairSet.add(a, b, weaklyPresent); - } else { - this._orderedPairSet.add(b, a, weaklyPresent); + const crvToCurve = (crv) => { + switch (crv) { + case 'P-256': + return 'prime256v1' + case 'P-384': + return 'secp384r1' + case 'P-521': + return 'secp521r1' } } + + const UNCOMPRESSED = Buffer.alloc(1, POINT_CONVERSION_UNCOMPRESSED) + const pubToBuffer = (x, y) => Buffer.concat([UNCOMPRESSED, base64url.decodeToBuffer(x), base64url.decodeToBuffer(y)]) + + module.exports = ({ crv, d }, { x, y }) => { + const curve = crvToCurve(crv) + const exchange = createECDH(curve) + + exchange.setPrivateKey(base64url.decodeToBuffer(d)) + + return exchange.computeSecret(pubToBuffer(x, y)) + } } /***/ }), -/***/ 62450: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 81417: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const { createHash } = __nccwpck_require__(6113) +const ecdhComputeSecret = __nccwpck_require__(94563) +const concat = (key, length, value) => { + const iterations = Math.ceil(length / 32) + let res -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.PossibleFragmentSpreadsRule = PossibleFragmentSpreadsRule; + for (let iter = 1; iter <= iterations; iter++) { + const buf = Buffer.allocUnsafe(4 + key.length + value.length) + buf.writeUInt32BE(iter, 0) + key.copy(buf, 4) + value.copy(buf, 4 + key.length) + if (!res) { + res = createHash('sha256').update(buf).digest() + } else { + res = Buffer.concat([res, createHash('sha256').update(buf).digest()]) + } + } -var _inspect = __nccwpck_require__(10102); + return res.slice(0, length) +} -var _GraphQLError = __nccwpck_require__(4797); +const uint32be = (value, buf = Buffer.allocUnsafe(4)) => { + buf.writeUInt32BE(value) + return buf +} -var _definition = __nccwpck_require__(32150); +const lengthAndInput = input => Buffer.concat([uint32be(input.length), input]) -var _typeComparators = __nccwpck_require__(10333); +module.exports = (alg, keyLen, privKey, pubKey, { apu = Buffer.alloc(0), apv = Buffer.alloc(0) } = {}, computeSecret = ecdhComputeSecret) => { + const value = Buffer.concat([ + lengthAndInput(Buffer.from(alg)), + lengthAndInput(apu), + lengthAndInput(apv), + uint32be(keyLen) + ]) -var _typeFromAST = __nccwpck_require__(27664); + const sharedSecret = computeSecret(privKey, pubKey) + return concat(sharedSecret, keyLen / 8, value) +} -/** - * Possible fragment spread - * - * A fragment spread is only valid if the type condition could ever possibly - * be true: if there is a non-empty intersection of the possible parent types, - * and possible types which pass the type condition. - */ -function PossibleFragmentSpreadsRule(context) { - return { - InlineFragment(node) { - const fragType = context.getType(); - const parentType = context.getParentType(); - if ( - (0, _definition.isCompositeType)(fragType) && - (0, _definition.isCompositeType)(parentType) && - !(0, _typeComparators.doTypesOverlap)( - context.getSchema(), - fragType, - parentType, - ) - ) { - const parentTypeStr = (0, _inspect.inspect)(parentType); - const fragTypeStr = (0, _inspect.inspect)(fragType); - context.reportError( - new _GraphQLError.GraphQLError( - `Fragment cannot be spread here as objects of type "${parentTypeStr}" can never be of type "${fragTypeStr}".`, - { - nodes: node, - }, - ), - ); - } - }, +/***/ }), - FragmentSpread(node) { - const fragName = node.name.value; - const fragType = getFragmentType(context, fragName); - const parentType = context.getParentType(); +/***/ 52652: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if ( - fragType && - parentType && - !(0, _typeComparators.doTypesOverlap)( - context.getSchema(), - fragType, - parentType, - ) - ) { - const parentTypeStr = (0, _inspect.inspect)(parentType); - const fragTypeStr = (0, _inspect.inspect)(fragType); - context.reportError( - new _GraphQLError.GraphQLError( - `Fragment "${fragName}" cannot be spread here as objects of type "${parentTypeStr}" can never be of type "${fragTypeStr}".`, - { - nodes: node, - }, - ), - ); - } - }, - }; +const { improvedDH } = __nccwpck_require__(32457) +const { KEYLENGTHS } = __nccwpck_require__(15501) +const { generateSync } = __nccwpck_require__(39377) + +const derive = __nccwpck_require__(81417) + +const wrapKey = (key, payload, { enc }) => { + const epk = generateSync(key.kty, key.crv) + + const derivedKey = derive(enc, KEYLENGTHS.get(enc), epk, key) + + return { + wrapped: derivedKey, + header: { epk: { kty: key.kty, crv: key.crv, x: epk.x, y: epk.y } } + } } -function getFragmentType(context, name) { - const frag = context.getFragment(name); +const unwrapKey = (key, payload, header) => { + const { enc, epk } = header + return derive(enc, KEYLENGTHS.get(enc), key, epk, header) +} - if (frag) { - const type = (0, _typeFromAST.typeFromAST)( - context.getSchema(), - frag.typeCondition, - ); +module.exports = (JWA, JWK) => { + JWA.keyManagementEncrypt.set('ECDH-ES', wrapKey) + JWA.keyManagementDecrypt.set('ECDH-ES', unwrapKey) + JWK.EC.deriveKey['ECDH-ES'] = key => (key.use === 'enc' || key.use === undefined) && key.crv !== 'secp256k1' - if ((0, _definition.isCompositeType)(type)) { - return type; - } + if (improvedDH) { + JWK.OKP.deriveKey['ECDH-ES'] = key => (key.use === 'enc' || key.use === undefined) && key.keyObject.asymmetricKeyType.startsWith('x') } } /***/ }), -/***/ 70075: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 7668: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const { improvedDH } = __nccwpck_require__(32457) +const { KEYOBJECT } = __nccwpck_require__(15010) +const { generateSync } = __nccwpck_require__(39377) +const { ECDH_DERIVE_LENGTHS } = __nccwpck_require__(15501) +const derive = __nccwpck_require__(81417) -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.PossibleTypeExtensionsRule = PossibleTypeExtensionsRule; +const wrapKey = (wrap, derive, key, payload) => { + const epk = generateSync(key.kty, key.crv) -var _didYouMean = __nccwpck_require__(42878); + const derivedKey = derive(epk, key, payload) -var _inspect = __nccwpck_require__(10102); + const result = wrap({ [KEYOBJECT]: derivedKey }, payload) + result.header = result.header || {} + Object.assign(result.header, { epk: { kty: key.kty, crv: key.crv, x: epk.x, y: epk.y } }) -var _invariant = __nccwpck_require__(28847); + return result +} -var _suggestionList = __nccwpck_require__(57704); +const unwrapKey = (unwrap, derive, key, payload, header) => { + const { epk } = header + const derivedKey = derive(key, epk, header) -var _GraphQLError = __nccwpck_require__(4797); + return unwrap({ [KEYOBJECT]: derivedKey }, payload, header) +} -var _kinds = __nccwpck_require__(11927); +module.exports = (JWA, JWK) => { + ['ECDH-ES+A128KW', 'ECDH-ES+A192KW', 'ECDH-ES+A256KW'].forEach((jwaAlg) => { + const kw = jwaAlg.substr(-6) + const kwWrap = JWA.keyManagementEncrypt.get(kw) + const kwUnwrap = JWA.keyManagementDecrypt.get(kw) + const keylen = parseInt(jwaAlg.substr(9, 3), 10) + ECDH_DERIVE_LENGTHS.set(jwaAlg, keylen) -var _predicates = __nccwpck_require__(20535); + if (kwWrap && kwUnwrap) { + JWA.keyManagementEncrypt.set(jwaAlg, wrapKey.bind(undefined, kwWrap, derive.bind(undefined, jwaAlg, keylen))) + JWA.keyManagementDecrypt.set(jwaAlg, unwrapKey.bind(undefined, kwUnwrap, derive.bind(undefined, jwaAlg, keylen))) + JWK.EC.deriveKey[jwaAlg] = key => (key.use === 'enc' || key.use === undefined) && key.crv !== 'secp256k1' -var _definition = __nccwpck_require__(32150); + if (improvedDH) { + JWK.OKP.deriveKey[jwaAlg] = key => (key.use === 'enc' || key.use === undefined) && key.keyObject.asymmetricKeyType.startsWith('x') + } + } + }) +} +module.exports.wrapKey = wrapKey +module.exports.unwrapKey = unwrapKey -/** - * Possible type extension - * - * A type extension is only valid if the type is defined and has the same kind. - */ -function PossibleTypeExtensionsRule(context) { - const schema = context.getSchema(); - const definedTypes = Object.create(null); - for (const def of context.getDocument().definitions) { - if ((0, _predicates.isTypeDefinitionNode)(def)) { - definedTypes[def.name.value] = def; - } - } +/***/ }), - return { - ScalarTypeExtension: checkExtension, - ObjectTypeExtension: checkExtension, - InterfaceTypeExtension: checkExtension, - UnionTypeExtension: checkExtension, - EnumTypeExtension: checkExtension, - InputObjectTypeExtension: checkExtension, - }; +/***/ 77634: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function checkExtension(node) { - const typeName = node.name.value; - const defNode = definedTypes[typeName]; - const existingType = - schema === null || schema === void 0 ? void 0 : schema.getType(typeName); - let expectedKind; +const { sign: signOneShot, verify: verifyOneShot, createSign, createVerify, getCurves } = __nccwpck_require__(6113) - if (defNode) { - expectedKind = defKindToExtKind[defNode.kind]; - } else if (existingType) { - expectedKind = typeToExtKind(existingType); - } +const { derToJose, joseToDer } = __nccwpck_require__(14451) +const { KEYOBJECT } = __nccwpck_require__(15010) +const resolveNodeAlg = __nccwpck_require__(20125) +const { asInput } = __nccwpck_require__(98921) +const { dsaEncodingSupported } = __nccwpck_require__(32457) - if (expectedKind) { - if (expectedKind !== node.kind) { - const kindStr = extensionKindToTypeName(node.kind); - context.reportError( - new _GraphQLError.GraphQLError( - `Cannot extend non-${kindStr} type "${typeName}".`, - { - nodes: defNode ? [defNode, node] : node, - }, - ), - ); - } - } else { - const allTypeNames = Object.keys({ - ...definedTypes, - ...(schema === null || schema === void 0 - ? void 0 - : schema.getTypeMap()), - }); - const suggestedTypes = (0, _suggestionList.suggestionList)( - typeName, - allTypeNames, - ); - context.reportError( - new _GraphQLError.GraphQLError( - `Cannot extend type "${typeName}" because it is not defined.` + - (0, _didYouMean.didYouMean)(suggestedTypes), - { - nodes: node.name, - }, - ), - ); +let sign, verify + +if (dsaEncodingSupported) { + sign = (jwaAlg, nodeAlg, { [KEYOBJECT]: keyObject }, payload) => { + if (typeof payload === 'string') { + payload = Buffer.from(payload) + } + return signOneShot(nodeAlg, payload, { key: asInput(keyObject, false), dsaEncoding: 'ieee-p1363' }) + } + verify = (jwaAlg, nodeAlg, { [KEYOBJECT]: keyObject }, payload, signature) => { + try { + return verifyOneShot(nodeAlg, payload, { key: asInput(keyObject, true), dsaEncoding: 'ieee-p1363' }, signature) + } catch (err) { + return false + } + } +} else { + sign = (jwaAlg, nodeAlg, { [KEYOBJECT]: keyObject }, payload) => { + return derToJose(createSign(nodeAlg).update(payload).sign(asInput(keyObject, false)), jwaAlg) + } + verify = (jwaAlg, nodeAlg, { [KEYOBJECT]: keyObject }, payload, signature) => { + try { + return createVerify(nodeAlg).update(payload).verify(asInput(keyObject, true), joseToDer(signature, jwaAlg)) + } catch (err) { + return false } } } -const defKindToExtKind = { - [_kinds.Kind.SCALAR_TYPE_DEFINITION]: _kinds.Kind.SCALAR_TYPE_EXTENSION, - [_kinds.Kind.OBJECT_TYPE_DEFINITION]: _kinds.Kind.OBJECT_TYPE_EXTENSION, - [_kinds.Kind.INTERFACE_TYPE_DEFINITION]: _kinds.Kind.INTERFACE_TYPE_EXTENSION, - [_kinds.Kind.UNION_TYPE_DEFINITION]: _kinds.Kind.UNION_TYPE_EXTENSION, - [_kinds.Kind.ENUM_TYPE_DEFINITION]: _kinds.Kind.ENUM_TYPE_EXTENSION, - [_kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION]: - _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION, -}; - -function typeToExtKind(type) { - if ((0, _definition.isScalarType)(type)) { - return _kinds.Kind.SCALAR_TYPE_EXTENSION; +const crvToAlg = (crv) => { + switch (crv) { + case 'P-256': + return 'ES256' + case 'secp256k1': + return 'ES256K' + case 'P-384': + return 'ES384' + case 'P-521': + return 'ES512' } +} - if ((0, _definition.isObjectType)(type)) { - return _kinds.Kind.OBJECT_TYPE_EXTENSION; - } +module.exports = (JWA, JWK) => { + const algs = [] - if ((0, _definition.isInterfaceType)(type)) { - return _kinds.Kind.INTERFACE_TYPE_EXTENSION; + if (getCurves().includes('prime256v1')) { + algs.push('ES256') } - if ((0, _definition.isUnionType)(type)) { - return _kinds.Kind.UNION_TYPE_EXTENSION; + if (getCurves().includes('secp256k1')) { + algs.push('ES256K') } - if ((0, _definition.isEnumType)(type)) { - return _kinds.Kind.ENUM_TYPE_EXTENSION; + if (getCurves().includes('secp384r1')) { + algs.push('ES384') } - if ((0, _definition.isInputObjectType)(type)) { - return _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION; + if (getCurves().includes('secp521r1')) { + algs.push('ES512') } - /* c8 ignore next 3 */ - // Not reachable. All possible types have been considered - false || - (0, _invariant.invariant)( - false, - 'Unexpected type: ' + (0, _inspect.inspect)(type), - ); + algs.forEach((jwaAlg) => { + const nodeAlg = resolveNodeAlg(jwaAlg) + JWA.sign.set(jwaAlg, sign.bind(undefined, jwaAlg, nodeAlg)) + JWA.verify.set(jwaAlg, verify.bind(undefined, jwaAlg, nodeAlg)) + JWK.EC.sign[jwaAlg] = key => key.private && JWK.EC.verify[jwaAlg](key) + JWK.EC.verify[jwaAlg] = key => (key.use === 'sig' || key.use === undefined) && crvToAlg(key.crv) === jwaAlg + }) } -function extensionKindToTypeName(kind) { - switch (kind) { - case _kinds.Kind.SCALAR_TYPE_EXTENSION: - return 'scalar'; - case _kinds.Kind.OBJECT_TYPE_EXTENSION: - return 'object'; +/***/ }), - case _kinds.Kind.INTERFACE_TYPE_EXTENSION: - return 'interface'; +/***/ 18803: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - case _kinds.Kind.UNION_TYPE_EXTENSION: - return 'union'; +const { sign: signOneShot, verify: verifyOneShot } = __nccwpck_require__(6113) - case _kinds.Kind.ENUM_TYPE_EXTENSION: - return 'enum'; +const { KEYOBJECT } = __nccwpck_require__(15010) +const { edDSASupported } = __nccwpck_require__(32457) - case _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION: - return 'input object'; - // Not reachable. All possible types have been considered +const sign = ({ [KEYOBJECT]: keyObject }, payload) => { + if (typeof payload === 'string') { + payload = Buffer.from(payload) + } + return signOneShot(undefined, payload, keyObject) +} - /* c8 ignore next */ +const verify = ({ [KEYOBJECT]: keyObject }, payload, signature) => { + return verifyOneShot(undefined, payload, keyObject, signature) +} - default: - false || - (0, _invariant.invariant)( - false, - 'Unexpected kind: ' + (0, _inspect.inspect)(kind), - ); +module.exports = (JWA, JWK) => { + if (edDSASupported) { + JWA.sign.set('EdDSA', sign) + JWA.verify.set('EdDSA', verify) + JWK.OKP.sign.EdDSA = key => key.private && JWK.OKP.verify.EdDSA(key) + JWK.OKP.verify.EdDSA = key => (key.use === 'sig' || key.use === undefined) && key.keyObject.asymmetricKeyType.startsWith('ed') } } /***/ }), -/***/ 57669: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 25866: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const { createHmac } = __nccwpck_require__(6113) +const { KEYOBJECT } = __nccwpck_require__(15010) +const timingSafeEqual = __nccwpck_require__(80820) +const resolveNodeAlg = __nccwpck_require__(20125) +const { asInput } = __nccwpck_require__(98921) -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.ProvidedRequiredArgumentsOnDirectivesRule = - ProvidedRequiredArgumentsOnDirectivesRule; -exports.ProvidedRequiredArgumentsRule = ProvidedRequiredArgumentsRule; +const sign = (jwaAlg, hmacAlg, { [KEYOBJECT]: keyObject }, payload) => { + const hmac = createHmac(hmacAlg, asInput(keyObject, false)) + hmac.update(payload) + return hmac.digest() +} -var _inspect = __nccwpck_require__(10102); +const verify = (jwaAlg, hmacAlg, key, payload, signature) => { + const expected = sign(jwaAlg, hmacAlg, key, payload) + const actual = signature -var _keyMap = __nccwpck_require__(10711); + return timingSafeEqual(actual, expected) +} -var _GraphQLError = __nccwpck_require__(4797); +module.exports = (JWA, JWK) => { + ['HS256', 'HS384', 'HS512'].forEach((jwaAlg) => { + const hmacAlg = resolveNodeAlg(jwaAlg) + JWA.sign.set(jwaAlg, sign.bind(undefined, jwaAlg, hmacAlg)) + JWA.verify.set(jwaAlg, verify.bind(undefined, jwaAlg, hmacAlg)) + JWK.oct.sign[jwaAlg] = JWK.oct.verify[jwaAlg] = key => key.use === 'sig' || key.use === undefined + }) +} -var _kinds = __nccwpck_require__(11927); -var _printer = __nccwpck_require__(68203); +/***/ }), -var _definition = __nccwpck_require__(32150); +/***/ 50191: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var _directives = __nccwpck_require__(83614); +const { JWKKeySupport, JOSENotSupported } = __nccwpck_require__(52973) +const { KEY_MANAGEMENT_ENCRYPT, KEY_MANAGEMENT_DECRYPT } = __nccwpck_require__(15010) -/** - * Provided required arguments - * - * A field or directive is only valid if all required (non-null without a - * default value) field arguments have been provided. - */ -function ProvidedRequiredArgumentsRule(context) { - return { - // eslint-disable-next-line new-cap - ...ProvidedRequiredArgumentsOnDirectivesRule(context), - Field: { - // Validate on leave to allow for deeper errors to appear first. - leave(fieldNode) { - var _fieldNode$arguments; +const { JWA, JWK } = __nccwpck_require__(15501) - const fieldDef = context.getFieldDef(); +// sign, verify +__nccwpck_require__(25866)(JWA, JWK) +__nccwpck_require__(77634)(JWA, JWK) +__nccwpck_require__(18803)(JWA, JWK) +__nccwpck_require__(35172)(JWA, JWK) +__nccwpck_require__(16984)(JWA, JWK) +__nccwpck_require__(77285)(JWA) - if (!fieldDef) { - return false; - } +// encrypt, decrypt +__nccwpck_require__(49651)(JWA, JWK) +__nccwpck_require__(21239)(JWA, JWK) - const providedArgs = new Set( // FIXME: https://github.com/graphql/graphql-js/issues/2203 - /* c8 ignore next */ - (_fieldNode$arguments = fieldNode.arguments) === null || - _fieldNode$arguments === void 0 - ? void 0 - : _fieldNode$arguments.map((arg) => arg.name.value), - ); +// wrapKey, unwrapKey +__nccwpck_require__(1029)(JWA, JWK) +__nccwpck_require__(80477)(JWA, JWK) +__nccwpck_require__(37813)(JWA, JWK) - for (const argDef of fieldDef.args) { - if ( - !providedArgs.has(argDef.name) && - (0, _definition.isRequiredArgument)(argDef) - ) { - const argTypeStr = (0, _inspect.inspect)(argDef.type); - context.reportError( - new _GraphQLError.GraphQLError( - `Field "${fieldDef.name}" argument "${argDef.name}" of type "${argTypeStr}" is required, but it was not provided.`, - { - nodes: fieldNode, - }, - ), - ); - } - } - }, - }, - }; -} -/** - * @internal - */ +// deriveKey +__nccwpck_require__(94515)(JWA, JWK) +__nccwpck_require__(52652)(JWA, JWK) +__nccwpck_require__(7668)(JWA, JWK) -function ProvidedRequiredArgumentsOnDirectivesRule(context) { - var _schema$getDirectives; +const check = (key, op, alg) => { + const cache = `_${op}_${alg}` - const requiredArgsMap = Object.create(null); - const schema = context.getSchema(); - const definedDirectives = - (_schema$getDirectives = - schema === null || schema === void 0 - ? void 0 - : schema.getDirectives()) !== null && _schema$getDirectives !== void 0 - ? _schema$getDirectives - : _directives.specifiedDirectives; + let label + let keyOp + if (op === 'keyManagementEncrypt') { + label = 'key management (encryption)' + keyOp = KEY_MANAGEMENT_ENCRYPT + } else if (op === 'keyManagementDecrypt') { + label = 'key management (decryption)' + keyOp = KEY_MANAGEMENT_DECRYPT + } - for (const directive of definedDirectives) { - requiredArgsMap[directive.name] = (0, _keyMap.keyMap)( - directive.args.filter(_definition.isRequiredArgument), - (arg) => arg.name, - ); + if (cache in key) { + if (key[cache]) { + return + } + throw new JWKKeySupport(`the key does not support ${alg} ${label || op} algorithm`) } - const astDefinitions = context.getDocument().definitions; + let value = true + if (!JWA[op].has(alg)) { + throw new JOSENotSupported(`unsupported ${label || op} alg: ${alg}`) + } else if (!key.algorithms(keyOp).has(alg)) { + value = false + } - for (const def of astDefinitions) { - if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { - var _def$arguments; + Object.defineProperty(key, cache, { value, enumerable: false }) - // FIXME: https://github.com/graphql/graphql-js/issues/2203 + if (!value) { + return check(key, op, alg) + } +} - /* c8 ignore next */ - const argNodes = - (_def$arguments = def.arguments) !== null && _def$arguments !== void 0 - ? _def$arguments - : []; - requiredArgsMap[def.name.value] = (0, _keyMap.keyMap)( - argNodes.filter(isRequiredArgumentNode), - (arg) => arg.name.value, - ); - } +module.exports = { + check, + sign: (alg, key, payload) => { + check(key, 'sign', alg) + return JWA.sign.get(alg)(key, payload) + }, + verify: (alg, key, payload, signature) => { + check(key, 'verify', alg) + return JWA.verify.get(alg)(key, payload, signature) + }, + keyManagementEncrypt: (alg, key, payload, opts) => { + check(key, 'keyManagementEncrypt', alg) + return JWA.keyManagementEncrypt.get(alg)(key, payload, opts) + }, + keyManagementDecrypt: (alg, key, payload, opts) => { + check(key, 'keyManagementDecrypt', alg) + return JWA.keyManagementDecrypt.get(alg)(key, payload, opts) + }, + encrypt: (alg, key, cleartext, opts) => { + check(key, 'encrypt', alg) + return JWA.encrypt.get(alg)(key, cleartext, opts) + }, + decrypt: (alg, key, ciphertext, opts) => { + check(key, 'decrypt', alg) + return JWA.decrypt.get(alg)(key, ciphertext, opts) } +} - return { - Directive: { - // Validate on leave to allow for deeper errors to appear first. - leave(directiveNode) { - const directiveName = directiveNode.name.value; - const requiredArgs = requiredArgsMap[directiveName]; - if (requiredArgs) { - var _directiveNode$argume; +/***/ }), - // FIXME: https://github.com/graphql/graphql-js/issues/2203 +/***/ 77285: +/***/ ((module) => { - /* c8 ignore next */ - const argNodes = - (_directiveNode$argume = directiveNode.arguments) !== null && - _directiveNode$argume !== void 0 - ? _directiveNode$argume - : []; - const argNodeMap = new Set(argNodes.map((arg) => arg.name.value)); +const sign = () => Buffer.from('') +const verify = (key, payload, signature) => !signature.length - for (const [argName, argDef] of Object.entries(requiredArgs)) { - if (!argNodeMap.has(argName)) { - const argType = (0, _definition.isType)(argDef.type) - ? (0, _inspect.inspect)(argDef.type) - : (0, _printer.print)(argDef.type); - context.reportError( - new _GraphQLError.GraphQLError( - `Directive "@${directiveName}" argument "${argName}" of type "${argType}" is required, but it was not provided.`, - { - nodes: directiveNode, - }, - ), - ); - } - } - } - }, - }, - }; +module.exports = (JWA, JWK) => { + JWA.sign.set('none', sign) + JWA.verify.set('none', verify) } -function isRequiredArgumentNode(arg) { - return ( - arg.type.kind === _kinds.Kind.NON_NULL_TYPE && arg.defaultValue == null - ); + +/***/ }), + +/***/ 94515: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const { pbkdf2Sync: pbkdf2, randomBytes } = __nccwpck_require__(6113) + +const { KEYOBJECT } = __nccwpck_require__(15010) +const base64url = __nccwpck_require__(73385) + +const SALT_LENGTH = 16 +const NULL_BUFFER = Buffer.alloc(1, 0) + +const concatSalt = (alg, p2s) => { + return Buffer.concat([ + Buffer.from(alg, 'utf8'), + NULL_BUFFER, + p2s + ]) +} + +const wrapKey = (keylen, sha, concat, wrap, { [KEYOBJECT]: keyObject }, payload) => { + // Note that if password-based encryption is used for multiple + // recipients, it is expected that each recipient use different values + // for the PBES2 parameters "p2s" and "p2c". + // here we generate p2c between 2048 and 4096 and random p2s + const p2c = Math.floor((Math.random() * 2049) + 2048) + const p2s = randomBytes(SALT_LENGTH) + const salt = concat(p2s) + + const derivedKey = pbkdf2(keyObject.export(), salt, p2c, keylen, sha) + + const result = wrap({ [KEYOBJECT]: derivedKey }, payload) + result.header = result.header || {} + Object.assign(result.header, { p2c, p2s: base64url.encodeBuffer(p2s) }) + + return result +} + +const unwrapKey = (keylen, sha, concat, unwrap, { [KEYOBJECT]: keyObject }, payload, header) => { + const { p2s, p2c } = header + const salt = concat(p2s) + const derivedKey = pbkdf2(keyObject.export(), salt, p2c, keylen, sha) + return unwrap({ [KEYOBJECT]: derivedKey }, payload, header) +} + +module.exports = (JWA, JWK) => { + ['PBES2-HS256+A128KW', 'PBES2-HS384+A192KW', 'PBES2-HS512+A256KW'].forEach((jwaAlg) => { + const kw = jwaAlg.substr(-6) + const kwWrap = JWA.keyManagementEncrypt.get(kw) + const kwUnwrap = JWA.keyManagementDecrypt.get(kw) + const keylen = parseInt(jwaAlg.substr(13, 3), 10) / 8 + const sha = `sha${jwaAlg.substr(8, 3)}` + + if (kwWrap && kwUnwrap) { + JWA.keyManagementEncrypt.set(jwaAlg, wrapKey.bind(undefined, keylen, sha, concatSalt.bind(undefined, jwaAlg), kwWrap)) + JWA.keyManagementDecrypt.set(jwaAlg, unwrapKey.bind(undefined, keylen, sha, concatSalt.bind(undefined, jwaAlg), kwUnwrap)) + JWK.oct.deriveKey[jwaAlg] = key => key.use === 'enc' || key.use === undefined + } + }) } /***/ }), -/***/ 16830: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 1029: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const { publicEncrypt, privateDecrypt, constants } = __nccwpck_require__(6113) +const { oaepHashSupported } = __nccwpck_require__(32457) +const { KEYOBJECT } = __nccwpck_require__(15010) +const { asInput } = __nccwpck_require__(98921) -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.ScalarLeafsRule = ScalarLeafsRule; +const resolvePadding = (alg) => { + switch (alg) { + case 'RSA-OAEP': + case 'RSA-OAEP-256': + case 'RSA-OAEP-384': + case 'RSA-OAEP-512': + return constants.RSA_PKCS1_OAEP_PADDING + case 'RSA1_5': + return constants.RSA_PKCS1_PADDING + } +} -var _inspect = __nccwpck_require__(10102); +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 + } +} -var _GraphQLError = __nccwpck_require__(4797); +const wrapKey = (padding, oaepHash, { [KEYOBJECT]: keyObject }, payload) => { + const key = asInput(keyObject, true) + return { wrapped: publicEncrypt({ key, oaepHash, padding }, payload) } +} -var _definition = __nccwpck_require__(32150); +const unwrapKey = (padding, oaepHash, { [KEYOBJECT]: keyObject }, payload) => { + const key = asInput(keyObject, false) + return privateDecrypt({ key, oaepHash, padding }, payload) +} -/** - * Scalar leafs - * - * A GraphQL document is valid only if all leaf fields (fields without - * sub selections) are of scalar or enum types. - */ -function ScalarLeafsRule(context) { - return { - Field(node) { - const type = context.getType(); - const selectionSet = node.selectionSet; +const LENGTHS = { + RSA1_5: 0, + 'RSA-OAEP': 592, + 'RSA-OAEP-256': 784, + 'RSA-OAEP-384': 1040, + 'RSA-OAEP-512': 1296 +} - if (type) { - if ((0, _definition.isLeafType)((0, _definition.getNamedType)(type))) { - if (selectionSet) { - const fieldName = node.name.value; - const typeStr = (0, _inspect.inspect)(type); - context.reportError( - new _GraphQLError.GraphQLError( - `Field "${fieldName}" must not have a selection since type "${typeStr}" has no subfields.`, - { - nodes: selectionSet, - }, - ), - ); - } - } else if (!selectionSet) { - const fieldName = node.name.value; - const typeStr = (0, _inspect.inspect)(type); - context.reportError( - new _GraphQLError.GraphQLError( - `Field "${fieldName}" of type "${typeStr}" must have a selection of subfields. Did you mean "${fieldName} { ... }"?`, - { - nodes: node, - }, - ), - ); - } else if (selectionSet.selections.length === 0) { - const fieldName = node.name.value; - const typeStr = (0, _inspect.inspect)(type); - context.reportError( - new _GraphQLError.GraphQLError( - `Field "${fieldName}" of type "${typeStr}" must have at least one field selected.`, - { - nodes: node, - }, - ), - ); - } - } - }, - }; +module.exports = (JWA, JWK) => { + const algs = ['RSA-OAEP', 'RSA1_5'] + + if (oaepHashSupported) { + algs.splice(1, 0, 'RSA-OAEP-256', 'RSA-OAEP-384', 'RSA-OAEP-512') + } + + algs.forEach((jwaAlg) => { + const padding = resolvePadding(jwaAlg) + const oaepHash = resolveOaepHash(jwaAlg) + JWA.keyManagementEncrypt.set(jwaAlg, wrapKey.bind(undefined, padding, oaepHash)) + JWA.keyManagementDecrypt.set(jwaAlg, unwrapKey.bind(undefined, padding, oaepHash)) + JWK.RSA.wrapKey[jwaAlg] = key => (key.use === 'enc' || key.use === undefined) && key.length >= LENGTHS[jwaAlg] + JWK.RSA.unwrapKey[jwaAlg] = key => key.private && (key.use === 'enc' || key.use === undefined) && key.length >= LENGTHS[jwaAlg] + }) } /***/ }), -/***/ 4365: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 16984: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const { createSign, createVerify } = __nccwpck_require__(6113) +const { KEYOBJECT } = __nccwpck_require__(15010) +const resolveNodeAlg = __nccwpck_require__(20125) +const { asInput } = __nccwpck_require__(98921) -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.SingleFieldSubscriptionsRule = SingleFieldSubscriptionsRule; +const sign = (nodeAlg, { [KEYOBJECT]: keyObject }, payload) => { + return createSign(nodeAlg).update(payload).sign(asInput(keyObject, false)) +} -var _GraphQLError = __nccwpck_require__(4797); +const verify = (nodeAlg, { [KEYOBJECT]: keyObject }, payload, signature) => { + return createVerify(nodeAlg).update(payload).verify(asInput(keyObject, true), signature) +} -var _kinds = __nccwpck_require__(11927); +const LENGTHS = { + RS256: 0, + RS384: 624, + RS512: 752 +} -var _collectFields = __nccwpck_require__(49942); +module.exports = (JWA, JWK) => { + ['RS256', 'RS384', 'RS512'].forEach((jwaAlg) => { + const nodeAlg = resolveNodeAlg(jwaAlg) + JWA.sign.set(jwaAlg, sign.bind(undefined, nodeAlg)) + JWA.verify.set(jwaAlg, verify.bind(undefined, nodeAlg)) + JWK.RSA.sign[jwaAlg] = key => key.private && JWK.RSA.verify[jwaAlg](key) + JWK.RSA.verify[jwaAlg] = key => (key.use === 'sig' || key.use === undefined) && key.length >= LENGTHS[jwaAlg] + }) +} -/** - * Subscriptions must only include a non-introspection field. - * - * A GraphQL subscription is valid only if it contains a single root field and - * that root field is not an introspection field. - * - * See https://spec.graphql.org/draft/#sec-Single-root-field - */ -function SingleFieldSubscriptionsRule(context) { - return { - OperationDefinition(node) { - if (node.operation === 'subscription') { - const schema = context.getSchema(); - const subscriptionType = schema.getSubscriptionType(); - if (subscriptionType) { - const operationName = node.name ? node.name.value : null; - const variableValues = Object.create(null); - const document = context.getDocument(); - const fragments = Object.create(null); +/***/ }), - for (const definition of document.definitions) { - if (definition.kind === _kinds.Kind.FRAGMENT_DEFINITION) { - fragments[definition.name.value] = definition; - } - } +/***/ 35172: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const fields = (0, _collectFields.collectFields)( - schema, - fragments, - variableValues, - subscriptionType, - node.selectionSet, - ); +const { + createSign, + createVerify, + constants +} = __nccwpck_require__(6113) - if (fields.size > 1) { - const fieldSelectionLists = [...fields.values()]; - const extraFieldSelectionLists = fieldSelectionLists.slice(1); - const extraFieldSelections = extraFieldSelectionLists.flat(); - context.reportError( - new _GraphQLError.GraphQLError( - operationName != null - ? `Subscription "${operationName}" must select only one top level field.` - : 'Anonymous Subscription must select only one top level field.', - { - nodes: extraFieldSelections, - }, - ), - ); - } +const { KEYOBJECT } = __nccwpck_require__(15010) +const resolveNodeAlg = __nccwpck_require__(20125) +const { asInput } = __nccwpck_require__(98921) - for (const fieldNodes of fields.values()) { - const field = fieldNodes[0]; - const fieldName = field.name.value; +const sign = (nodeAlg, { [KEYOBJECT]: keyObject }, payload) => { + const key = asInput(keyObject, false) + return createSign(nodeAlg).update(payload).sign({ + key, + padding: constants.RSA_PKCS1_PSS_PADDING, + saltLength: constants.RSA_PSS_SALTLEN_DIGEST + }) +} - if (fieldName.startsWith('__')) { - context.reportError( - new _GraphQLError.GraphQLError( - operationName != null - ? `Subscription "${operationName}" must not select an introspection top level field.` - : 'Anonymous Subscription must not select an introspection top level field.', - { - nodes: fieldNodes, - }, - ), - ); - } - } - } - } - }, - }; +const verify = (nodeAlg, { [KEYOBJECT]: keyObject }, payload, signature) => { + const key = asInput(keyObject, true) + return createVerify(nodeAlg).update(payload).verify({ + key, + padding: constants.RSA_PKCS1_PSS_PADDING, + saltLength: constants.RSA_PSS_SALTLEN_DIGEST + }, signature) +} + +const LENGTHS = { + PS256: 528, + PS384: 784, + PS512: 1040 +} + +module.exports = (JWA, JWK) => { + ['PS256', 'PS384', 'PS512'].forEach((jwaAlg) => { + const nodeAlg = resolveNodeAlg(jwaAlg) + JWA.sign.set(jwaAlg, sign.bind(undefined, nodeAlg)) + JWA.verify.set(jwaAlg, verify.bind(undefined, nodeAlg)) + JWK.RSA.sign[jwaAlg] = key => key.private && JWK.RSA.verify[jwaAlg](key) + JWK.RSA.verify[jwaAlg] = key => (key.use === 'sig' || key.use === undefined) && key.length >= LENGTHS[jwaAlg] + }) } /***/ }), -/***/ 55104: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 73607: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const { inflateRawSync } = __nccwpck_require__(59796) +const base64url = __nccwpck_require__(73385) +const getKey = __nccwpck_require__(31308) +const { KeyStore } = __nccwpck_require__(42896) +const errors = __nccwpck_require__(52973) +const { check, decrypt, keyManagementDecrypt } = __nccwpck_require__(50191) +const JWK = __nccwpck_require__(67894) -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.UniqueArgumentDefinitionNamesRule = UniqueArgumentDefinitionNamesRule; +const { createSecretKey } = __nccwpck_require__(98921) +const generateCEK = __nccwpck_require__(15242) +const validateHeaders = __nccwpck_require__(46904) +const { detect: resolveSerialization } = __nccwpck_require__(5348) -var _groupBy = __nccwpck_require__(93173); +const SINGLE_RECIPIENT = new Set(['compact', 'flattened']) -var _GraphQLError = __nccwpck_require__(4797); +const combineHeader = (prot = {}, unprotected = {}, header = {}) => { + if (typeof prot === 'string') { + prot = base64url.JSON.decode(prot) + } + + const p2s = prot.p2s || unprotected.p2s || header.p2s + const apu = prot.apu || unprotected.apu || header.apu + const apv = prot.apv || unprotected.apv || header.apv + const iv = prot.iv || unprotected.iv || header.iv + const tag = prot.tag || unprotected.tag || header.tag -/** - * Unique argument definition names - * - * A GraphQL Object or Interface type is only valid if all its fields have uniquely named arguments. - * A GraphQL Directive is only valid if all its arguments are uniquely named. - */ -function UniqueArgumentDefinitionNamesRule(context) { return { - DirectiveDefinition(directiveNode) { - var _directiveNode$argume; + ...prot, + ...unprotected, + ...header, + ...(typeof p2s === 'string' ? { p2s: base64url.decodeToBuffer(p2s) } : undefined), + ...(typeof apu === 'string' ? { apu: base64url.decodeToBuffer(apu) } : undefined), + ...(typeof apv === 'string' ? { apv: base64url.decodeToBuffer(apv) } : undefined), + ...(typeof iv === 'string' ? { iv: base64url.decodeToBuffer(iv) } : undefined), + ...(typeof tag === 'string' ? { tag: base64url.decodeToBuffer(tag) } : undefined) + } +} - // FIXME: https://github.com/graphql/graphql-js/issues/2203 +const validateAlgorithms = (algorithms, option) => { + if (algorithms !== undefined && (!Array.isArray(algorithms) || algorithms.some(s => typeof s !== 'string' || !s))) { + throw new TypeError(`"${option}" option must be an array of non-empty strings`) + } - /* c8 ignore next */ - const argumentNodes = - (_directiveNode$argume = directiveNode.arguments) !== null && - _directiveNode$argume !== void 0 - ? _directiveNode$argume - : []; - return checkArgUniqueness(`@${directiveNode.name.value}`, argumentNodes); - }, + if (!algorithms) { + return undefined + } - InterfaceTypeDefinition: checkArgUniquenessPerField, - InterfaceTypeExtension: checkArgUniquenessPerField, - ObjectTypeDefinition: checkArgUniquenessPerField, - ObjectTypeExtension: checkArgUniquenessPerField, - }; + return new Set(algorithms) +} - function checkArgUniquenessPerField(typeNode) { - var _typeNode$fields; +/* + * @public + */ +const jweDecrypt = (skipValidateHeaders, serialization, jwe, key, { crit = [], complete = false, keyManagementAlgorithms, contentEncryptionAlgorithms, maxPBES2Count = 10000, inflateRawSyncLimit = 250000 } = {}) => { + key = getKey(key, true) - const typeName = typeNode.name.value; // FIXME: https://github.com/graphql/graphql-js/issues/2203 + keyManagementAlgorithms = validateAlgorithms(keyManagementAlgorithms, 'keyManagementAlgorithms') + contentEncryptionAlgorithms = validateAlgorithms(contentEncryptionAlgorithms, 'contentEncryptionAlgorithms') - /* c8 ignore next */ + if (!Array.isArray(crit) || crit.some(s => typeof s !== 'string' || !s)) { + throw new TypeError('"crit" option must be an array of non-empty strings') + } - const fieldNodes = - (_typeNode$fields = typeNode.fields) !== null && - _typeNode$fields !== void 0 - ? _typeNode$fields - : []; + if (!serialization) { + serialization = resolveSerialization(jwe) + } - for (const fieldDef of fieldNodes) { - var _fieldDef$arguments; + let alg, ciphertext, enc, encryptedKey, iv, opts, prot, tag, unprotected, cek, aad, header - const fieldName = fieldDef.name.value; // FIXME: https://github.com/graphql/graphql-js/issues/2203 + // treat general format with one recipient as flattened + // skips iteration and avoids multi errors in this case + if (serialization === 'general' && jwe.recipients.length === 1) { + serialization = 'flattened' + const { recipients, ...root } = jwe + jwe = { ...root, ...recipients[0] } + } - /* c8 ignore next */ + if (SINGLE_RECIPIENT.has(serialization)) { + if (serialization === 'compact') { // compact serialization format + ([prot, encryptedKey, iv, ciphertext, tag] = jwe.split('.')) + } else { // flattened serialization format + ({ protected: prot, encrypted_key: encryptedKey, iv, ciphertext, tag, unprotected, aad, header } = jwe) + } - const argumentNodes = - (_fieldDef$arguments = fieldDef.arguments) !== null && - _fieldDef$arguments !== void 0 - ? _fieldDef$arguments - : []; - checkArgUniqueness(`${typeName}.${fieldName}`, argumentNodes); + if (!skipValidateHeaders) { + validateHeaders(prot, unprotected, [{ header }], true, crit) } - return false; - } + opts = combineHeader(prot, unprotected, header) - function checkArgUniqueness(parentName, argumentNodes) { - const seenArgs = (0, _groupBy.groupBy)( - argumentNodes, - (arg) => arg.name.value, - ); + ;({ alg, enc } = opts) - for (const [argName, argNodes] of seenArgs) { - if (argNodes.length > 1) { - context.reportError( - new _GraphQLError.GraphQLError( - `Argument "${parentName}(${argName}:)" can only be defined once.`, - { - nodes: argNodes.map((node) => node.name), - }, - ), - ); - } + if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) { + throw new errors.JOSEAlgNotWhitelisted('key management algorithm not whitelisted') } - return false; - } -} + if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) { + throw new errors.JOSEAlgNotWhitelisted('content encryption algorithm not whitelisted') + } + if (key instanceof KeyStore) { + const keystore = key + let keys + if (opts.alg === 'dir') { + keys = keystore.all({ kid: opts.kid, alg: opts.enc, key_ops: ['decrypt'] }) + } else { + keys = keystore.all({ kid: opts.kid, alg: opts.alg, key_ops: ['unwrapKey'] }) + } + switch (keys.length) { + case 0: + throw new errors.JWKSNoMatchingKey() + case 1: + // treat the call as if a Key instance was passed in + // skips iteration and avoids multi errors in this case + key = keys[0] + break + default: { + const errs = [] + for (const key of keys) { + try { + return jweDecrypt(true, serialization, jwe, key, { + crit, + complete, + contentEncryptionAlgorithms: contentEncryptionAlgorithms ? [...contentEncryptionAlgorithms] : undefined, + keyManagementAlgorithms: keyManagementAlgorithms ? [...keyManagementAlgorithms] : undefined + }) + } catch (err) { + errs.push(err) + continue + } + } -/***/ }), + const multi = new errors.JOSEMultiError(errs) + if ([...multi].some(e => e instanceof errors.JWEDecryptionFailed)) { + throw new errors.JWEDecryptionFailed() + } + throw multi + } + } + } -/***/ 45799: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + check(key, ...(alg === 'dir' ? ['decrypt', enc] : ['keyManagementDecrypt', alg])) -"use strict"; + if (alg.startsWith('PBES2')) { + if (opts && opts.p2c > maxPBES2Count) { + throw new errors.JWEInvalid('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds') + } + } + try { + if (alg === 'dir') { + cek = JWK.asKey(key, { alg: enc, use: 'enc' }) + } else if (alg === 'ECDH-ES') { + const unwrapped = keyManagementDecrypt(alg, key, undefined, opts) + cek = JWK.asKey(createSecretKey(unwrapped), { alg: enc, use: 'enc' }) + } else { + const unwrapped = keyManagementDecrypt(alg, key, base64url.decodeToBuffer(encryptedKey), opts) + cek = JWK.asKey(createSecretKey(unwrapped), { alg: enc, use: 'enc' }) + } + } catch (err) { + // To mitigate the attacks described in RFC 3218, the + // recipient MUST NOT distinguish between format, padding, and length + // errors of encrypted keys. It is strongly recommended, in the event + // of receiving an improperly formatted key, that the recipient + // substitute a randomly generated CEK and proceed to the next step, to + // mitigate timing attacks. + cek = generateCEK(enc) + } -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.UniqueArgumentNamesRule = UniqueArgumentNamesRule; + let adata + if (aad) { + adata = Buffer.concat([ + Buffer.from(prot || ''), + Buffer.from('.'), + Buffer.from(aad) + ]) + } else { + adata = Buffer.from(prot || '') + } -var _groupBy = __nccwpck_require__(93173); + try { + iv = base64url.decodeToBuffer(iv) + } catch (err) {} + try { + tag = base64url.decodeToBuffer(tag) + } catch (err) {} -var _GraphQLError = __nccwpck_require__(4797); + let cleartext = decrypt(enc, cek, base64url.decodeToBuffer(ciphertext), { iv, tag, aad: adata }) -/** - * Unique argument names - * - * A GraphQL field or directive is only valid if all supplied arguments are - * uniquely named. - * - * See https://spec.graphql.org/draft/#sec-Argument-Names - */ -function UniqueArgumentNamesRule(context) { - return { - Field: checkArgUniqueness, - Directive: checkArgUniqueness, - }; + if (opts.zip) { + cleartext = inflateRawSync(cleartext, { maxOutputLength: inflateRawSyncLimit }) + } - function checkArgUniqueness(parentNode) { - var _parentNode$arguments; + if (complete) { + const result = { cleartext, key, cek } + if (aad) result.aad = aad + if (header) result.header = header + if (unprotected) result.unprotected = unprotected + if (prot) result.protected = base64url.JSON.decode(prot) + return result + } - // FIXME: https://github.com/graphql/graphql-js/issues/2203 + return cleartext + } - /* c8 ignore next */ - const argumentNodes = - (_parentNode$arguments = parentNode.arguments) !== null && - _parentNode$arguments !== void 0 - ? _parentNode$arguments - : []; - const seenArgs = (0, _groupBy.groupBy)( - argumentNodes, - (arg) => arg.name.value, - ); + validateHeaders(jwe.protected, jwe.unprotected, jwe.recipients.map(({ header }) => ({ header })), true, crit) - for (const [argName, argNodes] of seenArgs) { - if (argNodes.length > 1) { - context.reportError( - new _GraphQLError.GraphQLError( - `There can be only one argument named "${argName}".`, - { - nodes: argNodes.map((node) => node.name), - }, - ), - ); - } + // general serialization format + const { recipients, ...root } = jwe + const errs = [] + for (const recipient of recipients) { + try { + return jweDecrypt(true, 'flattened', { ...root, ...recipient }, key, { + crit, + complete, + contentEncryptionAlgorithms: contentEncryptionAlgorithms ? [...contentEncryptionAlgorithms] : undefined, + keyManagementAlgorithms: keyManagementAlgorithms ? [...keyManagementAlgorithms] : undefined + }) + } catch (err) { + errs.push(err) + continue } } + + const multi = new errors.JOSEMultiError(errs) + if ([...multi].some(e => e instanceof errors.JWEDecryptionFailed)) { + throw new errors.JWEDecryptionFailed() + } else if ([...multi].every(e => e instanceof errors.JWKSNoMatchingKey)) { + throw new errors.JWKSNoMatchingKey() + } + throw multi } +module.exports = jweDecrypt.bind(undefined, false, undefined) + /***/ }), -/***/ 17074: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 19094: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const { deflateRawSync } = __nccwpck_require__(59796) +const { KEYOBJECT } = __nccwpck_require__(15010) +const generateIV = __nccwpck_require__(93137) +const base64url = __nccwpck_require__(73385) +const getKey = __nccwpck_require__(31308) +const isObject = __nccwpck_require__(41805) +const { createSecretKey } = __nccwpck_require__(98921) +const deepClone = __nccwpck_require__(43653) +const importKey = __nccwpck_require__(13468) +const { JWEInvalid } = __nccwpck_require__(52973) +const { check, keyManagementEncrypt, encrypt } = __nccwpck_require__(50191) + +const serializers = __nccwpck_require__(5348) +const generateCEK = __nccwpck_require__(15242) +const validateHeaders = __nccwpck_require__(46904) -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.UniqueDirectiveNamesRule = UniqueDirectiveNamesRule; +const PROCESS_RECIPIENT = Symbol('PROCESS_RECIPIENT') -var _GraphQLError = __nccwpck_require__(4797); +class Encrypt { + constructor (cleartext, protectedHeader, aad, unprotectedHeader) { + if (!Buffer.isBuffer(cleartext) && typeof cleartext !== 'string') { + throw new TypeError('cleartext argument must be a Buffer or a string') + } + cleartext = Buffer.from(cleartext) -/** - * Unique directive names - * - * A GraphQL document is only valid if all defined directives have unique names. - */ -function UniqueDirectiveNamesRule(context) { - const knownDirectiveNames = Object.create(null); - const schema = context.getSchema(); - return { - DirectiveDefinition(node) { - const directiveName = node.name.value; + if (aad !== undefined && !Buffer.isBuffer(aad) && typeof aad !== 'string') { + throw new TypeError('aad argument must be a Buffer or a string when provided') + } + aad = aad ? Buffer.from(aad) : undefined - if ( - schema !== null && - schema !== void 0 && - schema.getDirective(directiveName) - ) { - context.reportError( - new _GraphQLError.GraphQLError( - `Directive "@${directiveName}" already exists in the schema. It cannot be redefined.`, - { - nodes: node.name, - }, - ), - ); - return; - } + if (protectedHeader !== undefined && !isObject(protectedHeader)) { + throw new TypeError('protectedHeader argument must be a plain object when provided') + } - if (knownDirectiveNames[directiveName]) { - context.reportError( - new _GraphQLError.GraphQLError( - `There can be only one directive named "@${directiveName}".`, - { - nodes: [knownDirectiveNames[directiveName], node.name], - }, - ), - ); - } else { - knownDirectiveNames[directiveName] = node.name; - } + if (unprotectedHeader !== undefined && !isObject(unprotectedHeader)) { + throw new TypeError('unprotectedHeader argument must be a plain object when provided') + } - return false; - }, - }; -} + this._recipients = [] + this._cleartext = cleartext + this._aad = aad + this._unprotected = unprotectedHeader ? deepClone(unprotectedHeader) : undefined + this._protected = protectedHeader ? deepClone(protectedHeader) : undefined + } + /* + * @public + */ + recipient (key, header) { + key = getKey(key) -/***/ }), + if (header !== undefined && !isObject(header)) { + throw new TypeError('header argument must be a plain object when provided') + } + + this._recipients.push({ + key, + header: header ? deepClone(header) : undefined + }) + + return this + } + + /* + * @private + */ + [PROCESS_RECIPIENT] (recipient) { + const unprotectedHeader = this._unprotected + const protectedHeader = this._protected + const { length: recipientCount } = this._recipients + + const jweHeader = { + ...protectedHeader, + ...unprotectedHeader, + ...recipient.header + } + const { key } = recipient -/***/ 61944: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + const enc = jweHeader.enc + let alg = jweHeader.alg -"use strict"; + if (key.use === 'sig') { + throw new TypeError('a key with "use":"sig" is not usable for encryption') + } + if (alg === 'dir') { + check(key, 'encrypt', enc) + } else if (alg) { + check(key, 'keyManagementEncrypt', alg) + } else { + alg = key.alg || [...key.algorithms('wrapKey')][0] || [...key.algorithms('deriveKey')][0] -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.UniqueDirectivesPerLocationRule = UniqueDirectivesPerLocationRule; + if (alg === 'ECDH-ES' && recipientCount !== 1) { + alg = [...key.algorithms('deriveKey')][1] + } -var _GraphQLError = __nccwpck_require__(4797); + if (!alg) { + throw new JWEInvalid('could not resolve a usable "alg" for a recipient') + } -var _kinds = __nccwpck_require__(11927); + if (recipientCount === 1) { + if (protectedHeader) { + protectedHeader.alg = alg + } else { + this._protected = { alg } + } + } else { + if (recipient.header) { + recipient.header.alg = alg + } else { + recipient.header = { alg } + } + } + } -var _predicates = __nccwpck_require__(20535); + let wrapped + let generatedHeader -var _directives = __nccwpck_require__(83614); + if (key.kty === 'oct' && alg === 'dir') { + this._cek = importKey(key[KEYOBJECT], { use: 'enc', alg: enc }) + } else { + check(this._cek, 'encrypt', enc) + ;({ wrapped, header: generatedHeader } = keyManagementEncrypt(alg, key, this._cek[KEYOBJECT].export(), { enc, alg })) + if (alg === 'ECDH-ES') { + this._cek = importKey(createSecretKey(wrapped), { use: 'enc', alg: enc }) + } + } -/** - * Unique directive names per location - * - * A GraphQL document is only valid if all non-repeatable directives at - * a given location are uniquely named. - * - * See https://spec.graphql.org/draft/#sec-Directives-Are-Unique-Per-Location - */ -function UniqueDirectivesPerLocationRule(context) { - const uniqueDirectiveMap = Object.create(null); - const schema = context.getSchema(); - const definedDirectives = schema - ? schema.getDirectives() - : _directives.specifiedDirectives; + if (alg === 'dir' || alg === 'ECDH-ES') { + recipient.encrypted_key = '' + } else { + recipient.encrypted_key = base64url.encodeBuffer(wrapped) + } - for (const directive of definedDirectives) { - uniqueDirectiveMap[directive.name] = !directive.isRepeatable; + if (generatedHeader) { + recipient.generatedHeader = generatedHeader + } } - const astDefinitions = context.getDocument().definitions; + /* + * @public + */ + encrypt (serialization) { + const serializer = serializers[serialization] + if (!serializer) { + throw new TypeError('serialization must be one of "compact", "flattened", "general"') + } - for (const def of astDefinitions) { - if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { - uniqueDirectiveMap[def.name.value] = !def.repeatable; + if (!this._recipients.length) { + throw new JWEInvalid('missing recipients') } - } - const schemaDirectives = Object.create(null); - const typeDirectivesMap = Object.create(null); - return { - // Many different AST nodes may contain directives. Rather than listing - // them all, just listen for entering any node, and check to see if it - // defines any directives. - enter(node) { - if (!('directives' in node) || !node.directives) { - return; + serializer.validate(this._protected, this._unprotected, this._aad, this._recipients) + + let enc = validateHeaders(this._protected, this._unprotected, this._recipients, false, this._protected ? this._protected.crit : undefined) + if (!enc) { + enc = 'A128CBC-HS256' + if (this._protected) { + this._protected.enc = enc + } else { + this._protected = { enc } } + } + const final = {} + this._cek = generateCEK(enc) - let seenDirectives; + for (const recipient of this._recipients) { + this[PROCESS_RECIPIENT](recipient) + } - if ( - node.kind === _kinds.Kind.SCHEMA_DEFINITION || - node.kind === _kinds.Kind.SCHEMA_EXTENSION - ) { - seenDirectives = schemaDirectives; - } else if ( - (0, _predicates.isTypeDefinitionNode)(node) || - (0, _predicates.isTypeExtensionNode)(node) - ) { - const typeName = node.name.value; - seenDirectives = typeDirectivesMap[typeName]; + const iv = generateIV(enc) + final.iv = base64url.encodeBuffer(iv) - if (seenDirectives === undefined) { - typeDirectivesMap[typeName] = seenDirectives = Object.create(null); - } - } else { - seenDirectives = Object.create(null); + if (this._recipients.length === 1 && this._recipients[0].generatedHeader) { + const [{ generatedHeader }] = this._recipients + delete this._recipients[0].generatedHeader + this._protected = { + ...this._protected, + ...generatedHeader } + } - for (const directive of node.directives) { - const directiveName = directive.name.value; + if (this._protected) { + final.protected = base64url.JSON.encode(this._protected) + } + final.unprotected = this._unprotected - if (uniqueDirectiveMap[directiveName]) { - if (seenDirectives[directiveName]) { - context.reportError( - new _GraphQLError.GraphQLError( - `The directive "@${directiveName}" can only be used once at this location.`, - { - nodes: [seenDirectives[directiveName], directive], - }, - ), - ); - } else { - seenDirectives[directiveName] = directive; - } - } - } - }, - }; -} + let aad + if (this._aad) { + final.aad = base64url.encode(this._aad) + aad = Buffer.concat([ + Buffer.from(final.protected || ''), + Buffer.from('.'), + Buffer.from(final.aad) + ]) + } else { + aad = Buffer.from(final.protected || '') + } + let cleartext = this._cleartext + if (this._protected && 'zip' in this._protected) { + cleartext = deflateRawSync(cleartext) + } -/***/ }), + const { ciphertext, tag } = encrypt(enc, this._cek, cleartext, { iv, aad }) + final.tag = base64url.encodeBuffer(tag) + final.ciphertext = base64url.encodeBuffer(ciphertext) -/***/ 44437: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return serializer(final, this._recipients) + } +} -"use strict"; +module.exports = Encrypt -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.UniqueEnumValueNamesRule = UniqueEnumValueNamesRule; +/***/ }), -var _GraphQLError = __nccwpck_require__(4797); +/***/ 15242: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var _definition = __nccwpck_require__(32150); +const { randomBytes } = __nccwpck_require__(6113) -/** - * Unique enum value names - * - * A GraphQL enum type is only valid if all its values are uniquely named. - */ -function UniqueEnumValueNamesRule(context) { - const schema = context.getSchema(); - const existingTypeMap = schema ? schema.getTypeMap() : Object.create(null); - const knownValueNames = Object.create(null); - return { - EnumTypeDefinition: checkValueUniqueness, - EnumTypeExtension: checkValueUniqueness, - }; +const { createSecretKey } = __nccwpck_require__(98921) +const { KEYLENGTHS } = __nccwpck_require__(15501) +const Key = __nccwpck_require__(50504) - function checkValueUniqueness(node) { - var _node$values; +module.exports = (alg) => { + const keyLength = KEYLENGTHS.get(alg) - const typeName = node.name.value; + if (!keyLength) { + return new Key({ type: 'secret' }) + } - if (!knownValueNames[typeName]) { - knownValueNames[typeName] = Object.create(null); - } // FIXME: https://github.com/graphql/graphql-js/issues/2203 + return new Key(createSecretKey(randomBytes(keyLength / 8)), { use: 'enc', alg }) +} - /* c8 ignore next */ - const valueNodes = - (_node$values = node.values) !== null && _node$values !== void 0 - ? _node$values - : []; - const valueNames = knownValueNames[typeName]; +/***/ }), - for (const valueDef of valueNodes) { - const valueName = valueDef.name.value; - const existingType = existingTypeMap[typeName]; +/***/ 72851: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if ( - (0, _definition.isEnumType)(existingType) && - existingType.getValue(valueName) - ) { - context.reportError( - new _GraphQLError.GraphQLError( - `Enum value "${typeName}.${valueName}" already exists in the schema. It cannot also be defined in this type extension.`, - { - nodes: valueDef.name, - }, - ), - ); - } else if (valueNames[valueName]) { - context.reportError( - new _GraphQLError.GraphQLError( - `Enum value "${typeName}.${valueName}" can only be defined once.`, - { - nodes: [valueNames[valueName], valueDef.name], - }, - ), - ); - } else { - valueNames[valueName] = valueDef.name; - } - } +const Encrypt = __nccwpck_require__(19094) +const decrypt = __nccwpck_require__(73607) - return false; - } +const single = (serialization, cleartext, key, protectedHeader, aad, unprotectedHeader) => { + return new Encrypt(cleartext, protectedHeader, aad, unprotectedHeader) + .recipient(key) + .encrypt(serialization) } +module.exports.Encrypt = Encrypt +module.exports.encrypt = single.bind(undefined, 'compact') +module.exports.encrypt.flattened = single.bind(undefined, 'flattened') +module.exports.encrypt.general = single.bind(undefined, 'general') + +module.exports.decrypt = decrypt + /***/ }), -/***/ 9502: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 5348: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const isObject = __nccwpck_require__(41805) +let validateCrit = __nccwpck_require__(530) +const { JWEInvalid } = __nccwpck_require__(52973) -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.UniqueFieldDefinitionNamesRule = UniqueFieldDefinitionNamesRule; +validateCrit = validateCrit.bind(undefined, JWEInvalid) -var _GraphQLError = __nccwpck_require__(4797); +const compactSerializer = (final, [recipient]) => { + return `${final.protected}.${recipient.encrypted_key}.${final.iv}.${final.ciphertext}.${final.tag}` +} +compactSerializer.validate = (protectedHeader, unprotectedHeader, aad, { 0: { header }, length }) => { + if (length !== 1 || aad || unprotectedHeader || header) { + throw new JWEInvalid('JWE Compact Serialization doesn\'t support multiple recipients, JWE unprotected headers or AAD') + } + validateCrit(protectedHeader, unprotectedHeader, protectedHeader ? protectedHeader.crit : undefined) +} -var _definition = __nccwpck_require__(32150); +const flattenedSerializer = (final, [recipient]) => { + const { header, encrypted_key: encryptedKey } = recipient -/** - * Unique field definition names - * - * A GraphQL complex type is only valid if all its fields are uniquely named. - */ -function UniqueFieldDefinitionNamesRule(context) { - const schema = context.getSchema(); - const existingTypeMap = schema ? schema.getTypeMap() : Object.create(null); - const knownFieldNames = Object.create(null); return { - InputObjectTypeDefinition: checkFieldUniqueness, - InputObjectTypeExtension: checkFieldUniqueness, - InterfaceTypeDefinition: checkFieldUniqueness, - InterfaceTypeExtension: checkFieldUniqueness, - ObjectTypeDefinition: checkFieldUniqueness, - ObjectTypeExtension: checkFieldUniqueness, - }; + ...(final.protected ? { protected: final.protected } : undefined), + ...(final.unprotected ? { unprotected: final.unprotected } : undefined), + ...(header ? { header } : undefined), + ...(encryptedKey ? { encrypted_key: encryptedKey } : undefined), + ...(final.aad ? { aad: final.aad } : undefined), + iv: final.iv, + ciphertext: final.ciphertext, + tag: final.tag + } +} +flattenedSerializer.validate = (protectedHeader, unprotectedHeader, aad, { 0: { header }, length }) => { + if (length !== 1) { + throw new JWEInvalid('Flattened JWE JSON Serialization doesn\'t support multiple recipients') + } + validateCrit(protectedHeader, { ...unprotectedHeader, ...header }, protectedHeader ? protectedHeader.crit : undefined) +} - function checkFieldUniqueness(node) { - var _node$fields; +const generalSerializer = (final, recipients) => { + const result = { + ...(final.protected ? { protected: final.protected } : undefined), + ...(final.unprotected ? { unprotected: final.unprotected } : undefined), + recipients: recipients.map(({ header, encrypted_key: encryptedKey, generatedHeader }) => { + if (!header && !encryptedKey && !generatedHeader) { + return false + } - const typeName = node.name.value; + return { + ...(header || generatedHeader ? { header: { ...header, ...generatedHeader } } : undefined), + ...(encryptedKey ? { encrypted_key: encryptedKey } : undefined) + } + }).filter(Boolean), + ...(final.aad ? { aad: final.aad } : undefined), + iv: final.iv, + ciphertext: final.ciphertext, + tag: final.tag + } - if (!knownFieldNames[typeName]) { - knownFieldNames[typeName] = Object.create(null); - } // FIXME: https://github.com/graphql/graphql-js/issues/2203 + if (!result.recipients.length) { + delete result.recipients + } - /* c8 ignore next */ + return result +} +generalSerializer.validate = (protectedHeader, unprotectedHeader, aad, recipients) => { + recipients.forEach(({ header }) => { + validateCrit(protectedHeader, { ...header, ...unprotectedHeader }, protectedHeader ? protectedHeader.crit : undefined) + }) +} - const fieldNodes = - (_node$fields = node.fields) !== null && _node$fields !== void 0 - ? _node$fields - : []; - const fieldNames = knownFieldNames[typeName]; +const isJSON = (input) => { + return isObject(input) && + typeof input.ciphertext === 'string' && + typeof input.iv === 'string' && + typeof input.tag === 'string' && + (input.unprotected === undefined || isObject(input.unprotected)) && + (input.protected === undefined || typeof input.protected === 'string') && + (input.aad === undefined || typeof input.aad === 'string') +} - for (const fieldDef of fieldNodes) { - const fieldName = fieldDef.name.value; +const isSingleRecipient = (input) => { + return (input.encrypted_key === undefined || typeof input.encrypted_key === 'string') && + (input.header === undefined || isObject(input.header)) +} - if (hasField(existingTypeMap[typeName], fieldName)) { - context.reportError( - new _GraphQLError.GraphQLError( - `Field "${typeName}.${fieldName}" already exists in the schema. It cannot also be defined in this type extension.`, - { - nodes: fieldDef.name, - }, - ), - ); - } else if (fieldNames[fieldName]) { - context.reportError( - new _GraphQLError.GraphQLError( - `Field "${typeName}.${fieldName}" can only be defined once.`, - { - nodes: [fieldNames[fieldName], fieldDef.name], - }, - ), - ); - } else { - fieldNames[fieldName] = fieldDef.name; - } - } +const isValidRecipient = (recipient) => { + return isObject(recipient) && typeof recipient.encrypted_key === 'string' && (recipient.header === undefined || isObject(recipient.header)) +} - return false; +const isMultiRecipient = (input) => { + if (Array.isArray(input.recipients) && input.recipients.every(isValidRecipient)) { + return true } + + return false } -function hasField(type, fieldName) { - if ( - (0, _definition.isObjectType)(type) || - (0, _definition.isInterfaceType)(type) || - (0, _definition.isInputObjectType)(type) - ) { - return type.getFields()[fieldName] != null; +const detect = (input) => { + if (typeof input === 'string' && input.split('.').length === 5) { + return 'compact' } - return false; + if (isJSON(input)) { + if (isMultiRecipient(input)) { + return 'general' + } + + if (isSingleRecipient(input)) { + return 'flattened' + } + } + + throw new JWEInvalid('JWE malformed or invalid serialization') +} + +module.exports = { + compact: compactSerializer, + flattened: flattenedSerializer, + general: generalSerializer, + detect } /***/ }), -/***/ 79402: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 46904: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const isDisjoint = __nccwpck_require__(29024) +const base64url = __nccwpck_require__(73385) +let validateCrit = __nccwpck_require__(530) +const { JWEInvalid, JOSENotSupported } = __nccwpck_require__(52973) +validateCrit = validateCrit.bind(undefined, JWEInvalid) -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.UniqueFragmentNamesRule = UniqueFragmentNamesRule; +module.exports = (prot, unprotected, recipients, checkAlgorithms, crit) => { + if (typeof prot === 'string') { + try { + prot = base64url.JSON.decode(prot) + } catch (err) { + throw new JWEInvalid('could not parse JWE protected header') + } + } -var _GraphQLError = __nccwpck_require__(4797); + let alg = [] + const enc = new Set() + if (!isDisjoint(prot, unprotected) || !recipients.every(({ header }) => { + if (typeof header === 'object') { + alg.push(header.alg) + enc.add(header.enc) + } + const combined = { ...unprotected, ...header } + validateCrit(prot, combined, crit) + if ('zip' in combined) { + throw new JWEInvalid('"zip" Header Parameter MUST be integrity protected') + } else if (prot && 'zip' in prot && prot.zip !== 'DEF') { + throw new JOSENotSupported('only "DEF" compression algorithm is supported') + } + return isDisjoint(header, prot) && isDisjoint(header, unprotected) + })) { + throw new JWEInvalid('JWE Shared Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint') + } -/** - * Unique fragment names - * - * A GraphQL document is only valid if all defined fragments have unique names. - * - * See https://spec.graphql.org/draft/#sec-Fragment-Name-Uniqueness - */ -function UniqueFragmentNamesRule(context) { - const knownFragmentNames = Object.create(null); - return { - OperationDefinition: () => false, + if (typeof prot === 'object') { + alg.push(prot.alg) + enc.add(prot.enc) + } + if (typeof unprotected === 'object') { + alg.push(unprotected.alg) + enc.add(unprotected.enc) + } - FragmentDefinition(node) { - const fragmentName = node.name.value; + alg = alg.filter(Boolean) + enc.delete(undefined) - if (knownFragmentNames[fragmentName]) { - context.reportError( - new _GraphQLError.GraphQLError( - `There can be only one fragment named "${fragmentName}".`, - { - nodes: [knownFragmentNames[fragmentName], node.name], - }, - ), - ); - } else { - knownFragmentNames[fragmentName] = node.name; - } + if (recipients.length !== 1) { + if (alg.includes('dir') || alg.includes('ECDH-ES')) { + throw new JWEInvalid('dir and ECDH-ES alg may only be used with a single recipient') + } + } - return false; - }, - }; + if (checkAlgorithms) { + if (alg.length !== recipients.length) { + throw new JWEInvalid('missing Key Management algorithm') + } + if (enc.size === 0) { + throw new JWEInvalid('missing Content Encryption algorithm') + } else if (enc.size !== 1) { + throw new JWEInvalid('there must only be one Content Encryption algorithm') + } + } else { + if (enc.size > 1) { + throw new JWEInvalid('there must only be one Content Encryption algorithm') + } + } + + return [...enc][0] } /***/ }), -/***/ 83552: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 39377: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const errors = __nccwpck_require__(52973) +const importKey = __nccwpck_require__(13468) -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.UniqueInputFieldNamesRule = UniqueInputFieldNamesRule; +const RSAKey = __nccwpck_require__(73242) +const ECKey = __nccwpck_require__(53426) +const OKPKey = __nccwpck_require__(24510) +const OctKey = __nccwpck_require__(50504) -var _invariant = __nccwpck_require__(28847); +const generate = async (kty, crvOrSize, params, generatePrivate = true) => { + switch (kty) { + case 'RSA': + return importKey( + await RSAKey.generate(crvOrSize, generatePrivate), + params + ) + case 'EC': + return importKey( + await ECKey.generate(crvOrSize, generatePrivate), + params + ) + case 'OKP': + return importKey( + await OKPKey.generate(crvOrSize, generatePrivate), + params + ) + case 'oct': + return importKey( + await OctKey.generate(crvOrSize, generatePrivate), + params + ) + default: + throw new errors.JOSENotSupported(`unsupported key type: ${kty}`) + } +} -var _GraphQLError = __nccwpck_require__(4797); +const generateSync = (kty, crvOrSize, params, generatePrivate = true) => { + switch (kty) { + case 'RSA': + return importKey(RSAKey.generateSync(crvOrSize, generatePrivate), params) + case 'EC': + return importKey(ECKey.generateSync(crvOrSize, generatePrivate), params) + case 'OKP': + return importKey(OKPKey.generateSync(crvOrSize, generatePrivate), params) + case 'oct': + return importKey(OctKey.generateSync(crvOrSize, generatePrivate), params) + default: + throw new errors.JOSENotSupported(`unsupported key type: ${kty}`) + } +} -/** - * Unique input field names - * - * A GraphQL input object value is only valid if all supplied fields are - * uniquely named. - * - * See https://spec.graphql.org/draft/#sec-Input-Object-Field-Uniqueness - */ -function UniqueInputFieldNamesRule(context) { - const knownNameStack = []; - let knownNames = Object.create(null); - return { - ObjectValue: { - enter() { - knownNameStack.push(knownNames); - knownNames = Object.create(null); - }, +module.exports.generate = generate +module.exports.generateSync = generateSync - leave() { - const prevKnownNames = knownNameStack.pop(); - prevKnownNames || (0, _invariant.invariant)(false); - knownNames = prevKnownNames; - }, - }, - ObjectField(node) { - const fieldName = node.name.value; +/***/ }), - if (knownNames[fieldName]) { - context.reportError( - new _GraphQLError.GraphQLError( - `There can be only one input field named "${fieldName}".`, - { - nodes: [knownNames[fieldName], node.name], - }, - ), - ); - } else { - knownNames[fieldName] = node.name; - } - }, - }; +/***/ 13468: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const { createPublicKey, createPrivateKey, createSecretKey, KeyObject } = __nccwpck_require__(98921) +const base64url = __nccwpck_require__(73385) +const isObject = __nccwpck_require__(41805) +const { jwkToPem } = __nccwpck_require__(69693) +const errors = __nccwpck_require__(52973) + +const RSAKey = __nccwpck_require__(73242) +const ECKey = __nccwpck_require__(53426) +const OKPKey = __nccwpck_require__(24510) +const OctKey = __nccwpck_require__(50504) + +const importable = new Set(['string', 'buffer', 'object']) + +const mergedParameters = (target = {}, source = {}) => { + return { + alg: source.alg, + key_ops: source.key_ops, + kid: source.kid, + use: source.use, + x5c: source.x5c, + x5t: source.x5t, + 'x5t#S256': source['x5t#S256'], + ...target + } } +const openSSHpublicKey = /^[a-zA-Z0-9-]+ AAAA(?:[0-9A-Za-z+/])+(?:==|=)?(?: .*)?$/ -/***/ }), +const asKey = (key, parameters, { calculateMissingRSAPrimes = false } = {}) => { + let privateKey, publicKey, secret -/***/ 94865: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (!importable.has(typeof key)) { + throw new TypeError('key argument must be a string, buffer or an object') + } -"use strict"; + if (parameters !== undefined && !isObject(parameters)) { + throw new TypeError('parameters argument must be a plain object when provided') + } + if (key instanceof KeyObject) { + switch (key.type) { + case 'private': + privateKey = key + break + case 'public': + publicKey = key + break + case 'secret': + secret = key + break + } + } else if (typeof key === 'object' && key && 'kty' in key && key.kty === 'oct') { // symmetric key + try { + secret = createSecretKey(base64url.decodeToBuffer(key.k)) + } catch (err) { + if (!('k' in key)) { + secret = { type: 'secret' } + } + } + parameters = mergedParameters(parameters, key) + } else if (typeof key === 'object' && key && 'kty' in key) { // assume JWK formatted asymmetric key + ({ calculateMissingRSAPrimes = false } = parameters || { calculateMissingRSAPrimes }) + let pem -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.UniqueOperationNamesRule = UniqueOperationNamesRule; + try { + pem = jwkToPem(key, { calculateMissingRSAPrimes }) + } catch (err) { + if (err instanceof errors.JOSEError) { + throw err + } + } -var _GraphQLError = __nccwpck_require__(4797); + if (pem && key.d) { + privateKey = createPrivateKey(pem) + } else if (pem) { + publicKey = createPublicKey(pem) + } -/** - * Unique operation names - * - * A GraphQL document is only valid if all defined operations have unique names. - * - * See https://spec.graphql.org/draft/#sec-Operation-Name-Uniqueness - */ -function UniqueOperationNamesRule(context) { - const knownOperationNames = Object.create(null); - return { - OperationDefinition(node) { - const operationName = node.name; + parameters = mergedParameters({}, key) + } else if (key && (typeof key === 'object' || typeof key === 'string')) { // | | passed to crypto.createPrivateKey or crypto.createPublicKey or passed to crypto.createSecretKey + try { + privateKey = createPrivateKey(key) + } catch (err) { + if (err instanceof errors.JOSEError) { + throw err + } + } - if (operationName) { - if (knownOperationNames[operationName.value]) { - context.reportError( - new _GraphQLError.GraphQLError( - `There can be only one operation named "${operationName.value}".`, - { - nodes: [ - knownOperationNames[operationName.value], - operationName, - ], - }, - ), - ); - } else { - knownOperationNames[operationName.value] = operationName; - } + try { + publicKey = createPublicKey(key) + if (key.startsWith('-----BEGIN CERTIFICATE-----') && (!parameters || !('x5c' in parameters))) { + parameters = mergedParameters(parameters, { + x5c: [key.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g, '')] + }) + } + } catch (err) { + if (err instanceof errors.JOSEError) { + throw err } + } - return false; - }, + try { + // this is to filter out invalid PEM keys and certs, i'll rather have them fail import then + // have them imported as symmetric "oct" keys + if (!key.includes('-----BEGIN') && !openSSHpublicKey.test(key.toString('ascii').replace(/[\r\n]/g, ''))) { + secret = createSecretKey(Buffer.isBuffer(key) ? key : Buffer.from(key)) + } + } catch (err) {} + } - FragmentDefinition: () => false, - }; + const keyObject = privateKey || publicKey || secret + + if (privateKey || publicKey) { + switch (keyObject.asymmetricKeyType) { + case 'rsa': + return new RSAKey(keyObject, parameters) + case 'ec': + return new ECKey(keyObject, parameters) + case 'ed25519': + case 'ed448': + case 'x25519': + case 'x448': + return new OKPKey(keyObject, parameters) + default: + throw new errors.JOSENotSupported('only RSA, EC and OKP asymmetric keys are supported') + } + } else if (secret) { + return new OctKey(keyObject, parameters) + } + + throw new errors.JWKImportFailed('key import failed') } +module.exports = asKey -/***/ }), -/***/ 31492: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ }), -"use strict"; +/***/ 67894: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const Key = __nccwpck_require__(57841) +const None = __nccwpck_require__(98012) +const EmbeddedJWK = __nccwpck_require__(40561) +const EmbeddedX5C = __nccwpck_require__(303) +const importKey = __nccwpck_require__(13468) +const generate = __nccwpck_require__(39377) -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.UniqueOperationTypesRule = UniqueOperationTypesRule; +module.exports = { + ...generate, + asKey: importKey, + isKey: input => input instanceof Key, + None, + EmbeddedJWK, + EmbeddedX5C +} -var _GraphQLError = __nccwpck_require__(4797); -/** - * Unique operation types - * - * A GraphQL document is only valid if it has only one type per operation. - */ -function UniqueOperationTypesRule(context) { - const schema = context.getSchema(); - const definedOperationTypes = Object.create(null); - const existingOperationTypes = schema - ? { - query: schema.getQueryType(), - mutation: schema.getMutationType(), - subscription: schema.getSubscriptionType(), - } - : {}; - return { - SchemaDefinition: checkOperationTypes, - SchemaExtension: checkOperationTypes, - }; +/***/ }), - function checkOperationTypes(node) { - var _node$operationTypes; +/***/ 57841: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // See: https://github.com/graphql/graphql-js/issues/2203 +const { strict: assert } = __nccwpck_require__(39491) +const { inspect } = __nccwpck_require__(73837) +const { EOL } = __nccwpck_require__(22037) - /* c8 ignore next */ - const operationTypesNodes = - (_node$operationTypes = node.operationTypes) !== null && - _node$operationTypes !== void 0 - ? _node$operationTypes - : []; +const { keyObjectSupported } = __nccwpck_require__(32457) +const { createPublicKey } = __nccwpck_require__(98921) +const { keyObjectToJWK } = __nccwpck_require__(69693) +const { + THUMBPRINT_MATERIAL, PUBLIC_MEMBERS, PRIVATE_MEMBERS, JWK_MEMBERS, KEYOBJECT, + USES_MAPPING, OPS, USES +} = __nccwpck_require__(15010) +const isObject = __nccwpck_require__(41805) +const thumbprint = __nccwpck_require__(82253) +const errors = __nccwpck_require__(52973) - for (const operationType of operationTypesNodes) { - const operation = operationType.operation; - const alreadyDefinedOperationType = definedOperationTypes[operation]; +const privateApi = Symbol('privateApi') +const { JWK } = __nccwpck_require__(15501) - if (existingOperationTypes[operation]) { - context.reportError( - new _GraphQLError.GraphQLError( - `Type for ${operation} already defined in the schema. It cannot be redefined.`, - { - nodes: operationType, - }, - ), - ); - } else if (alreadyDefinedOperationType) { - context.reportError( - new _GraphQLError.GraphQLError( - `There can be only one ${operation} type in schema.`, - { - nodes: [alreadyDefinedOperationType, operationType], - }, - ), - ); - } else { - definedOperationTypes[operation] = operationType; +class Key { + constructor (keyObject, { alg, use, kid, key_ops: ops, x5c, x5t, 'x5t#S256': x5t256 } = {}) { + if (use !== undefined) { + if (typeof use !== 'string' || !USES.has(use)) { + throw new TypeError('`use` must be either "sig" or "enc" string when provided') } } - return false; - } -} - + if (alg !== undefined) { + if (typeof alg !== 'string' || !alg) { + throw new TypeError('`alg` must be a non-empty string when provided') + } + } -/***/ }), + if (kid !== undefined) { + if (typeof kid !== 'string' || !kid) { + throw new TypeError('`kid` must be a non-empty string when provided') + } + } -/***/ 24316: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (ops !== undefined) { + if (!Array.isArray(ops) || !ops.length || ops.some(o => typeof o !== 'string')) { + throw new TypeError('`key_ops` must be a non-empty array of strings when provided') + } + ops = Array.from(new Set(ops)).filter(x => OPS.has(x)) + } -"use strict"; + if (ops && use) { + if ( + (use === 'enc' && ops.some(x => USES_MAPPING.sig.has(x))) || + (use === 'sig' && ops.some(x => USES_MAPPING.enc.has(x))) + ) { + throw new errors.JWKInvalid('inconsistent JWK "use" and "key_ops"') + } + } + if (keyObjectSupported && x5c !== undefined) { + if (!Array.isArray(x5c) || !x5c.length || x5c.some(c => typeof c !== 'string')) { + throw new TypeError('`x5c` must be an array of one or more PKIX certificates when provided') + } -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.UniqueTypeNamesRule = UniqueTypeNamesRule; + x5c.forEach((cert, i) => { + let publicKey + try { + publicKey = createPublicKey({ + key: `-----BEGIN CERTIFICATE-----${EOL}${(cert.match(/.{1,64}/g) || []).join(EOL)}${EOL}-----END CERTIFICATE-----`, format: 'pem' + }) + } catch (err) { + throw new errors.JWKInvalid(`\`x5c\` member at index ${i} is not a valid base64-encoded DER PKIX certificate`) + } + if (i === 0) { + try { + assert.deepEqual( + publicKey.export({ type: 'spki', format: 'der' }), + (keyObject.type === 'public' ? keyObject : createPublicKey(keyObject)).export({ type: 'spki', format: 'der' }) + ) + } catch (err) { + throw new errors.JWKInvalid('The key in the first `x5c` certificate MUST match the public key represented by the JWK') + } + } + }) + } -var _GraphQLError = __nccwpck_require__(4797); + Object.defineProperties(this, { + [KEYOBJECT]: { value: isObject(keyObject) ? undefined : keyObject }, + keyObject: { + get () { + if (!keyObjectSupported) { + throw new errors.JOSENotSupported('KeyObject class is not supported in your Node.js runtime version') + } -/** - * Unique type names - * - * A GraphQL document is only valid if all defined types have unique names. - */ -function UniqueTypeNamesRule(context) { - const knownTypeNames = Object.create(null); - const schema = context.getSchema(); - return { - ScalarTypeDefinition: checkTypeName, - ObjectTypeDefinition: checkTypeName, - InterfaceTypeDefinition: checkTypeName, - UnionTypeDefinition: checkTypeName, - EnumTypeDefinition: checkTypeName, - InputObjectTypeDefinition: checkTypeName, - }; + return this[KEYOBJECT] + } + }, + type: { value: keyObject.type }, + private: { value: keyObject.type === 'private' }, + public: { value: keyObject.type === 'public' }, + secret: { value: keyObject.type === 'secret' }, + alg: { value: alg, enumerable: alg !== undefined }, + use: { value: use, enumerable: use !== undefined }, + x5c: { + enumerable: x5c !== undefined, + ...(x5c ? { get () { return [...x5c] } } : { value: undefined }) + }, + key_ops: { + enumerable: ops !== undefined, + ...(ops ? { get () { return [...ops] } } : { value: undefined }) + }, + kid: { + enumerable: true, + ...(kid + ? { value: kid } + : { + get () { + Object.defineProperty(this, 'kid', { value: this.thumbprint, configurable: false }) + return this.kid + }, + configurable: true + }) + }, + ...(x5c + ? { + x5t: { + enumerable: true, + ...(x5t + ? { value: x5t } + : { + get () { + Object.defineProperty(this, 'x5t', { value: thumbprint.x5t(this.x5c[0]), configurable: false }) + return this.x5t + }, + configurable: true + }) + } + } + : undefined), + ...(x5c + ? { + 'x5t#S256': { + enumerable: true, + ...(x5t256 + ? { value: x5t256 } + : { + get () { + Object.defineProperty(this, 'x5t#S256', { value: thumbprint['x5t#S256'](this.x5c[0]), configurable: false }) + return this['x5t#S256'] + }, + configurable: true + }) + } + } + : undefined), + thumbprint: { + get () { + Object.defineProperty(this, 'thumbprint', { value: thumbprint.kid(this[THUMBPRINT_MATERIAL]()), configurable: false }) + return this.thumbprint + }, + configurable: true + } + }) + } - function checkTypeName(node) { - const typeName = node.name.value; + toPEM (priv = false, encoding = {}) { + if (this.secret) { + throw new TypeError('symmetric keys cannot be exported as PEM') + } - if (schema !== null && schema !== void 0 && schema.getType(typeName)) { - context.reportError( - new _GraphQLError.GraphQLError( - `Type "${typeName}" already exists in the schema. It cannot also be defined in this type definition.`, - { - nodes: node.name, - }, - ), - ); - return; + if (priv && this.public === true) { + throw new TypeError('public key cannot be exported as private') } - if (knownTypeNames[typeName]) { - context.reportError( - new _GraphQLError.GraphQLError( - `There can be only one type named "${typeName}".`, - { - nodes: [knownTypeNames[typeName], node.name], - }, - ), - ); - } else { - knownTypeNames[typeName] = node.name; + const { type = priv ? 'pkcs8' : 'spki', cipher, passphrase } = encoding + + let keyObject = this[KEYOBJECT] + + if (!priv) { + if (this.private) { + keyObject = createPublicKey(keyObject) + } + if (cipher || passphrase) { + throw new TypeError('cipher and passphrase can only be applied when exporting private keys') + } } - return false; + if (priv) { + return keyObject.export({ format: 'pem', type, cipher, passphrase }) + } + + return keyObject.export({ format: 'pem', type }) } -} + toJWK (priv = false) { + if (priv && this.public === true) { + throw new TypeError('public key cannot be exported as private') + } -/***/ }), + const components = [...this.constructor[priv ? PRIVATE_MEMBERS : PUBLIC_MEMBERS]] + .map(k => [k, this[k]]) -/***/ 65931: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + const result = {} -"use strict"; + Object.keys(components).forEach((key) => { + const [k, v] = components[key] + result[k] = v + }) -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.UniqueVariableNamesRule = UniqueVariableNamesRule; + result.kty = this.kty + result.kid = this.kid -var _groupBy = __nccwpck_require__(93173); + if (this.alg) { + result.alg = this.alg + } -var _GraphQLError = __nccwpck_require__(4797); + if (this.key_ops && this.key_ops.length) { + result.key_ops = this.key_ops + } -/** - * Unique variable names - * - * A GraphQL operation is only valid if all its variables are uniquely named. - */ -function UniqueVariableNamesRule(context) { - return { - OperationDefinition(operationNode) { - var _operationNode$variab; + if (this.use) { + result.use = this.use + } - // See: https://github.com/graphql/graphql-js/issues/2203 + if (this.x5c) { + result.x5c = this.x5c + } - /* c8 ignore next */ - const variableDefinitions = - (_operationNode$variab = operationNode.variableDefinitions) !== null && - _operationNode$variab !== void 0 - ? _operationNode$variab - : []; - const seenVariableDefinitions = (0, _groupBy.groupBy)( - variableDefinitions, - (node) => node.variable.name.value, - ); + if (this.x5t) { + result.x5t = this.x5t + } - for (const [variableName, variableNodes] of seenVariableDefinitions) { - if (variableNodes.length > 1) { - context.reportError( - new _GraphQLError.GraphQLError( - `There can be only one variable named "$${variableName}".`, - { - nodes: variableNodes.map((node) => node.variable.name), - }, - ), - ); - } + if (this['x5t#S256']) { + result['x5t#S256'] = this['x5t#S256'] + } + + return result + } + + [JWK_MEMBERS] () { + const props = this[KEYOBJECT].type === 'private' ? this.constructor[PRIVATE_MEMBERS] : this.constructor[PUBLIC_MEMBERS] + Object.defineProperties(this, [...props].reduce((acc, component) => { + acc[component] = { + get () { + const jwk = keyObjectToJWK(this[KEYOBJECT]) + Object.defineProperties( + this, + Object.entries(jwk) + .filter(([key]) => props.has(key)) + .reduce((acc, [key, value]) => { + acc[key] = { value, enumerable: this.constructor[PUBLIC_MEMBERS].has(key), configurable: false } + return acc + }, {}) + ) + + return this[component] + }, + enumerable: this.constructor[PUBLIC_MEMBERS].has(component), + configurable: true } - }, - }; -} + return acc + }, {})) + } + /* c8 ignore next 8 */ + [inspect.custom] () { + return `${this.constructor.name} ${inspect(this.toJWK(false), { + depth: Infinity, + colors: process.stdout.isTTY, + compact: false, + sorted: true + })}` + } -/***/ }), + /* c8 ignore next 3 */ + [THUMBPRINT_MATERIAL] () { + throw new Error(`"[THUMBPRINT_MATERIAL]()" is not implemented on ${this.constructor.name}`) + } -/***/ 85189: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + algorithms (operation, /* the rest is private API */ int, opts) { + const { use = this.use, alg = this.alg, key_ops: ops = this.key_ops } = int === privateApi ? opts : {} + if (alg) { + return new Set(this.algorithms(operation, privateApi, { alg: null, use, key_ops: ops }).has(alg) ? [alg] : undefined) + } -"use strict"; + if (typeof operation === 'symbol') { + try { + return this[operation]() + } catch (err) { + return new Set() + } + } + if (operation && ops && !ops.includes(operation)) { + return new Set() + } -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.ValuesOfCorrectTypeRule = ValuesOfCorrectTypeRule; + switch (operation) { + case 'decrypt': + case 'deriveKey': + case 'encrypt': + case 'sign': + case 'unwrapKey': + case 'verify': + case 'wrapKey': + return new Set(Object.entries(JWK[this.kty][operation]).map(([alg, fn]) => fn(this) ? alg : undefined).filter(Boolean)) + case undefined: + return new Set([ + ...this.algorithms('sign'), + ...this.algorithms('verify'), + ...this.algorithms('decrypt'), + ...this.algorithms('encrypt'), + ...this.algorithms('unwrapKey'), + ...this.algorithms('wrapKey'), + ...this.algorithms('deriveKey') + ]) + default: + throw new TypeError('invalid key operation') + } + } -var _didYouMean = __nccwpck_require__(42878); + /* c8 ignore next 3 */ + static async generate () { + throw new Error(`"static async generate()" is not implemented on ${this.name}`) + } -var _inspect = __nccwpck_require__(10102); + /* c8 ignore next 3 */ + static generateSync () { + throw new Error(`"static generateSync()" is not implemented on ${this.name}`) + } -var _keyMap = __nccwpck_require__(10711); + /* c8 ignore next 3 */ + static get [PUBLIC_MEMBERS] () { + throw new Error(`"static get [PUBLIC_MEMBERS]()" is not implemented on ${this.name}`) + } -var _suggestionList = __nccwpck_require__(57704); + /* c8 ignore next 3 */ + static get [PRIVATE_MEMBERS] () { + throw new Error(`"static get [PRIVATE_MEMBERS]()" is not implemented on ${this.name}`) + } +} -var _GraphQLError = __nccwpck_require__(4797); +module.exports = Key -var _kinds = __nccwpck_require__(11927); -var _printer = __nccwpck_require__(68203); +/***/ }), -var _definition = __nccwpck_require__(32150); +/***/ 53426: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Value literals of correct type - * - * A GraphQL document is only valid if all value literals are of the type - * expected at their position. - * - * See https://spec.graphql.org/draft/#sec-Values-of-Correct-Type - */ -function ValuesOfCorrectTypeRule(context) { - let variableDefinitions = {}; - return { - OperationDefinition: { - enter() { - variableDefinitions = {}; - }, - }, +const { generateKeyPairSync, generateKeyPair: async } = __nccwpck_require__(6113) +const { promisify } = __nccwpck_require__(73837) - VariableDefinition(definition) { - variableDefinitions[definition.variable.name.value] = definition; - }, +const { + THUMBPRINT_MATERIAL, JWK_MEMBERS, PUBLIC_MEMBERS, + PRIVATE_MEMBERS, KEY_MANAGEMENT_DECRYPT, KEY_MANAGEMENT_ENCRYPT +} = __nccwpck_require__(15010) +const { EC_CURVES } = __nccwpck_require__(15501) +const { keyObjectSupported } = __nccwpck_require__(32457) +const { createPublicKey, createPrivateKey } = __nccwpck_require__(98921) - ListValue(node) { - // Note: TypeInfo will traverse into a list's item type, so look to the - // parent input type to check if it is a list. - const type = (0, _definition.getNullableType)( - context.getParentInputType(), - ); +const errors = __nccwpck_require__(52973) - if (!(0, _definition.isListType)(type)) { - isValidValueNode(context, node); - return false; // Don't traverse further. - } - }, +const Key = __nccwpck_require__(57841) - ObjectValue(node) { - const type = (0, _definition.getNamedType)(context.getInputType()); +const generateKeyPair = promisify(async) - if (!(0, _definition.isInputObjectType)(type)) { - isValidValueNode(context, node); - return false; // Don't traverse further. - } // Ensure every required field exists. +const EC_PUBLIC = new Set(['crv', 'x', 'y']) +Object.freeze(EC_PUBLIC) +const EC_PRIVATE = new Set([...EC_PUBLIC, 'd']) +Object.freeze(EC_PRIVATE) - const fieldNodeMap = (0, _keyMap.keyMap)( - node.fields, - (field) => field.name.value, - ); +// Elliptic Curve Key Type +class ECKey extends Key { + constructor (...args) { + super(...args) + this[JWK_MEMBERS]() + Object.defineProperty(this, 'kty', { value: 'EC', enumerable: true }) + if (!EC_CURVES.has(this.crv)) { + throw new errors.JOSENotSupported('unsupported EC key curve') + } + } - for (const fieldDef of Object.values(type.getFields())) { - const fieldNode = fieldNodeMap[fieldDef.name]; + static get [PUBLIC_MEMBERS] () { + return EC_PUBLIC + } - if (!fieldNode && (0, _definition.isRequiredInputField)(fieldDef)) { - const typeStr = (0, _inspect.inspect)(fieldDef.type); - context.reportError( - new _GraphQLError.GraphQLError( - `Field "${type.name}.${fieldDef.name}" of required type "${typeStr}" was not provided.`, - { - nodes: node, - }, - ), - ); - } - } + static get [PRIVATE_MEMBERS] () { + return EC_PRIVATE + } - if (type.isOneOf) { - validateOneOfInputObject( - context, - node, - type, - fieldNodeMap, - variableDefinitions, - ); - } - }, + // https://tc39.github.io/ecma262/#sec-ordinaryownpropertykeys no need for any special + // JSON.stringify handling in V8 + [THUMBPRINT_MATERIAL] () { + return { crv: this.crv, kty: 'EC', x: this.x, y: this.y } + } - ObjectField(node) { - const parentType = (0, _definition.getNamedType)( - context.getParentInputType(), - ); - const fieldType = context.getInputType(); + [KEY_MANAGEMENT_ENCRYPT] () { + return this.algorithms('deriveKey') + } - if (!fieldType && (0, _definition.isInputObjectType)(parentType)) { - const suggestions = (0, _suggestionList.suggestionList)( - node.name.value, - Object.keys(parentType.getFields()), - ); - context.reportError( - new _GraphQLError.GraphQLError( - `Field "${node.name.value}" is not defined by type "${parentType.name}".` + - (0, _didYouMean.didYouMean)(suggestions), - { - nodes: node, - }, - ), - ); - } - }, + [KEY_MANAGEMENT_DECRYPT] () { + if (this.public) { + return new Set() + } + return this.algorithms('deriveKey') + } - NullValue(node) { - const type = context.getInputType(); + static async generate (crv = 'P-256', privat = true) { + if (!EC_CURVES.has(crv)) { + throw new errors.JOSENotSupported(`unsupported EC key curve: ${crv}`) + } - if ((0, _definition.isNonNullType)(type)) { - context.reportError( - new _GraphQLError.GraphQLError( - `Expected value of type "${(0, _inspect.inspect)( - type, - )}", found ${(0, _printer.print)(node)}.`, - { - nodes: node, - }, - ), - ); - } - }, + let privateKey, publicKey - EnumValue: (node) => isValidValueNode(context, node), - IntValue: (node) => isValidValueNode(context, node), - FloatValue: (node) => isValidValueNode(context, node), - StringValue: (node) => isValidValueNode(context, node), - BooleanValue: (node) => isValidValueNode(context, node), - }; -} -/** - * Any value literal may be a valid representation of a Scalar, depending on - * that scalar type. - */ + if (keyObjectSupported) { + ({ privateKey, publicKey } = await generateKeyPair('ec', { namedCurve: crv })) + return privat ? privateKey : publicKey + } -function isValidValueNode(context, node) { - // Report any error at the full type expected by the location. - const locationType = context.getInputType(); + ({ privateKey, publicKey } = await generateKeyPair('ec', { + namedCurve: crv, + publicKeyEncoding: { type: 'spki', format: 'pem' }, + privateKeyEncoding: { type: 'pkcs8', format: 'pem' } + })) - if (!locationType) { - return; + if (privat) { + return createPrivateKey(privateKey) + } else { + return createPublicKey(publicKey) + } } - const type = (0, _definition.getNamedType)(locationType); - - if (!(0, _definition.isLeafType)(type)) { - const typeStr = (0, _inspect.inspect)(locationType); - context.reportError( - new _GraphQLError.GraphQLError( - `Expected value of type "${typeStr}", found ${(0, _printer.print)( - node, - )}.`, - { - nodes: node, - }, - ), - ); - return; - } // Scalars and Enums determine if a literal value is valid via parseLiteral(), - // which may throw or return an invalid value to indicate failure. + static generateSync (crv = 'P-256', privat = true) { + if (!EC_CURVES.has(crv)) { + throw new errors.JOSENotSupported(`unsupported EC key curve: ${crv}`) + } - try { - const parseResult = type.parseLiteral( - node, - undefined, - /* variables */ - ); + let privateKey, publicKey - if (parseResult === undefined) { - const typeStr = (0, _inspect.inspect)(locationType); - context.reportError( - new _GraphQLError.GraphQLError( - `Expected value of type "${typeStr}", found ${(0, _printer.print)( - node, - )}.`, - { - nodes: node, - }, - ), - ); + if (keyObjectSupported) { + ({ privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: crv })) + return privat ? privateKey : publicKey } - } catch (error) { - const typeStr = (0, _inspect.inspect)(locationType); - if (error instanceof _GraphQLError.GraphQLError) { - context.reportError(error); + ({ privateKey, publicKey } = generateKeyPairSync('ec', { + namedCurve: crv, + publicKeyEncoding: { type: 'spki', format: 'pem' }, + privateKeyEncoding: { type: 'pkcs8', format: 'pem' } + })) + + if (privat) { + return createPrivateKey(privateKey) } else { - context.reportError( - new _GraphQLError.GraphQLError( - `Expected value of type "${typeStr}", found ${(0, _printer.print)( - node, - )}; ` + error.message, - { - nodes: node, - originalError: error, - }, - ), - ); + return createPublicKey(publicKey) } } } -function validateOneOfInputObject( - context, - node, - type, - fieldNodeMap, - variableDefinitions, -) { - var _fieldNodeMap$keys$; +module.exports = ECKey - const keys = Object.keys(fieldNodeMap); - const isNotExactlyOneField = keys.length !== 1; - if (isNotExactlyOneField) { - context.reportError( - new _GraphQLError.GraphQLError( - `OneOf Input Object "${type.name}" must specify exactly one key.`, - { - nodes: [node], - }, - ), - ); - return; - } +/***/ }), - const value = - (_fieldNodeMap$keys$ = fieldNodeMap[keys[0]]) === null || - _fieldNodeMap$keys$ === void 0 - ? void 0 - : _fieldNodeMap$keys$.value; - const isNullLiteral = !value || value.kind === _kinds.Kind.NULL; - const isVariable = - (value === null || value === void 0 ? void 0 : value.kind) === - _kinds.Kind.VARIABLE; +/***/ 40561: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (isNullLiteral) { - context.reportError( - new _GraphQLError.GraphQLError( - `Field "${type.name}.${keys[0]}" must be non-null.`, - { - nodes: [node], - }, - ), - ); - return; +const { inspect } = __nccwpck_require__(73837) + +const Key = __nccwpck_require__(57841) + +class EmbeddedJWK extends Key { + constructor () { + super({ type: 'embedded' }) + Object.defineProperties(this, { + kid: { value: undefined }, + kty: { value: undefined }, + thumbprint: { value: undefined }, + toJWK: { value: undefined }, + toPEM: { value: undefined } + }) } - if (isVariable) { - const variableName = value.name.value; - const definition = variableDefinitions[variableName]; - const isNullableVariable = - definition.type.kind !== _kinds.Kind.NON_NULL_TYPE; + /* c8 ignore next 3 */ + [inspect.custom] () { + return 'Embedded.JWK {}' + } - if (isNullableVariable) { - context.reportError( - new _GraphQLError.GraphQLError( - `Variable "${variableName}" must be non-nullable to be used for OneOf Input Object "${type.name}".`, - { - nodes: [node], - }, - ), - ); - } + algorithms () { + return new Set() } } +module.exports = new EmbeddedJWK() + /***/ }), -/***/ 99506: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 303: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const { inspect } = __nccwpck_require__(73837) +const Key = __nccwpck_require__(57841) -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.VariablesAreInputTypesRule = VariablesAreInputTypesRule; +class EmbeddedX5C extends Key { + constructor () { + super({ type: 'embedded' }) + Object.defineProperties(this, { + kid: { value: undefined }, + kty: { value: undefined }, + thumbprint: { value: undefined }, + toJWK: { value: undefined }, + toPEM: { value: undefined } + }) + } -var _GraphQLError = __nccwpck_require__(4797); + /* c8 ignore next 3 */ + [inspect.custom] () { + return 'Embedded.X5C {}' + } -var _printer = __nccwpck_require__(68203); + algorithms () { + return new Set() + } +} -var _definition = __nccwpck_require__(32150); +module.exports = new EmbeddedX5C() -var _typeFromAST = __nccwpck_require__(27664); -/** - * Variables are input types - * - * A GraphQL operation is only valid if all the variables it defines are of - * input types (scalar, enum, or input object). - * - * See https://spec.graphql.org/draft/#sec-Variables-Are-Input-Types - */ -function VariablesAreInputTypesRule(context) { - return { - VariableDefinition(node) { - const type = (0, _typeFromAST.typeFromAST)( - context.getSchema(), - node.type, - ); +/***/ }), - if (type !== undefined && !(0, _definition.isInputType)(type)) { - const variableName = node.variable.name.value; - const typeName = (0, _printer.print)(node.type); - context.reportError( - new _GraphQLError.GraphQLError( - `Variable "$${variableName}" cannot be non-input type "${typeName}".`, - { - nodes: node.type, - }, - ), - ); - } - }, - }; -} +/***/ 98012: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const { inspect } = __nccwpck_require__(73837) -/***/ }), +const Key = __nccwpck_require__(57841) -/***/ 8815: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +class NoneKey extends Key { + constructor () { + super({ type: 'unsecured' }, { alg: 'none' }) + Object.defineProperties(this, { + kid: { value: undefined }, + kty: { value: undefined }, + thumbprint: { value: undefined }, + toJWK: { value: undefined }, + toPEM: { value: undefined } + }) + } -"use strict"; + /* c8 ignore next 3 */ + [inspect.custom] () { + return 'None {}' + } + algorithms (operation) { + switch (operation) { + case 'sign': + case 'verify': + case undefined: + return new Set(['none']) + default: + return new Set() + } + } +} -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.VariablesInAllowedPositionRule = VariablesInAllowedPositionRule; +module.exports = new NoneKey() -var _inspect = __nccwpck_require__(10102); -var _GraphQLError = __nccwpck_require__(4797); +/***/ }), -var _kinds = __nccwpck_require__(11927); +/***/ 50504: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var _definition = __nccwpck_require__(32150); +const { randomBytes } = __nccwpck_require__(6113) -var _typeComparators = __nccwpck_require__(10333); +const { createSecretKey } = __nccwpck_require__(98921) +const base64url = __nccwpck_require__(73385) +const { + THUMBPRINT_MATERIAL, PUBLIC_MEMBERS, PRIVATE_MEMBERS, + KEY_MANAGEMENT_DECRYPT, KEY_MANAGEMENT_ENCRYPT, KEYOBJECT +} = __nccwpck_require__(15010) -var _typeFromAST = __nccwpck_require__(27664); +const Key = __nccwpck_require__(57841) -/** - * Variables in allowed position - * - * Variable usages must be compatible with the arguments they are passed to. - * - * See https://spec.graphql.org/draft/#sec-All-Variable-Usages-are-Allowed - */ -function VariablesInAllowedPositionRule(context) { - let varDefMap = Object.create(null); - return { - OperationDefinition: { - enter() { - varDefMap = Object.create(null); - }, +const OCT_PUBLIC = new Set() +Object.freeze(OCT_PUBLIC) +const OCT_PRIVATE = new Set(['k']) +Object.freeze(OCT_PRIVATE) - leave(operation) { - const usages = context.getRecursiveVariableUsages(operation); +// Octet sequence Key Type +class OctKey extends Key { + constructor (...args) { + super(...args) + Object.defineProperties(this, { + kty: { + value: 'oct', + enumerable: true + }, + length: { + value: this[KEYOBJECT] ? this[KEYOBJECT].symmetricKeySize * 8 : undefined + }, + k: { + enumerable: false, + get () { + if (this[KEYOBJECT]) { + Object.defineProperty(this, 'k', { + value: base64url.encodeBuffer(this[KEYOBJECT].export()), + configurable: false + }) + } else { + Object.defineProperty(this, 'k', { + value: undefined, + configurable: false + }) + } - for (const { node, type, defaultValue, parentType } of usages) { - const varName = node.name.value; - const varDef = varDefMap[varName]; + return this.k + }, + configurable: true + } + }) + } - if (varDef && type) { - // A var type is allowed if it is the same or more strict (e.g. is - // a subtype of) than the expected type. It can be more strict if - // the variable type is non-null when the expected type is nullable. - // If both are list types, the variable item type can be more strict - // than the expected item type (contravariant). - const schema = context.getSchema(); - const varType = (0, _typeFromAST.typeFromAST)(schema, varDef.type); + static get [PUBLIC_MEMBERS] () { + return OCT_PUBLIC + } - if ( - varType && - !allowedVariableUsage( - schema, - varType, - varDef.defaultValue, - type, - defaultValue, - ) - ) { - const varTypeStr = (0, _inspect.inspect)(varType); - const typeStr = (0, _inspect.inspect)(type); - context.reportError( - new _GraphQLError.GraphQLError( - `Variable "$${varName}" of type "${varTypeStr}" used in position expecting type "${typeStr}".`, - { - nodes: [varDef, node], - }, - ), - ); - } + static get [PRIVATE_MEMBERS] () { + return OCT_PRIVATE + } - if ( - (0, _definition.isInputObjectType)(parentType) && - parentType.isOneOf && - (0, _definition.isNullableType)(varType) - ) { - context.reportError( - new _GraphQLError.GraphQLError( - `Variable "$${varName}" is of type "${varType}" but must be non-nullable to be used for OneOf Input Object "${parentType}".`, - { - nodes: [varDef, node], - }, - ), - ); - } - } - } - }, - }, + // https://tc39.github.io/ecma262/#sec-ordinaryownpropertykeys no need for any special + // JSON.stringify handling in V8 + [THUMBPRINT_MATERIAL] () { + if (!this[KEYOBJECT]) { + throw new TypeError('reference "oct" keys without "k" cannot have their thumbprint calculated') + } + return { k: this.k, kty: 'oct' } + } - VariableDefinition(node) { - varDefMap[node.variable.name.value] = node; - }, - }; -} -/** - * Returns true if the variable is allowed in the location it was found, - * which includes considering if default values exist for either the variable - * or the location at which it is located. - */ + [KEY_MANAGEMENT_ENCRYPT] () { + return new Set([ + ...this.algorithms('wrapKey'), + ...this.algorithms('deriveKey') + ]) + } -function allowedVariableUsage( - schema, - varType, - varDefaultValue, - locationType, - locationDefaultValue, -) { - if ( - (0, _definition.isNonNullType)(locationType) && - !(0, _definition.isNonNullType)(varType) - ) { - const hasNonNullVariableDefaultValue = - varDefaultValue != null && varDefaultValue.kind !== _kinds.Kind.NULL; - const hasLocationDefaultValue = locationDefaultValue !== undefined; + [KEY_MANAGEMENT_DECRYPT] () { + return this[KEY_MANAGEMENT_ENCRYPT]() + } - if (!hasNonNullVariableDefaultValue && !hasLocationDefaultValue) { - return false; + algorithms (...args) { + if (!this[KEYOBJECT]) { + return new Set() } - const nullableLocationType = locationType.ofType; - return (0, _typeComparators.isTypeSubTypeOf)( - schema, - varType, - nullableLocationType, - ); + return Key.prototype.algorithms.call(this, ...args) } - return (0, _typeComparators.isTypeSubTypeOf)(schema, varType, locationType); + static async generate (...args) { + return this.generateSync(...args) + } + + static generateSync (len = 256, privat = true) { + if (!privat) { + throw new TypeError('"oct" keys cannot be generated as public') + } + if (!Number.isSafeInteger(len) || !len || len % 8 !== 0) { + throw new TypeError('invalid bit length') + } + + return createSecretKey(randomBytes(len / 8)) + } } +module.exports = OctKey + /***/ }), -/***/ 33915: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 24510: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const { generateKeyPairSync, generateKeyPair: async } = __nccwpck_require__(6113) +const { promisify } = __nccwpck_require__(73837) +const { + THUMBPRINT_MATERIAL, JWK_MEMBERS, PUBLIC_MEMBERS, + PRIVATE_MEMBERS, KEY_MANAGEMENT_DECRYPT, KEY_MANAGEMENT_ENCRYPT +} = __nccwpck_require__(15010) +const { OKP_CURVES } = __nccwpck_require__(15501) +const { edDSASupported } = __nccwpck_require__(32457) +const errors = __nccwpck_require__(52973) -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.NoDeprecatedCustomRule = NoDeprecatedCustomRule; +const Key = __nccwpck_require__(57841) -var _invariant = __nccwpck_require__(28847); +const generateKeyPair = promisify(async) -var _GraphQLError = __nccwpck_require__(4797); +const OKP_PUBLIC = new Set(['crv', 'x']) +Object.freeze(OKP_PUBLIC) +const OKP_PRIVATE = new Set([...OKP_PUBLIC, 'd']) +Object.freeze(OKP_PRIVATE) -var _definition = __nccwpck_require__(32150); +// Octet string key pairs Key Type +class OKPKey extends Key { + constructor (...args) { + super(...args) + this[JWK_MEMBERS]() + Object.defineProperty(this, 'kty', { value: 'OKP', enumerable: true }) + if (!OKP_CURVES.has(this.crv)) { + throw new errors.JOSENotSupported('unsupported OKP key curve') + } + } -/** - * No deprecated - * - * A GraphQL document is only valid if all selected fields and all used enum values have not been - * deprecated. - * - * Note: This rule is optional and is not part of the Validation section of the GraphQL - * Specification. The main purpose of this rule is detection of deprecated usages and not - * necessarily to forbid their use when querying a service. - */ -function NoDeprecatedCustomRule(context) { - return { - Field(node) { - const fieldDef = context.getFieldDef(); - const deprecationReason = - fieldDef === null || fieldDef === void 0 - ? void 0 - : fieldDef.deprecationReason; + static get [PUBLIC_MEMBERS] () { + return OKP_PUBLIC + } - if (fieldDef && deprecationReason != null) { - const parentType = context.getParentType(); - parentType != null || (0, _invariant.invariant)(false); - context.reportError( - new _GraphQLError.GraphQLError( - `The field ${parentType.name}.${fieldDef.name} is deprecated. ${deprecationReason}`, - { - nodes: node, - }, - ), - ); - } - }, + static get [PRIVATE_MEMBERS] () { + return OKP_PRIVATE + } - Argument(node) { - const argDef = context.getArgument(); - const deprecationReason = - argDef === null || argDef === void 0 - ? void 0 - : argDef.deprecationReason; + // https://tc39.github.io/ecma262/#sec-ordinaryownpropertykeys no need for any special + // JSON.stringify handling in V8 + [THUMBPRINT_MATERIAL] () { + return { crv: this.crv, kty: 'OKP', x: this.x } + } - if (argDef && deprecationReason != null) { - const directiveDef = context.getDirective(); + [KEY_MANAGEMENT_ENCRYPT] () { + return this.algorithms('deriveKey') + } - if (directiveDef != null) { - context.reportError( - new _GraphQLError.GraphQLError( - `Directive "@${directiveDef.name}" argument "${argDef.name}" is deprecated. ${deprecationReason}`, - { - nodes: node, - }, - ), - ); - } else { - const parentType = context.getParentType(); - const fieldDef = context.getFieldDef(); - (parentType != null && fieldDef != null) || - (0, _invariant.invariant)(false); - context.reportError( - new _GraphQLError.GraphQLError( - `Field "${parentType.name}.${fieldDef.name}" argument "${argDef.name}" is deprecated. ${deprecationReason}`, - { - nodes: node, - }, - ), - ); - } - } - }, + [KEY_MANAGEMENT_DECRYPT] () { + if (this.public) { + return new Set() + } + return this.algorithms('deriveKey') + } - ObjectField(node) { - const inputObjectDef = (0, _definition.getNamedType)( - context.getParentInputType(), - ); + static async generate (crv = 'Ed25519', privat = true) { + if (!edDSASupported) { + throw new errors.JOSENotSupported('OKP keys are not supported in your Node.js runtime version') + } - if ((0, _definition.isInputObjectType)(inputObjectDef)) { - const inputFieldDef = inputObjectDef.getFields()[node.name.value]; - const deprecationReason = - inputFieldDef === null || inputFieldDef === void 0 - ? void 0 - : inputFieldDef.deprecationReason; + if (!OKP_CURVES.has(crv)) { + throw new errors.JOSENotSupported(`unsupported OKP key curve: ${crv}`) + } - if (deprecationReason != null) { - context.reportError( - new _GraphQLError.GraphQLError( - `The input field ${inputObjectDef.name}.${inputFieldDef.name} is deprecated. ${deprecationReason}`, - { - nodes: node, - }, - ), - ); - } - } - }, + const { privateKey, publicKey } = await generateKeyPair(crv.toLowerCase()) - EnumValue(node) { - const enumValueDef = context.getEnumValue(); - const deprecationReason = - enumValueDef === null || enumValueDef === void 0 - ? void 0 - : enumValueDef.deprecationReason; + return privat ? privateKey : publicKey + } - if (enumValueDef && deprecationReason != null) { - const enumTypeDef = (0, _definition.getNamedType)( - context.getInputType(), - ); - enumTypeDef != null || (0, _invariant.invariant)(false); - context.reportError( - new _GraphQLError.GraphQLError( - `The enum value "${enumTypeDef.name}.${enumValueDef.name}" is deprecated. ${deprecationReason}`, - { - nodes: node, - }, - ), - ); - } - }, - }; + static generateSync (crv = 'Ed25519', privat = true) { + if (!edDSASupported) { + throw new errors.JOSENotSupported('OKP keys are not supported in your Node.js runtime version') + } + + if (!OKP_CURVES.has(crv)) { + throw new errors.JOSENotSupported(`unsupported OKP key curve: ${crv}`) + } + + const { privateKey, publicKey } = generateKeyPairSync(crv.toLowerCase()) + + return privat ? privateKey : publicKey + } } +module.exports = OKPKey -/***/ }), -/***/ 39478: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ }), -"use strict"; +/***/ 73242: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const { generateKeyPairSync, generateKeyPair: async } = __nccwpck_require__(6113) +const { promisify } = __nccwpck_require__(73837) -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.NoSchemaIntrospectionCustomRule = NoSchemaIntrospectionCustomRule; +const { + THUMBPRINT_MATERIAL, JWK_MEMBERS, PUBLIC_MEMBERS, + PRIVATE_MEMBERS, KEY_MANAGEMENT_DECRYPT, KEY_MANAGEMENT_ENCRYPT +} = __nccwpck_require__(15010) +const { keyObjectSupported } = __nccwpck_require__(32457) +const { createPublicKey, createPrivateKey } = __nccwpck_require__(98921) -var _GraphQLError = __nccwpck_require__(4797); +const Key = __nccwpck_require__(57841) -var _definition = __nccwpck_require__(32150); +const generateKeyPair = promisify(async) -var _introspection = __nccwpck_require__(28344); +const RSA_PUBLIC = new Set(['e', 'n']) +Object.freeze(RSA_PUBLIC) +const RSA_PRIVATE = new Set([...RSA_PUBLIC, 'd', 'p', 'q', 'dp', 'dq', 'qi']) +Object.freeze(RSA_PRIVATE) -/** - * Prohibit introspection queries - * - * A GraphQL document is only valid if all fields selected are not fields that - * return an introspection type. - * - * Note: This rule is optional and is not part of the Validation section of the - * GraphQL Specification. This rule effectively disables introspection, which - * does not reflect best practices and should only be done if absolutely necessary. - */ -function NoSchemaIntrospectionCustomRule(context) { - return { - Field(node) { - const type = (0, _definition.getNamedType)(context.getType()); +// RSA Key Type +class RSAKey extends Key { + constructor (...args) { + super(...args) + this[JWK_MEMBERS]() + Object.defineProperties(this, { + kty: { + value: 'RSA', + enumerable: true + }, + length: { + get () { + Object.defineProperty(this, 'length', { + value: Buffer.byteLength(this.n, 'base64') * 8, + configurable: false + }) - if (type && (0, _introspection.isIntrospectionType)(type)) { - context.reportError( - new _GraphQLError.GraphQLError( - `GraphQL introspection has been disabled, but the requested query contained the field "${node.name.value}".`, - { - nodes: node, - }, - ), - ); + return this.length + }, + configurable: true } - }, - }; -} - + }) + } -/***/ }), + static get [PUBLIC_MEMBERS] () { + return RSA_PUBLIC + } -/***/ 61556: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + static get [PRIVATE_MEMBERS] () { + return RSA_PRIVATE + } -"use strict"; + // https://tc39.github.io/ecma262/#sec-ordinaryownpropertykeys no need for any special + // JSON.stringify handling in V8 + [THUMBPRINT_MATERIAL] () { + return { e: this.e, kty: 'RSA', n: this.n } + } + [KEY_MANAGEMENT_ENCRYPT] () { + return this.algorithms('wrapKey') + } -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.specifiedSDLRules = - exports.specifiedRules = - exports.recommendedRules = - void 0; + [KEY_MANAGEMENT_DECRYPT] () { + return this.algorithms('unwrapKey') + } -var _ExecutableDefinitionsRule = __nccwpck_require__(89199); + static async generate (len = 2048, privat = true) { + if (!Number.isSafeInteger(len) || len < 512 || len % 8 !== 0 || (('electron' in process.versions) && len % 128 !== 0)) { + throw new TypeError('invalid bit length') + } -var _FieldsOnCorrectTypeRule = __nccwpck_require__(63016); + let privateKey, publicKey -var _FragmentsOnCompositeTypesRule = __nccwpck_require__(60381); + if (keyObjectSupported) { + ({ privateKey, publicKey } = await generateKeyPair('rsa', { modulusLength: len })) + return privat ? privateKey : publicKey + } -var _KnownArgumentNamesRule = __nccwpck_require__(67147); + ({ privateKey, publicKey } = await generateKeyPair('rsa', { + modulusLength: len, + publicKeyEncoding: { type: 'spki', format: 'pem' }, + privateKeyEncoding: { type: 'pkcs8', format: 'pem' } + })) -var _KnownDirectivesRule = __nccwpck_require__(85303); + if (privat) { + return createPrivateKey(privateKey) + } else { + return createPublicKey(publicKey) + } + } -var _KnownFragmentNamesRule = __nccwpck_require__(15166); + static generateSync (len = 2048, privat = true) { + if (!Number.isSafeInteger(len) || len < 512 || len % 8 !== 0 || (('electron' in process.versions) && len % 128 !== 0)) { + throw new TypeError('invalid bit length') + } -var _KnownTypeNamesRule = __nccwpck_require__(42509); + let privateKey, publicKey -var _LoneAnonymousOperationRule = __nccwpck_require__(45726); + if (keyObjectSupported) { + ({ privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: len })) + return privat ? privateKey : publicKey + } -var _LoneSchemaDefinitionRule = __nccwpck_require__(48307); + ({ privateKey, publicKey } = generateKeyPairSync('rsa', { + modulusLength: len, + publicKeyEncoding: { type: 'spki', format: 'pem' }, + privateKeyEncoding: { type: 'pkcs8', format: 'pem' } + })) -var _MaxIntrospectionDepthRule = __nccwpck_require__(53318); + if (privat) { + return createPrivateKey(privateKey) + } else { + return createPublicKey(publicKey) + } + } +} -var _NoFragmentCyclesRule = __nccwpck_require__(62564); +module.exports = RSAKey -var _NoUndefinedVariablesRule = __nccwpck_require__(61671); -var _NoUnusedFragmentsRule = __nccwpck_require__(192); +/***/ }), -var _NoUnusedVariablesRule = __nccwpck_require__(40242); +/***/ 82253: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var _OverlappingFieldsCanBeMergedRule = __nccwpck_require__(23577); +const { createHash } = __nccwpck_require__(6113) -var _PossibleFragmentSpreadsRule = __nccwpck_require__(62450); +const base64url = __nccwpck_require__(73385) -var _PossibleTypeExtensionsRule = __nccwpck_require__(70075); +const x5t = (hash, cert) => base64url.encodeBuffer(createHash(hash).update(Buffer.from(cert, 'base64')).digest()) -var _ProvidedRequiredArgumentsRule = __nccwpck_require__(57669); +module.exports.kid = components => base64url.encodeBuffer(createHash('sha256').update(JSON.stringify(components)).digest()) +module.exports.x5t = x5t.bind(undefined, 'sha1') +module.exports["x5t#S256"] = x5t.bind(undefined, 'sha256') -var _ScalarLeafsRule = __nccwpck_require__(16830); -var _SingleFieldSubscriptionsRule = __nccwpck_require__(4365); +/***/ }), -var _UniqueArgumentDefinitionNamesRule = __nccwpck_require__(55104); +/***/ 42896: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var _UniqueArgumentNamesRule = __nccwpck_require__(45799); +const KeyStore = __nccwpck_require__(24998) -var _UniqueDirectiveNamesRule = __nccwpck_require__(17074); +module.exports = KeyStore -var _UniqueDirectivesPerLocationRule = __nccwpck_require__(61944); -var _UniqueEnumValueNamesRule = __nccwpck_require__(44437); +/***/ }), -var _UniqueFieldDefinitionNamesRule = __nccwpck_require__(9502); +/***/ 24998: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var _UniqueFragmentNamesRule = __nccwpck_require__(79402); +const { inspect } = __nccwpck_require__(73837) -var _UniqueInputFieldNamesRule = __nccwpck_require__(83552); +const isObject = __nccwpck_require__(41805) +const { generate, generateSync } = __nccwpck_require__(39377) +const { USES_MAPPING } = __nccwpck_require__(15010) +const { isKey, asKey: importKey } = __nccwpck_require__(67894) -var _UniqueOperationNamesRule = __nccwpck_require__(94865); +const keyscore = (key, { alg, use, ops }) => { + let score = 0 -var _UniqueOperationTypesRule = __nccwpck_require__(31492); + if (alg && key.alg) { + score++ + } -var _UniqueTypeNamesRule = __nccwpck_require__(24316); + if (use && key.use) { + score++ + } -var _UniqueVariableNamesRule = __nccwpck_require__(65931); + if (ops && key.key_ops) { + score++ + } -var _ValuesOfCorrectTypeRule = __nccwpck_require__(85189); + return score +} -var _VariablesAreInputTypesRule = __nccwpck_require__(99506); +class KeyStore { + constructor (...keys) { + while (keys.some(Array.isArray)) { + keys = keys.flat + ? keys.flat() + : keys.reduce((acc, val) => { + if (Array.isArray(val)) { + return [...acc, ...val] + } -var _VariablesInAllowedPositionRule = __nccwpck_require__(8815); + acc.push(val) + return acc + }, []) + } + if (keys.some(k => !isKey(k) || !k.kty)) { + throw new TypeError('all keys must be instances of a key instantiated by JWK.asKey') + } -// Spec Section: "Executable Definitions" -// Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" -// Spec Section: "Fragments on Composite Types" -// Spec Section: "Argument Names" -// Spec Section: "Directives Are Defined" -// Spec Section: "Fragment spread target defined" -// Spec Section: "Fragment Spread Type Existence" -// Spec Section: "Lone Anonymous Operation" -// SDL-specific validation rules -// TODO: Spec Section -// Spec Section: "Fragments must not form cycles" -// Spec Section: "All Variable Used Defined" -// Spec Section: "Fragments must be used" -// Spec Section: "All Variables Used" -// Spec Section: "Field Selection Merging" -// Spec Section: "Fragment spread is possible" -// Spec Section: "Argument Optionality" -// Spec Section: "Leaf Field Selections" -// Spec Section: "Subscriptions with Single Root Field" -// Spec Section: "Argument Uniqueness" -// Spec Section: "Directives Are Unique Per Location" -// Spec Section: "Fragment Name Uniqueness" -// Spec Section: "Input Object Field Uniqueness" -// Spec Section: "Operation Name Uniqueness" -// Spec Section: "Variable Uniqueness" -// Spec Section: "Value Type Correctness" -// Spec Section: "Variables are Input Types" -// Spec Section: "All Variable Usages Are Allowed" + this._keys = new Set(keys) + } -/** - * Technically these aren't part of the spec but they are strongly encouraged - * validation rules. - */ -const recommendedRules = Object.freeze([ - _MaxIntrospectionDepthRule.MaxIntrospectionDepthRule, -]); -/** - * This set includes all validation rules defined by the GraphQL spec. - * - * The order of the rules in this list has been adjusted to lead to the - * most clear output when encountering multiple validation errors. - */ + all ({ alg, kid, thumbprint, use, kty, key_ops: ops, x5t, 'x5t#S256': x5t256, crv } = {}) { + if (ops !== undefined && (!Array.isArray(ops) || !ops.length || ops.some(x => typeof x !== 'string'))) { + throw new TypeError('`key_ops` must be a non-empty array of strings') + } -exports.recommendedRules = recommendedRules; -const specifiedRules = Object.freeze([ - _ExecutableDefinitionsRule.ExecutableDefinitionsRule, - _UniqueOperationNamesRule.UniqueOperationNamesRule, - _LoneAnonymousOperationRule.LoneAnonymousOperationRule, - _SingleFieldSubscriptionsRule.SingleFieldSubscriptionsRule, - _KnownTypeNamesRule.KnownTypeNamesRule, - _FragmentsOnCompositeTypesRule.FragmentsOnCompositeTypesRule, - _VariablesAreInputTypesRule.VariablesAreInputTypesRule, - _ScalarLeafsRule.ScalarLeafsRule, - _FieldsOnCorrectTypeRule.FieldsOnCorrectTypeRule, - _UniqueFragmentNamesRule.UniqueFragmentNamesRule, - _KnownFragmentNamesRule.KnownFragmentNamesRule, - _NoUnusedFragmentsRule.NoUnusedFragmentsRule, - _PossibleFragmentSpreadsRule.PossibleFragmentSpreadsRule, - _NoFragmentCyclesRule.NoFragmentCyclesRule, - _UniqueVariableNamesRule.UniqueVariableNamesRule, - _NoUndefinedVariablesRule.NoUndefinedVariablesRule, - _NoUnusedVariablesRule.NoUnusedVariablesRule, - _KnownDirectivesRule.KnownDirectivesRule, - _UniqueDirectivesPerLocationRule.UniqueDirectivesPerLocationRule, - _KnownArgumentNamesRule.KnownArgumentNamesRule, - _UniqueArgumentNamesRule.UniqueArgumentNamesRule, - _ValuesOfCorrectTypeRule.ValuesOfCorrectTypeRule, - _ProvidedRequiredArgumentsRule.ProvidedRequiredArgumentsRule, - _VariablesInAllowedPositionRule.VariablesInAllowedPositionRule, - _OverlappingFieldsCanBeMergedRule.OverlappingFieldsCanBeMergedRule, - _UniqueInputFieldNamesRule.UniqueInputFieldNamesRule, - ...recommendedRules, -]); -/** - * @internal - */ + const search = { alg, use, ops } + return [...this._keys] + .filter((key) => { + let candidate = true -exports.specifiedRules = specifiedRules; -const specifiedSDLRules = Object.freeze([ - _LoneSchemaDefinitionRule.LoneSchemaDefinitionRule, - _UniqueOperationTypesRule.UniqueOperationTypesRule, - _UniqueTypeNamesRule.UniqueTypeNamesRule, - _UniqueEnumValueNamesRule.UniqueEnumValueNamesRule, - _UniqueFieldDefinitionNamesRule.UniqueFieldDefinitionNamesRule, - _UniqueArgumentDefinitionNamesRule.UniqueArgumentDefinitionNamesRule, - _UniqueDirectiveNamesRule.UniqueDirectiveNamesRule, - _KnownTypeNamesRule.KnownTypeNamesRule, - _KnownDirectivesRule.KnownDirectivesRule, - _UniqueDirectivesPerLocationRule.UniqueDirectivesPerLocationRule, - _PossibleTypeExtensionsRule.PossibleTypeExtensionsRule, - _KnownArgumentNamesRule.KnownArgumentNamesOnDirectivesRule, - _UniqueArgumentNamesRule.UniqueArgumentNamesRule, - _UniqueInputFieldNamesRule.UniqueInputFieldNamesRule, - _ProvidedRequiredArgumentsRule.ProvidedRequiredArgumentsOnDirectivesRule, -]); -exports.specifiedSDLRules = specifiedSDLRules; + if (candidate && kid !== undefined && key.kid !== kid) { + candidate = false + } + if (candidate && thumbprint !== undefined && key.thumbprint !== thumbprint) { + candidate = false + } -/***/ }), + if (candidate && x5t !== undefined && key.x5t !== x5t) { + candidate = false + } -/***/ 14193: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (candidate && x5t256 !== undefined && key['x5t#S256'] !== x5t256) { + candidate = false + } -"use strict"; + if (candidate && kty !== undefined && key.kty !== kty) { + candidate = false + } + if (candidate && crv !== undefined && (key.crv !== crv)) { + candidate = false + } -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.assertValidSDL = assertValidSDL; -exports.assertValidSDLExtension = assertValidSDLExtension; -exports.validate = validate; -exports.validateSDL = validateSDL; + if (alg !== undefined && !key.algorithms().has(alg)) { + candidate = false + } -var _devAssert = __nccwpck_require__(46514); + if (candidate && use !== undefined && (key.use !== undefined && key.use !== use)) { + candidate = false + } -var _GraphQLError = __nccwpck_require__(4797); + // TODO: + if (candidate && ops !== undefined && (key.key_ops !== undefined || key.use !== undefined)) { + let keyOps + if (key.key_ops) { + keyOps = new Set(key.key_ops) + } else { + keyOps = USES_MAPPING[key.use] + } + if (ops.some(x => !keyOps.has(x))) { + candidate = false + } + } -var _visitor = __nccwpck_require__(5678); + return candidate + }) + .sort((first, second) => keyscore(second, search) - keyscore(first, search)) + } -var _validate = __nccwpck_require__(22430); + get (...args) { + return this.all(...args)[0] + } -var _TypeInfo = __nccwpck_require__(76625); + add (key) { + if (!isKey(key) || !key.kty) { + throw new TypeError('key must be an instance of a key instantiated by JWK.asKey') + } -var _specifiedRules = __nccwpck_require__(61556); + this._keys.add(key) + } -var _ValidationContext = __nccwpck_require__(28263); + remove (key) { + if (!isKey(key)) { + throw new TypeError('key must be an instance of a key instantiated by JWK.asKey') + } -/** - * Implements the "Validation" section of the spec. - * - * Validation runs synchronously, returning an array of encountered errors, or - * an empty array if no errors were encountered and the document is valid. - * - * A list of specific validation rules may be provided. If not provided, the - * default list of rules defined by the GraphQL specification will be used. - * - * Each validation rules is a function which returns a visitor - * (see the language/visitor API). Visitor methods are expected to return - * GraphQLErrors, or Arrays of GraphQLErrors when invalid. - * - * Validate will stop validation after a `maxErrors` limit has been reached. - * Attackers can send pathologically invalid queries to induce a DoS attack, - * so by default `maxErrors` set to 100 errors. - * - * Optionally a custom TypeInfo instance may be provided. If not provided, one - * will be created from the provided schema. - */ -function validate( - schema, - documentAST, - rules = _specifiedRules.specifiedRules, - options, - /** @deprecated will be removed in 17.0.0 */ - typeInfo = new _TypeInfo.TypeInfo(schema), -) { - var _options$maxErrors; + this._keys.delete(key) + } - const maxErrors = - (_options$maxErrors = - options === null || options === void 0 ? void 0 : options.maxErrors) !== - null && _options$maxErrors !== void 0 - ? _options$maxErrors - : 100; - documentAST || (0, _devAssert.devAssert)(false, 'Must provide document.'); // If the schema used for validation is invalid, throw an error. + toJWKS (priv = false) { + return { + keys: [...this._keys.values()].map( + key => key.toJWK(priv && (key.private || (key.secret && key.k))) + ) + } + } - (0, _validate.assertValidSchema)(schema); - const abortObj = Object.freeze({}); - const errors = []; - const context = new _ValidationContext.ValidationContext( - schema, - documentAST, - typeInfo, - (error) => { - if (errors.length >= maxErrors) { - errors.push( - new _GraphQLError.GraphQLError( - 'Too many validation errors, error limit reached. Validation aborted.', - ), - ); // eslint-disable-next-line @typescript-eslint/no-throw-literal + async generate (...args) { + this._keys.add(await generate(...args)) + } - throw abortObj; - } + generateSync (...args) { + this._keys.add(generateSync(...args)) + } - errors.push(error); - }, - ); // This uses a specialized visitor which runs multiple visitors in parallel, - // while maintaining the visitor skip and break API. + get size () { + return this._keys.size + } - const visitor = (0, _visitor.visitInParallel)( - rules.map((rule) => rule(context)), - ); // Visit the whole document with each instance of all provided rules. + /* c8 ignore next 8 */ + [inspect.custom] () { + return `${this.constructor.name} ${inspect(this.toJWKS(false), { + depth: Infinity, + colors: process.stdout.isTTY, + compact: false, + sorted: true + })}` + } - try { - (0, _visitor.visit)( - documentAST, - (0, _TypeInfo.visitWithTypeInfo)(typeInfo, visitor), - ); - } catch (e) { - if (e !== abortObj) { - throw e; + * [Symbol.iterator] () { + for (const key of this._keys) { + yield key } } - - return errors; -} -/** - * @internal - */ - -function validateSDL( - documentAST, - schemaToExtend, - rules = _specifiedRules.specifiedSDLRules, -) { - const errors = []; - const context = new _ValidationContext.SDLValidationContext( - documentAST, - schemaToExtend, - (error) => { - errors.push(error); - }, - ); - const visitors = rules.map((rule) => rule(context)); - (0, _visitor.visit)(documentAST, (0, _visitor.visitInParallel)(visitors)); - return errors; } -/** - * Utility function which asserts a SDL document is valid by throwing an error - * if it is invalid. - * - * @internal - */ - -function assertValidSDL(documentAST) { - const errors = validateSDL(documentAST); - if (errors.length !== 0) { - throw new Error(errors.map((error) => error.message).join('\n\n')); +function asKeyStore (jwks, { ignoreErrors = false, calculateMissingRSAPrimes = false } = {}) { + if (!isObject(jwks) || !Array.isArray(jwks.keys) || jwks.keys.some(k => !isObject(k) || !('kty' in k))) { + throw new TypeError('jwks must be a JSON Web Key Set formatted object') } -} -/** - * Utility function which asserts a SDL document is valid by throwing an error - * if it is invalid. - * - * @internal - */ -function assertValidSDLExtension(documentAST, schema) { - const errors = validateSDL(documentAST, schema); + const keys = jwks.keys.map((jwk) => { + try { + return importKey(jwk, { calculateMissingRSAPrimes }) + } catch (err) { + if (!ignoreErrors) { + throw err + } + return undefined + } + }).filter(Boolean) - if (errors.length !== 0) { - throw new Error(errors.map((error) => error.message).join('\n\n')); - } + return new KeyStore(...keys) } +module.exports = { KeyStore, asKeyStore } -/***/ }), -/***/ 81923: -/***/ ((__unused_webpack_module, exports) => { +/***/ }), -"use strict"; +/***/ 36518: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const Sign = __nccwpck_require__(1728) +const { verify } = __nccwpck_require__(39835) -Object.defineProperty(exports, "__esModule", ({ - value: true, -})); -exports.versionInfo = exports.version = void 0; -// Note: This file is autogenerated using "resources/gen-version.js" script and -// automatically updated by "npm version" command. +const single = (serialization, payload, key, protectedHeader, unprotectedHeader) => { + return new Sign(payload) + .recipient(key, protectedHeader, unprotectedHeader) + .sign(serialization) +} -/** - * A string containing the version of the GraphQL.js library - */ -const version = '16.11.0'; -/** - * An object containing the components of the GraphQL.js version string - */ +module.exports.Sign = Sign +module.exports.sign = single.bind(undefined, 'compact') +module.exports.sign.flattened = single.bind(undefined, 'flattened') +module.exports.sign.general = single.bind(undefined, 'general') -exports.version = version; -const versionInfo = Object.freeze({ - major: 16, - minor: 11, - patch: 0, - preReleaseTag: null, -}); -exports.versionInfo = versionInfo; +module.exports.verify = verify /***/ }), -/***/ 13679: +/***/ 28104: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const isObject = __nccwpck_require__(41805) +let validateCrit = __nccwpck_require__(530) +const { JWSInvalid } = __nccwpck_require__(52973) +validateCrit = validateCrit.bind(undefined, JWSInvalid) -module.exports = { - afterRequest: __nccwpck_require__(83932), - beforeRequest: __nccwpck_require__(36136), - browser: __nccwpck_require__(805), - cache: __nccwpck_require__(51632), - content: __nccwpck_require__(61567), - cookie: __nccwpck_require__(25725), - creator: __nccwpck_require__(47218), - entry: __nccwpck_require__(74560), - har: __nccwpck_require__(75579), - header: __nccwpck_require__(75147), - log: __nccwpck_require__(53013), - page: __nccwpck_require__(34777), - pageTimings: __nccwpck_require__(5538), - postData: __nccwpck_require__(12096), - query: __nccwpck_require__(21251), - request: __nccwpck_require__(99646), - response: __nccwpck_require__(9103), - timings: __nccwpck_require__(22007) +const compactSerializer = (payload, [recipient]) => { + return `${recipient.protected}.${payload}.${recipient.signature}` +} +compactSerializer.validate = (jws, { 0: { unprotectedHeader, protectedHeader }, length }) => { + if (length !== 1 || unprotectedHeader) { + throw new JWSInvalid('JWS Compact Serialization doesn\'t support multiple recipients or JWS unprotected headers') + } + validateCrit(protectedHeader, unprotectedHeader, protectedHeader ? protectedHeader.crit : undefined) } +const flattenedSerializer = (payload, [recipient]) => { + const { header, signature, protected: prot } = recipient -/***/ }), + return { + payload, + ...prot ? { protected: prot } : undefined, + ...header ? { header } : undefined, + signature + } +} +flattenedSerializer.validate = (jws, { 0: { unprotectedHeader, protectedHeader }, length }) => { + if (length !== 1) { + throw new JWSInvalid('Flattened JWS JSON Serialization doesn\'t support multiple recipients') + } + validateCrit(protectedHeader, unprotectedHeader, protectedHeader ? protectedHeader.crit : undefined) +} -/***/ 74944: -/***/ ((module) => { +const generalSerializer = (payload, recipients) => { + return { + payload, + signatures: recipients.map(({ header, signature, protected: prot }) => { + return { + ...prot ? { protected: prot } : undefined, + ...header ? { header } : undefined, + signature + } + }) + } +} +generalSerializer.validate = (jws, recipients) => { + let validateB64 = false + recipients.forEach(({ protectedHeader, unprotectedHeader }) => { + if (protectedHeader && !validateB64 && 'b64' in protectedHeader) { + validateB64 = true + } + validateCrit(protectedHeader, unprotectedHeader, protectedHeader ? protectedHeader.crit : undefined) + }) -function HARError (errors) { - var message = 'validation failed' + if (validateB64) { + const values = recipients.map(({ protectedHeader }) => protectedHeader && protectedHeader.b64) + if (!values.every((actual, i, [expected]) => actual === expected)) { + throw new JWSInvalid('the "b64" Header Parameter value MUST be the same for all recipients') + } + } +} - this.name = 'HARError' - this.message = message - this.errors = errors +const isJSON = (input) => { + return isObject(input) && (typeof input.payload === 'string' || Buffer.isBuffer(input.payload)) +} - if (typeof Error.captureStackTrace === 'function') { - Error.captureStackTrace(this, this.constructor) - } else { - this.stack = (new Error(message)).stack +const isValidRecipient = (recipient) => { + return isObject(recipient) && typeof recipient.signature === 'string' && + (recipient.header === undefined || isObject(recipient.header)) && + (recipient.protected === undefined || typeof recipient.protected === 'string') +} + +const isMultiRecipient = (input) => { + if (Array.isArray(input.signatures) && input.signatures.every(isValidRecipient)) { + return true } + + return false } -HARError.prototype = Error.prototype +const detect = (input) => { + if (typeof input === 'string' && input.split('.').length === 3) { + return 'compact' + } -module.exports = HARError + if (isJSON(input)) { + if (isMultiRecipient(input)) { + return 'general' + } + + if (isValidRecipient(input)) { + return 'flattened' + } + } + + throw new JWSInvalid('JWS malformed or invalid serialization') +} + +module.exports = { + compact: compactSerializer, + flattened: flattenedSerializer, + general: generalSerializer, + detect +} /***/ }), -/***/ 75697: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 1728: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var Ajv = __nccwpck_require__(64941) -var HARError = __nccwpck_require__(74944) -var schemas = __nccwpck_require__(13679) +const base64url = __nccwpck_require__(73385) +const isDisjoint = __nccwpck_require__(29024) +const isObject = __nccwpck_require__(41805) +const deepClone = __nccwpck_require__(43653) +const { JWSInvalid } = __nccwpck_require__(52973) +const { sign } = __nccwpck_require__(50191) +const getKey = __nccwpck_require__(31308) -var ajv +const serializers = __nccwpck_require__(28104) -function createAjvInstance () { - var ajv = new Ajv({ - allErrors: true - }) - ajv.addMetaSchema(__nccwpck_require__(96273)) - ajv.addSchema(schemas) +const PROCESS_RECIPIENT = Symbol('PROCESS_RECIPIENT') - return ajv -} +class Sign { + constructor (payload) { + if (typeof payload === 'string') { + payload = base64url.encode(payload) + } else if (Buffer.isBuffer(payload)) { + payload = base64url.encodeBuffer(payload) + this._binary = true + } else if (isObject(payload)) { + payload = base64url.JSON.encode(payload) + } else { + throw new TypeError('payload argument must be a Buffer, string or an object') + } -function validate (name, data) { - data = data || {} + this._payload = payload + this._recipients = [] + } - // validator config - ajv = ajv || createAjvInstance() + /* + * @public + */ + recipient (key, protectedHeader, unprotectedHeader) { + key = getKey(key) - var validate = ajv.getSchema(name + '.json') + if (protectedHeader !== undefined && !isObject(protectedHeader)) { + throw new TypeError('protectedHeader argument must be a plain object when provided') + } - return new Promise(function (resolve, reject) { - var valid = validate(data) + if (unprotectedHeader !== undefined && !isObject(unprotectedHeader)) { + throw new TypeError('unprotectedHeader argument must be a plain object when provided') + } - !valid ? reject(new HARError(validate.errors)) : resolve(data) - }) -} + if (!isDisjoint(protectedHeader, unprotectedHeader)) { + throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint') + } -exports.afterRequest = function (data) { - return validate('afterRequest', data) -} + this._recipients.push({ + key, + protectedHeader: protectedHeader ? deepClone(protectedHeader) : undefined, + unprotectedHeader: unprotectedHeader ? deepClone(unprotectedHeader) : undefined + }) -exports.beforeRequest = function (data) { - return validate('beforeRequest', data) -} + return this + } -exports.browser = function (data) { - return validate('browser', data) -} + /* + * @private + */ + [PROCESS_RECIPIENT] (recipient, first) { + const { key, protectedHeader, unprotectedHeader } = recipient -exports.cache = function (data) { - return validate('cache', data) -} + if (key.use === 'enc') { + throw new TypeError('a key with "use":"enc" is not usable for signing') + } -exports.content = function (data) { - return validate('content', data) -} + const joseHeader = { + protected: protectedHeader || {}, + unprotected: unprotectedHeader || {} + } -exports.cookie = function (data) { - return validate('cookie', data) -} + let alg = joseHeader.protected.alg || joseHeader.unprotected.alg -exports.creator = function (data) { - return validate('creator', data) -} + if (!alg) { + alg = key.alg || [...key.algorithms('sign')][0] + if (recipient.protectedHeader) { + joseHeader.protected.alg = recipient.protectedHeader.alg = alg + } else { + joseHeader.protected = recipient.protectedHeader = { alg } + } + } -exports.entry = function (data) { - return validate('entry', data) -} + if (!alg) { + throw new JWSInvalid('could not resolve a usable "alg" for a recipient') + } -exports.har = function (data) { - return validate('har', data) -} + recipient.header = unprotectedHeader + recipient.protected = Object.keys(joseHeader.protected).length ? base64url.JSON.encode(joseHeader.protected) : '' -exports.header = function (data) { - return validate('header', data) -} + if (first && joseHeader.protected.crit && joseHeader.protected.crit.includes('b64') && joseHeader.protected.b64 === false) { + if (this._binary) { + this._payload = base64url.decodeToBuffer(this._payload) + } else { + this._payload = base64url.decode(this._payload) + } + } -exports.log = function (data) { - return validate('log', data) -} + const data = Buffer.concat([ + Buffer.from(recipient.protected || ''), + Buffer.from('.'), + Buffer.from(this._payload) + ]) -exports.page = function (data) { - return validate('page', data) -} + recipient.signature = base64url.encodeBuffer(sign(alg, key, data)) + } -exports.pageTimings = function (data) { - return validate('pageTimings', data) -} + /* + * @public + */ + sign (serialization) { + const serializer = serializers[serialization] + if (!serializer) { + throw new TypeError('serialization must be one of "compact", "flattened", "general"') + } -exports.postData = function (data) { - return validate('postData', data) -} + if (!this._recipients.length) { + throw new JWSInvalid('missing recipients') + } -exports.query = function (data) { - return validate('query', data) -} + serializer.validate(this, this._recipients) -exports.request = function (data) { - return validate('request', data) -} + this._recipients.forEach((recipient, i) => { + this[PROCESS_RECIPIENT](recipient, i === 0) + }) -exports.response = function (data) { - return validate('response', data) + return serializer(this._payload, this._recipients) + } } -exports.timings = function (data) { - return validate('timings', data) -} +module.exports = Sign /***/ }), -/***/ 31621: -/***/ ((module) => { +/***/ 39835: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const { EOL } = __nccwpck_require__(22037) +const base64url = __nccwpck_require__(73385) +const isDisjoint = __nccwpck_require__(29024) +const isObject = __nccwpck_require__(41805) +let validateCrit = __nccwpck_require__(530) +const getKey = __nccwpck_require__(31308) +const { KeyStore } = __nccwpck_require__(42896) +const errors = __nccwpck_require__(52973) +const { check, verify } = __nccwpck_require__(50191) +const JWK = __nccwpck_require__(67894) -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); -}; +const { detect: resolveSerialization } = __nccwpck_require__(28104) +validateCrit = validateCrit.bind(undefined, errors.JWSInvalid) +const SINGLE_RECIPIENT = new Set(['compact', 'flattened', 'preparsed']) -/***/ }), +/* + * @public + */ +const jwsVerify = (skipDisjointCheck, serialization, jws, key, { crit = [], complete = false, algorithms } = {}) => { + key = getKey(key, true) -/***/ 57747: -/***/ ((module) => { + if (algorithms !== undefined && (!Array.isArray(algorithms) || algorithms.some(s => typeof s !== 'string' || !s))) { + throw new TypeError('"algorithms" option must be an array of non-empty strings') + } else if (algorithms) { + algorithms = new Set(algorithms) + } -"use strict"; + if (!Array.isArray(crit) || crit.some(s => typeof s !== 'string' || !s)) { + throw new TypeError('"crit" option must be an array of non-empty strings') + } + if (!serialization) { + serialization = resolveSerialization(jws) + } -/* eslint complexity: [2, 18], max-statements: [2, 33] */ -module.exports = function hasSymbols() { - if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } - if (typeof Symbol.iterator === 'symbol') { return true; } + let prot // protected header + let header // unprotected header + let payload + let signature + let alg - var obj = {}; - var sym = Symbol('test'); - var symObj = Object(sym); - if (typeof sym === 'string') { return false; } + // treat general format with one recipient as flattened + // skips iteration and avoids multi errors in this case + if (serialization === 'general' && jws.signatures.length === 1) { + serialization = 'flattened' + const { signatures, ...root } = jws + jws = { ...root, ...signatures[0] } + } - if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } - if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } + let decoded - // temp disabled per https://github.com/ljharb/object.assign/issues/17 - // if (sym instanceof Symbol) { return false; } - // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 - // if (!(symObj instanceof Symbol)) { return false; } + if (SINGLE_RECIPIENT.has(serialization)) { + let parsedProt = {} - // if (typeof Symbol.prototype.toString !== 'function') { return false; } - // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } + switch (serialization) { + case 'compact': // compact serialization format + ([prot, payload, signature] = jws.split('.')) + break + case 'flattened': // flattened serialization format + ({ protected: prot, payload, signature, header } = jws) + break + case 'preparsed': { // from the JWT module + ({ decoded } = jws); + ([prot, payload, signature] = jws.token.split('.')) + break + } + } - var symVal = 42; - obj[sym] = symVal; - for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop - if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } + if (!header) { + skipDisjointCheck = true + } - if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } + if (decoded) { + parsedProt = decoded.header + } else if (prot) { + try { + parsedProt = base64url.JSON.decode(prot) + } catch (err) { + throw new errors.JWSInvalid('could not parse JWS protected header') + } + } else { + skipDisjointCheck = skipDisjointCheck || true + } - var syms = Object.getOwnPropertySymbols(obj); - if (syms.length !== 1 || syms[0] !== sym) { return false; } + if (!skipDisjointCheck && !isDisjoint(parsedProt, header)) { + throw new errors.JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint') + } - if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } + const combinedHeader = { ...parsedProt, ...header } + validateCrit(parsedProt, header, crit) - if (typeof Object.getOwnPropertyDescriptor === 'function') { - var descriptor = Object.getOwnPropertyDescriptor(obj, sym); - if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } - } + alg = parsedProt.alg || (header && header.alg) + if (!alg) { + throw new errors.JWSInvalid('missing JWS signature algorithm') + } else if (algorithms && !algorithms.has(alg)) { + throw new errors.JOSEAlgNotWhitelisted('alg not whitelisted') + } + + if (key instanceof KeyStore) { + const keystore = key + const keys = keystore.all({ kid: combinedHeader.kid, alg: combinedHeader.alg, key_ops: ['verify'] }) + switch (keys.length) { + case 0: + throw new errors.JWKSNoMatchingKey() + case 1: + // treat the call as if a Key instance was passed in + // skips iteration and avoids multi errors in this case + key = keys[0] + break + default: { + const errs = [] + for (const key of keys) { + try { + return jwsVerify(true, serialization, jws, key, { crit, complete, algorithms: algorithms ? [...algorithms] : undefined }) + } catch (err) { + errs.push(err) + continue + } + } - return true; -}; + const multi = new errors.JOSEMultiError(errs) + if ([...multi].some(e => e instanceof errors.JWSVerificationFailed)) { + throw new errors.JWSVerificationFailed() + } + throw multi + } + } + } + if (key === JWK.EmbeddedJWK) { + if (!isObject(combinedHeader.jwk)) { + throw new errors.JWSInvalid('JWS Header Parameter "jwk" must be a JSON object') + } + key = JWK.asKey(combinedHeader.jwk) + if (key.type !== 'public') { + throw new errors.JWSInvalid('JWS Header Parameter "jwk" must be a public key') + } + } else if (key === JWK.EmbeddedX5C) { + if (!Array.isArray(combinedHeader.x5c) || !combinedHeader.x5c.length || combinedHeader.x5c.some(c => typeof c !== 'string' || !c)) { + throw new errors.JWSInvalid('JWS Header Parameter "x5c" must be a JSON array of certificate value strings') + } + key = JWK.asKey( + `-----BEGIN CERTIFICATE-----${EOL}${(combinedHeader.x5c[0].match(/.{1,64}/g) || []).join(EOL)}${EOL}-----END CERTIFICATE-----`, + { x5c: combinedHeader.x5c } + ) + } -/***/ }), + check(key, 'verify', alg) -/***/ 62157: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + const toBeVerified = Buffer.concat([ + Buffer.from(prot || ''), + Buffer.from('.'), + Buffer.isBuffer(payload) ? payload : Buffer.from(payload) + ]) -"use strict"; + if (!verify(alg, key, toBeVerified, base64url.decodeToBuffer(signature))) { + throw new errors.JWSVerificationFailed() + } + if (combinedHeader.b64 === false) { + payload = Buffer.from(payload) + } else { + payload = base64url.decodeToBuffer(payload) + } -var call = Function.prototype.call; -var $hasOwn = Object.prototype.hasOwnProperty; -var bind = __nccwpck_require__(37138); + if (complete) { + const result = { payload, key } + if (prot) result.protected = parsedProt + if (header) result.header = header + return result + } -/** @type {import('.')} */ -module.exports = bind.call(call, $hasOwn); + return payload + } + // general serialization format + const { signatures, ...root } = jws + const errs = [] + for (const recipient of signatures) { + try { + return jwsVerify(false, 'flattened', { ...root, ...recipient }, key, { crit, complete, algorithms: algorithms ? [...algorithms] : undefined }) + } catch (err) { + errs.push(err) + continue + } + } -/***/ }), + const multi = new errors.JOSEMultiError(errs) + if ([...multi].some(e => e instanceof errors.JWSVerificationFailed)) { + throw new errors.JWSVerificationFailed() + } else if ([...multi].every(e => e instanceof errors.JWKSNoMatchingKey)) { + throw new errors.JWKSNoMatchingKey() + } + throw multi +} -/***/ 29788: -/***/ ((module) => { +module.exports = { + bare: jwsVerify, + verify: jwsVerify.bind(undefined, false, undefined) +} -"use strict"; +/***/ }), -/* eslint no-invalid-this: 1 */ +/***/ 6743: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; -var toStr = Object.prototype.toString; -var max = Math.max; -var funcType = '[object Function]'; +const base64url = __nccwpck_require__(73385) +const errors = __nccwpck_require__(52973) -var concatty = function concatty(a, b) { - var arr = []; +module.exports = (token, { complete = false } = {}) => { + if (typeof token !== 'string' || !token) { + throw new TypeError('JWT must be a string') + } - for (var i = 0; i < a.length; i += 1) { - arr[i] = a[i]; - } - for (var j = 0; j < b.length; j += 1) { - arr[j + a.length] = b[j]; - } + const { 0: header, 1: payload, 2: signature, length } = token.split('.') - return arr; -}; + if (length === 5) { + throw new TypeError('encrypted JWTs cannot be decoded') + } -var slicy = function slicy(arrLike, offset) { - var arr = []; - for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { - arr[j] = arrLike[i]; - } - return arr; -}; + if (length !== 3) { + throw new errors.JWTMalformed('JWTs must have three components') + } -var joiny = function (arr, joiner) { - var str = ''; - for (var i = 0; i < arr.length; i += 1) { - str += arr[i]; - if (i + 1 < arr.length) { - str += joiner; - } + try { + const result = { + header: base64url.JSON.decode(header), + payload: base64url.JSON.decode(payload), + signature } - return str; -}; -module.exports = function bind(that) { - var target = this; - if (typeof target !== 'function' || toStr.apply(target) !== funcType) { - throw new TypeError(ERROR_MESSAGE + target); - } - var args = slicy(arguments, 1); + return complete ? result : result.payload + } catch (err) { + throw new errors.JWTMalformed('JWT is malformed') + } +} - var bound; - var binder = function () { - if (this instanceof bound) { - var result = target.apply( - this, - concatty(args, arguments) - ); - if (Object(result) === result) { - return result; - } - return this; - } - return target.apply( - that, - concatty(args, arguments) - ); - }; +/***/ }), - var boundLength = max(0, target.length - args.length); - var boundArgs = []; - for (var i = 0; i < boundLength; i++) { - boundArgs[i] = '$' + i; - } +/***/ 18138: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); +const decode = __nccwpck_require__(6743) +const sign = __nccwpck_require__(86703) +const verify = __nccwpck_require__(44856) +const profiles = __nccwpck_require__(39547) - if (target.prototype) { - var Empty = function Empty() {}; - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - Empty.prototype = null; - } +module.exports = { + sign, + verify, + ...profiles +} - return bound; -}; +Object.defineProperty(module.exports, "decode", ({ + enumerable: false, + configurable: true, + value: decode +})) /***/ }), -/***/ 37138: +/***/ 39547: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - - -var implementation = __nccwpck_require__(29788); - -module.exports = Function.prototype.bind || implementation; +const { JWTClaimInvalid } = __nccwpck_require__(52973) +const secs = __nccwpck_require__(97305) +const epoch = __nccwpck_require__(47396) +const isObject = __nccwpck_require__(41805) +const verify = __nccwpck_require__(44856) +const { + isString, + isRequired, + isTimestamp, + isStringOrArrayOfStrings +} = __nccwpck_require__(23951) -/***/ }), +const isPayloadRequired = isRequired.bind(undefined, JWTClaimInvalid) +const isPayloadString = isString.bind(undefined, JWTClaimInvalid) +const isOptionString = isString.bind(undefined, TypeError) -/***/ 61002: -/***/ ((module) => { +const defineLazyExportWithWarning = (obj, property, name, definition) => { + Object.defineProperty(obj, property, { + enumerable: true, + configurable: true, + value (...args) { + process.emitWarning( + `The ${name} API implements an IETF draft. Breaking draft implementations are included as minor versions of the jose library, therefore, the ~ semver operator should be used and close attention be payed to library changelog as well as the drafts themselves.`, + 'DraftWarning' + ) + Object.defineProperty(obj, property, { + enumerable: true, + configurable: true, + value: definition + }) + return obj[property](...args) + } + }) +} -"use strict"; +const validateCommonOptions = (options, profile) => { + if (!isObject(options)) { + throw new TypeError('options must be an object') + } -// rfc7231 6.1 -const statusCodeCacheableByDefault = new Set([ - 200, - 203, - 204, - 206, - 300, - 301, - 308, - 404, - 405, - 410, - 414, - 501, -]); + if (!options.issuer) { + throw new TypeError(`"issuer" option is required to validate ${profile}`) + } -// 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, -]); + if (!options.audience) { + throw new TypeError(`"audience" option is required to validate ${profile}`) + } +} -const errorStatusCodes = new Set([ - 500, - 502, - 503, - 504, -]); +module.exports = { + IdToken: { + verify: (token, key, options = {}) => { + validateCommonOptions(options, 'an ID Token') -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, -}; + if ('maxAuthAge' in options) { + isOptionString(options.maxAuthAge, 'options.maxAuthAge') + } + if ('nonce' in options) { + isOptionString(options.nonce, 'options.nonce') + } -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, -}; + const unix = epoch(options.now || new Date()) + const result = verify(token, key, { ...options }) + const payload = options.complete ? result.payload : result -function toNumberOrZero(s) { - const n = parseInt(s, 10); - return isFinite(n) ? n : 0; -} + if (Array.isArray(payload.aud) && payload.aud.length > 1) { + isPayloadRequired(payload.azp, '"azp" claim', 'azp') + } + isPayloadRequired(payload.iat, '"iat" claim', 'iat') + isPayloadRequired(payload.sub, '"sub" claim', 'sub') + isPayloadRequired(payload.exp, '"exp" claim', 'exp') + isTimestamp(payload.auth_time, 'auth_time', !!options.maxAuthAge) + isPayloadString(payload.nonce, '"nonce" claim', 'nonce', !!options.nonce) + isPayloadString(payload.acr, '"acr" claim', 'acr') + isStringOrArrayOfStrings(payload.amr, 'amr') -// RFC 5861 -function isErrorResponse(response) { - // consider undefined response as faulty - if(!response) { - return true - } - return errorStatusCodes.has(response.status); -} + if (options.nonce && payload.nonce !== options.nonce) { + throw new JWTClaimInvalid('unexpected "nonce" claim value', 'nonce', 'check_failed') + } -function parseCacheControl(header) { - const cc = {}; - if (!header) return cc; + const tolerance = options.clockTolerance ? secs(options.clockTolerance) : 0 - // 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, ''); - } + if (options.maxAuthAge) { + const maxAuthAgeSeconds = secs(options.maxAuthAge) + if (payload.auth_time + maxAuthAgeSeconds < unix - tolerance) { + throw new JWTClaimInvalid('"auth_time" claim timestamp check failed (too much time has elapsed since the last End-User authentication)', 'auth_time', 'check_failed') + } + } - return cc; -} + if (Array.isArray(payload.aud) && payload.aud.length > 1 && payload.azp !== options.audience) { + throw new JWTClaimInvalid('unexpected "azp" claim value', 'azp', 'check_failed') + } -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 result } - return parts.join(', '); + }, + LogoutToken: {}, + AccessToken: {} } -module.exports = class CachePolicy { - constructor( - req, - res, - { - shared, - cacheHeuristic, - immutableMinTimeToLive, - ignoreCargoCult, - _fromObject, - } = {} - ) { - if (_fromObject) { - this._fromObject(_fromObject); - return; - } +defineLazyExportWithWarning(module.exports.LogoutToken, 'verify', 'jose.JWT.LogoutToken.verify', (token, key, options = {}) => { + validateCommonOptions(options, 'a Logout Token') - if (!res || !res.headers) { - throw Error('Response headers missing'); - } - this._assertRequestHasHeaders(req); + const result = verify(token, key, { ...options }) + const payload = options.complete ? result.payload : result - 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; + isPayloadRequired(payload.iat, '"iat" claim', 'iat') + isPayloadRequired(payload.jti, '"jti" claim', 'jti') + isPayloadString(payload.sid, '"sid" claim', 'sid') - 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']); + if (!('sid' in payload) && !('sub' in payload)) { + throw new JWTClaimInvalid('either "sid" or "sub" (or both) claims must be present') + } - // 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; - } + if ('nonce' in payload) { + throw new JWTClaimInvalid('"nonce" claim is prohibited', 'nonce', 'prohibited') + } - // 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; - } - } + if (!('events' in payload)) { + throw new JWTClaimInvalid('"events" claim is missing', 'events', 'missing') + } - now() { - return Date.now(); - } + if (!isObject(payload.events)) { + throw new JWTClaimInvalid('"events" claim must be an object', 'events', 'invalid') + } - 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)) - ); - } + if (!('http://schemas.openid.net/event/backchannel-logout' in payload.events)) { + throw new JWTClaimInvalid('"http://schemas.openid.net/event/backchannel-logout" member is missing in the "events" claim', 'events', 'invalid') + } - _hasExplicitExpiration() { - // 4.2.1 Calculating Freshness Lifetime - return ( - (this._isShared && this._rescc['s-maxage']) || - this._rescc['max-age'] || - this._resHeaders.expires - ); - } + if (!isObject(payload.events['http://schemas.openid.net/event/backchannel-logout'])) { + throw new JWTClaimInvalid('"http://schemas.openid.net/event/backchannel-logout" member in the "events" claim must be an object', 'events', 'invalid') + } - _assertRequestHasHeaders(req) { - if (!req || !req.headers) { - throw Error('Request headers missing'); - } - } + return result +}) - satisfiesWithoutRevalidation(req) { - this._assertRequestHasHeaders(req); +defineLazyExportWithWarning(module.exports.AccessToken, 'verify', 'jose.JWT.AccessToken.verify', (token, key, options = {}) => { + validateCommonOptions(options, 'a JWT Access Token') - // 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; - } + isOptionString(options.maxAuthAge, 'options.maxAuthAge') - if (requestCC['max-age'] && this.age() > requestCC['max-age']) { - return false; - } + const unix = epoch(options.now || new Date()) + const typ = 'at+JWT' + const result = verify(token, key, { ...options, typ }) + const payload = options.complete ? result.payload : result - if ( - requestCC['min-fresh'] && - this.timeToLive() < 1000 * requestCC['min-fresh'] - ) { - return false; - } + isPayloadRequired(payload.iat, '"iat" claim', 'iat') + isPayloadRequired(payload.exp, '"exp" claim', 'exp') + isPayloadRequired(payload.sub, '"sub" claim', 'sub') + isPayloadRequired(payload.jti, '"jti" claim', 'jti') + isPayloadString(payload.client_id, '"client_id" claim', 'client_id', true) + isTimestamp(payload.auth_time, 'auth_time', !!options.maxAuthAge) + isPayloadString(payload.acr, '"acr" claim', 'acr') + isStringOrArrayOfStrings(payload.amr, 'amr') - // 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; - } - } + const tolerance = options.clockTolerance ? secs(options.clockTolerance) : 0 - return this._requestMatches(req, false); + if (options.maxAuthAge) { + const maxAuthAgeSeconds = secs(options.maxAuthAge) + if (payload.auth_time + maxAuthAgeSeconds < unix - tolerance) { + throw new JWTClaimInvalid('"auth_time" claim timestamp check failed (too much time has elapsed since the last End-User authentication)', 'auth_time', 'check_failed') } + } - _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 result +}) - _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'] - ); - } - _varyMatches(req) { - if (!this._resHeaders.vary) { - return true; - } +/***/ }), - // A Vary header field-value of "*" always fails to match - if (this._resHeaders.vary === '*') { - return false; - } +/***/ 23951: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - 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; - } +const { JWTClaimInvalid } = __nccwpck_require__(52973) - _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; - } +const isNotString = val => typeof val !== 'string' || val.length === 0 +const isNotArrayOfStrings = val => !Array.isArray(val) || val.length === 0 || val.some(isNotString) +const isRequired = (Err, value, label, claim) => { + if (value === undefined) { + throw new Err(`${label} is missing`, claim, 'missing') + } +} +const isString = (Err, value, label, claim, required = false) => { + if (required) { + isRequired(Err, value, label, claim) + } - responseHeaders() { - const headers = this._copyWithoutHopByHopHeaders(this._resHeaders); - const age = this.age(); + if (value !== undefined && isNotString(value)) { + throw new Err(`${label} must be a string`, claim, 'invalid') + } +} +const isTimestamp = (value, label, required = false) => { + if (required && value === undefined) { + throw new JWTClaimInvalid(`"${label}" claim is missing`, label, 'missing') + } - // 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; - } + if (value !== undefined && (typeof value !== 'number')) { + throw new JWTClaimInvalid(`"${label}" claim must be a JSON numeric value`, label, 'invalid') + } +} +const isStringOrArrayOfStrings = (value, label, required = false) => { + if (required && value === undefined) { + throw new JWTClaimInvalid(`"${label}" claim is missing`, label, 'missing') + } - /** - * 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; - } + if (value !== undefined && (isNotString(value) && isNotArrayOfStrings(value))) { + throw new JWTClaimInvalid(`"${label}" claim must be a string or array of strings`, label, 'invalid') + } +} - /** - * Value of the Age header, in seconds, updated for the current time. - * May be fractional. - * - * @return Number - */ - age() { - let age = this._ageValue(); +module.exports = { + isNotArrayOfStrings, + isRequired, + isNotString, + isString, + isTimestamp, + isStringOrArrayOfStrings +} - const residentTime = (this.now() - this._responseTime) / 1000; - return age + residentTime; - } - _ageValue() { - return toNumberOrZero(this._resHeaders.age); - } +/***/ }), - /** - * 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; - } +/***/ 86703: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 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; - } +const isObject = __nccwpck_require__(41805) +const secs = __nccwpck_require__(97305) +const epoch = __nccwpck_require__(47396) +const getKey = __nccwpck_require__(31308) +const JWS = __nccwpck_require__(36518) - if (this._resHeaders.vary === '*') { - return 0; - } +const isString = (__nccwpck_require__(23951).isString.bind)(undefined, TypeError) - 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']); - } - } +const validateOptions = (options) => { + if (typeof options.iat !== 'boolean') { + throw new TypeError('options.iat must be a boolean') + } - // 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']); - } + if (typeof options.kid !== 'boolean') { + throw new TypeError('options.kid must be a boolean') + } - const defaultMinTtl = this._rescc.immutable ? this._immutableMinTtl : 0; + isString(options.subject, 'options.subject') + isString(options.issuer, 'options.issuer') - 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); - } + if ( + options.audience !== undefined && + ( + (typeof options.audience !== 'string' || !options.audience) && + (!Array.isArray(options.audience) || options.audience.length === 0 || options.audience.some(a => !a || typeof a !== 'string')) + ) + ) { + throw new TypeError('options.audience must be a string or an array of strings') + } - 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 - ); - } - } + if (!isObject(options.header)) { + throw new TypeError('options.header must be an object') + } - return defaultMinTtl; - } + isString(options.algorithm, 'options.algorithm') + isString(options.expiresIn, 'options.expiresIn') + isString(options.notBefore, 'options.notBefore') + isString(options.jti, 'options.jti') - 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; - } + if (options.now !== undefined && (!(options.now instanceof Date) || !options.now.getTime())) { + throw new TypeError('options.now must be a valid Date object') + } +} - stale() { - return this.maxAge() <= this.age(); - } +module.exports = (payload, key, options = {}) => { + if (!isObject(options)) { + throw new TypeError('options must be an object') + } - _useStaleIfError() { - return this.maxAge() + toNumberOrZero(this._rescc['stale-if-error']) > this.age(); - } + const { + algorithm, audience, expiresIn, header = {}, iat = true, + issuer, jti, kid = true, notBefore, subject, now + } = options - useStaleWhileRevalidate() { - return this.maxAge() + toNumberOrZero(this._rescc['stale-while-revalidate']) > this.age(); - } + validateOptions({ + algorithm, audience, expiresIn, header, iat, issuer, jti, kid, notBefore, now, subject + }) - static fromObject(obj) { - return new this(undefined, undefined, { _fromObject: obj }); - } + if (!isObject(payload)) { + throw new TypeError('payload must be an object') + } - _fromObject(obj) { - if (this._responseTime) throw Error('Reinitialized'); - if (!obj || obj.v !== 1) throw Error('Invalid serialization'); + let unix + if (expiresIn || notBefore || iat) { + unix = epoch(now || new Date()) + } - 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; - } + payload = { + ...payload, + sub: subject || payload.sub, + aud: audience || payload.aud, + iss: issuer || payload.iss, + jti: jti || payload.jti, + iat: iat ? unix : payload.iat, + exp: expiresIn ? unix + secs(expiresIn) : payload.exp, + nbf: notBefore ? unix + secs(notBefore) : payload.nbf + } - 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, - }; - } + key = getKey(key) - /** - * 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); + let includeKid - // This implementation does not understand range requests - delete headers['if-range']; + if (typeof options.kid === 'boolean') { + includeKid = kid + } else { + includeKid = !key.secret + } - 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 JWS.sign(JSON.stringify(payload), key, { + ...header, + alg: algorithm || header.alg, + kid: includeKid ? key.kid : header.kid + }) +} - /* 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']; +/***/ 44856: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - 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']; - } +const isObject = __nccwpck_require__(41805) +const epoch = __nccwpck_require__(47396) +const secs = __nccwpck_require__(97305) +const getKey = __nccwpck_require__(31308) +const { bare: verify } = __nccwpck_require__(39835) +const { JWTClaimInvalid, JWTExpired } = __nccwpck_require__(52973) - return headers; - } +const { + isString, + isNotString, + isNotArrayOfStrings, + isTimestamp, + isStringOrArrayOfStrings +} = __nccwpck_require__(23951) +const decode = __nccwpck_require__(6743) - /** - * 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'); - } +const isPayloadString = isString.bind(undefined, JWTClaimInvalid) +const isOptionString = isString.bind(undefined, TypeError) - // 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; - } - } +const normalizeTyp = (value) => value.toLowerCase().replace(/^application\//, '') + +const validateOptions = ({ + algorithms, audience, clockTolerance, complete = false, crit, ignoreExp = false, + ignoreIat = false, ignoreNbf = false, issuer, jti, maxTokenAge, now = new Date(), + subject, typ +}) => { + if (typeof complete !== 'boolean') { + throw new TypeError('options.complete must be a boolean') + } - 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, - }; - } + if (typeof ignoreExp !== 'boolean') { + throw new TypeError('options.ignoreExp must be a boolean') + } - // 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]; - } + if (typeof ignoreNbf !== 'boolean') { + throw new TypeError('options.ignoreNbf must be a boolean') + } - 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, - }; - } -}; + if (typeof ignoreIat !== 'boolean') { + throw new TypeError('options.ignoreIat must be a boolean') + } + isOptionString(maxTokenAge, 'options.maxTokenAge') + isOptionString(subject, 'options.subject') + isOptionString(jti, 'options.jti') + isOptionString(clockTolerance, 'options.clockTolerance') + isOptionString(typ, 'options.typ') -/***/ }), + if (issuer !== undefined && (isNotString(issuer) && isNotArrayOfStrings(issuer))) { + throw new TypeError('options.issuer must be a string or an array of strings') + } -/***/ 42479: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (audience !== undefined && (isNotString(audience) && isNotArrayOfStrings(audience))) { + throw new TypeError('options.audience must be a string or an array of strings') + } -// Copyright 2015 Joyent, Inc. + if (algorithms !== undefined && isNotArrayOfStrings(algorithms)) { + throw new TypeError('options.algorithms must be an array of strings') + } -var parser = __nccwpck_require__(95086); -var signer = __nccwpck_require__(38143); -var verify = __nccwpck_require__(51227); -var utils = __nccwpck_require__(65689); + if (!(now instanceof Date) || !now.getTime()) { + throw new TypeError('options.now must be a valid Date object') + } + if (ignoreIat && maxTokenAge !== undefined) { + throw new TypeError('options.ignoreIat and options.maxTokenAge cannot used together') + } + if (crit !== undefined && isNotArrayOfStrings(crit)) { + throw new TypeError('options.crit must be an array of strings') + } -///--- API + return { + algorithms, + audience, + clockTolerance, + complete, + crit, + ignoreExp, + ignoreIat, + ignoreNbf, + issuer, + jti, + maxTokenAge, + now, + subject, + typ + } +} -module.exports = { +const validateTypes = ({ header, payload }, options) => { + isPayloadString(header.alg, '"alg" header parameter', 'alg', true) - parse: parser.parseRequest, - parseRequest: parser.parseRequest, + isTimestamp(payload.iat, 'iat', !!options.maxTokenAge) + isTimestamp(payload.exp, 'exp') + isTimestamp(payload.nbf, 'nbf') + isPayloadString(payload.jti, '"jti" claim', 'jti', !!options.jti) + isStringOrArrayOfStrings(payload.iss, 'iss', !!options.issuer) + isPayloadString(payload.sub, '"sub" claim', 'sub', !!options.subject) + isStringOrArrayOfStrings(payload.aud, 'aud', !!options.audience) + isPayloadString(header.typ, '"typ" header parameter', 'typ', !!options.typ) +} - sign: signer.signRequest, - signRequest: signer.signRequest, - createSigner: signer.createSigner, - isSigner: signer.isSigner, +const checkAudiencePresence = (audPayload, audOption) => { + if (typeof audPayload === 'string') { + return audOption.includes(audPayload) + } - sshKeyToPEM: utils.sshKeyToPEM, - sshKeyFingerprint: utils.fingerprint, - pemToRsaSSHKey: utils.pemToRsaSSHKey, + // Each principal intended to process the JWT MUST + // identify itself with a value in the audience claim + audPayload = new Set(audPayload) + return audOption.some(Set.prototype.has.bind(audPayload)) +} - verify: verify.verifySignature, - verifySignature: verify.verifySignature, - verifyHMAC: verify.verifyHMAC -}; +module.exports = (token, key, options = {}) => { + if (!isObject(options)) { + throw new TypeError('options must be an object') + } + const { + algorithms, audience, clockTolerance, complete, crit, ignoreExp, ignoreIat, ignoreNbf, issuer, + jti, maxTokenAge, now, subject, typ + } = options = validateOptions(options) -/***/ }), + const decoded = decode(token, { complete: true }) + key = getKey(key, true) -/***/ 95086: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (complete) { + ({ key } = verify(true, 'preparsed', { decoded, token }, key, { crit, algorithms, complete: true })) + decoded.key = key + } else { + verify(true, 'preparsed', { decoded, token }, key, { crit, algorithms }) + } -// Copyright 2012 Joyent, Inc. All rights reserved. + const unix = epoch(now) + validateTypes(decoded, options) -var assert = __nccwpck_require__(66631); -var util = __nccwpck_require__(73837); -var utils = __nccwpck_require__(65689); + if (issuer && (typeof decoded.payload.iss !== 'string' || !(typeof issuer === 'string' ? [issuer] : issuer).includes(decoded.payload.iss))) { + throw new JWTClaimInvalid('unexpected "iss" claim value', 'iss', 'check_failed') + } + + if (subject && decoded.payload.sub !== subject) { + throw new JWTClaimInvalid('unexpected "sub" claim value', 'sub', 'check_failed') + } + if (jti && decoded.payload.jti !== jti) { + throw new JWTClaimInvalid('unexpected "jti" claim value', 'jti', 'check_failed') + } + if (audience && !checkAudiencePresence(decoded.payload.aud, typeof audience === 'string' ? [audience] : audience)) { + throw new JWTClaimInvalid('unexpected "aud" claim value', 'aud', 'check_failed') + } -///--- Globals + if (typ && normalizeTyp(decoded.header.typ) !== normalizeTyp(typ)) { + throw new JWTClaimInvalid('unexpected "typ" JWT header value', 'typ', 'check_failed') + } -var HASH_ALGOS = utils.HASH_ALGOS; -var PK_ALGOS = utils.PK_ALGOS; -var HttpSignatureError = utils.HttpSignatureError; -var InvalidAlgorithmError = utils.InvalidAlgorithmError; -var validateAlgorithm = utils.validateAlgorithm; + const tolerance = clockTolerance ? secs(clockTolerance) : 0 -var State = { - New: 0, - Params: 1 -}; + if (!ignoreIat && !('exp' in decoded.payload) && 'iat' in decoded.payload && decoded.payload.iat > unix + tolerance) { + throw new JWTClaimInvalid('"iat" claim timestamp check failed (it should be in the past)', 'iat', 'check_failed') + } -var ParamsState = { - Name: 0, - Quote: 1, - Value: 2, - Comma: 3 -}; + if (!ignoreNbf && 'nbf' in decoded.payload && decoded.payload.nbf > unix + tolerance) { + throw new JWTClaimInvalid('"nbf" claim timestamp check failed', 'nbf', 'check_failed') + } + if (!ignoreExp && 'exp' in decoded.payload && decoded.payload.exp <= unix - tolerance) { + throw new JWTExpired('"exp" claim timestamp check failed', 'exp', 'check_failed') + } -///--- Specific Errors + if (maxTokenAge) { + const age = unix - decoded.payload.iat + const max = secs(maxTokenAge) + if (age - tolerance > max) { + throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', 'iat', 'check_failed') + } -function ExpiredRequestError(message) { - HttpSignatureError.call(this, message, ExpiredRequestError); + if (age < 0 - tolerance) { + throw new JWTClaimInvalid('"iat" claim timestamp check failed (it should be in the past)', 'iat', 'check_failed') + } + } + + return complete ? decoded : decoded.payload } -util.inherits(ExpiredRequestError, HttpSignatureError); -function InvalidHeaderError(message) { - HttpSignatureError.call(this, message, InvalidHeaderError); -} -util.inherits(InvalidHeaderError, HttpSignatureError); +/***/ }), + +/***/ 30760: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const { getCurves } = __nccwpck_require__(6113) -function InvalidParamsError(message) { - HttpSignatureError.call(this, message, InvalidParamsError); +const curves = new Set() + +if (getCurves().includes('prime256v1')) { + curves.add('P-256') } -util.inherits(InvalidParamsError, HttpSignatureError); +if (getCurves().includes('secp256k1')) { + curves.add('secp256k1') +} -function MissingHeaderError(message) { - HttpSignatureError.call(this, message, MissingHeaderError); +if (getCurves().includes('secp384r1')) { + curves.add('P-384') } -util.inherits(MissingHeaderError, HttpSignatureError); -function StrictParsingError(message) { - HttpSignatureError.call(this, message, StrictParsingError); +if (getCurves().includes('secp521r1')) { + curves.add('P-521') } -util.inherits(StrictParsingError, HttpSignatureError); -///--- Exported API +module.exports = curves + + +/***/ }), + +/***/ 87168: +/***/ ((module) => { + +module.exports = new Map() + + +/***/ }), + +/***/ 15501: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const EC_CURVES = __nccwpck_require__(30760) +const IVLENGTHS = __nccwpck_require__(19805) +const JWA = __nccwpck_require__(72430) +const JWK = __nccwpck_require__(95942) +const KEYLENGTHS = __nccwpck_require__(54358) +const OKP_CURVES = __nccwpck_require__(24720) +const ECDH_DERIVE_LENGTHS = __nccwpck_require__(87168) module.exports = { + EC_CURVES, + ECDH_DERIVE_LENGTHS, + IVLENGTHS, + JWA, + JWK, + KEYLENGTHS, + OKP_CURVES +} - /** - * Parses the 'Authorization' header out of an http.ServerRequest object. - * - * Note that this API will fully validate the Authorization header, and throw - * on any error. It will not however check the signature, or the keyId format - * as those are specific to your environment. You can use the options object - * to pass in extra constraints. - * - * As a response object you can expect this: - * - * { - * "scheme": "Signature", - * "params": { - * "keyId": "foo", - * "algorithm": "rsa-sha256", - * "headers": [ - * "date" or "x-date", - * "digest" - * ], - * "signature": "base64" - * }, - * "signingString": "ready to be passed to crypto.verify()" - * } - * - * @param {Object} request an http.ServerRequest. - * @param {Object} options an optional options object with: - * - clockSkew: allowed clock skew in seconds (default 300). - * - headers: required header names (def: date or x-date) - * - algorithms: algorithms to support (default: all). - * - strict: should enforce latest spec parsing - * (default: false). - * @return {Object} parsed out object (see above). - * @throws {TypeError} on invalid input. - * @throws {InvalidHeaderError} on an invalid Authorization header error. - * @throws {InvalidParamsError} if the params in the scheme are invalid. - * @throws {MissingHeaderError} if the params indicate a header not present, - * either in the request headers from the params, - * or not in the params from a required header - * in options. - * @throws {StrictParsingError} if old attributes are used in strict parsing - * mode. - * @throws {ExpiredRequestError} if the value of date or x-date exceeds skew. - */ - parseRequest: function parseRequest(request, options) { - assert.object(request, 'request'); - assert.object(request.headers, 'request.headers'); - if (options === undefined) { - options = {}; - } - if (options.headers === undefined) { - options.headers = [request.headers['x-date'] ? 'x-date' : 'date']; - } - assert.object(options, 'options'); - assert.arrayOfString(options.headers, 'options.headers'); - assert.optionalFinite(options.clockSkew, 'options.clockSkew'); - var authzHeaderName = options.authorizationHeaderName || 'authorization'; +/***/ }), - if (!request.headers[authzHeaderName]) { - throw new MissingHeaderError('no ' + authzHeaderName + ' header ' + - 'present in the request'); - } +/***/ 19805: +/***/ ((module) => { - options.clockSkew = options.clockSkew || 300; +module.exports = new Map([ + ['A128CBC-HS256', 128], + ['A128GCM', 96], + ['A128GCMKW', 96], + ['A192CBC-HS384', 128], + ['A192GCM', 96], + ['A192GCMKW', 96], + ['A256CBC-HS512', 128], + ['A256GCM', 96], + ['A256GCMKW', 96] +]) - var i = 0; - var state = State.New; - var substate = ParamsState.Name; - var tmpName = ''; - var tmpValue = ''; +/***/ }), - var parsed = { - scheme: '', - params: {}, - signingString: '' - }; +/***/ 72430: +/***/ ((module) => { - var authz = request.headers[authzHeaderName]; - for (i = 0; i < authz.length; i++) { - var c = authz.charAt(i); +module.exports = { + sign: new Map(), + verify: new Map(), + keyManagementEncrypt: new Map(), + keyManagementDecrypt: new Map(), + encrypt: new Map(), + decrypt: new Map() +} - switch (Number(state)) { - case State.New: - if (c !== ' ') parsed.scheme += c; - else state = State.Params; - break; +/***/ }), - case State.Params: - switch (Number(substate)) { +/***/ 95942: +/***/ ((module) => { - case ParamsState.Name: - var code = c.charCodeAt(0); - // restricted name of A-Z / a-z - if ((code >= 0x41 && code <= 0x5a) || // A-Z - (code >= 0x61 && code <= 0x7a)) { // a-z - tmpName += c; - } else if (c === '=') { - if (tmpName.length === 0) - throw new InvalidHeaderError('bad param format'); - substate = ParamsState.Quote; - } else { - throw new InvalidHeaderError('bad param format'); - } - break; +module.exports = { + oct: { + decrypt: {}, + deriveKey: {}, + encrypt: {}, + sign: {}, + unwrapKey: {}, + verify: {}, + wrapKey: {} + }, + EC: { + decrypt: {}, + deriveKey: {}, + encrypt: {}, + sign: {}, + unwrapKey: {}, + verify: {}, + wrapKey: {} + }, + RSA: { + decrypt: {}, + deriveKey: {}, + encrypt: {}, + sign: {}, + unwrapKey: {}, + verify: {}, + wrapKey: {} + }, + OKP: { + decrypt: {}, + deriveKey: {}, + encrypt: {}, + sign: {}, + unwrapKey: {}, + verify: {}, + wrapKey: {} + } +} - case ParamsState.Quote: - if (c === '"') { - tmpValue = ''; - substate = ParamsState.Value; - } else { - throw new InvalidHeaderError('bad param format'); - } - break; - case ParamsState.Value: - if (c === '"') { - parsed.params[tmpName] = tmpValue; - substate = ParamsState.Comma; - } else { - tmpValue += c; - } - break; +/***/ }), - case ParamsState.Comma: - if (c === ',') { - tmpName = ''; - substate = ParamsState.Name; - } else { - throw new InvalidHeaderError('bad param format'); - } - break; +/***/ 54358: +/***/ ((module) => { - default: - throw new Error('Invalid substate'); - } - break; +module.exports = new Map([ + ['A128CBC-HS256', 256], + ['A128GCM', 128], + ['A192CBC-HS384', 384], + ['A192GCM', 192], + ['A256CBC-HS512', 512], + ['A256GCM', 256] +]) - default: - throw new Error('Invalid substate'); - } - } +/***/ }), - if (!parsed.params.headers || parsed.params.headers === '') { - if (request.headers['x-date']) { - parsed.params.headers = ['x-date']; - } else { - parsed.params.headers = ['date']; - } - } else { - parsed.params.headers = parsed.params.headers.split(' '); - } +/***/ 24720: +/***/ ((module) => { - // Minimally validate the parsed object - if (!parsed.scheme || parsed.scheme !== 'Signature') - throw new InvalidHeaderError('scheme was not "Signature"'); +const curves = new Set(['Ed25519']) - if (!parsed.params.keyId) - throw new InvalidHeaderError('keyId was not specified'); +if (!('electron' in process.versions)) { + curves.add('Ed448') + curves.add('X25519') + curves.add('X448') +} - if (!parsed.params.algorithm) - throw new InvalidHeaderError('algorithm was not specified'); +module.exports = curves - if (!parsed.params.signature) - throw new InvalidHeaderError('signature was not specified'); - // Check the algorithm against the official list - parsed.params.algorithm = parsed.params.algorithm.toLowerCase(); - try { - validateAlgorithm(parsed.params.algorithm); - } catch (e) { - if (e instanceof InvalidAlgorithmError) - throw (new InvalidParamsError(parsed.params.algorithm + ' is not ' + - 'supported')); - else - throw (e); - } +/***/ }), - // Build the signingString - for (i = 0; i < parsed.params.headers.length; i++) { - var h = parsed.params.headers[i].toLowerCase(); - parsed.params.headers[i] = h; +/***/ 21917: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (h === 'request-line') { - if (!options.strict) { - /* - * We allow headers from the older spec drafts if strict parsing isn't - * specified in options. - */ - parsed.signingString += - request.method + ' ' + request.url + ' HTTP/' + request.httpVersion; - } else { - /* Strict parsing doesn't allow older draft headers. */ - throw (new StrictParsingError('request-line is not a valid header ' + - 'with strict parsing enabled.')); - } - } else if (h === '(request-target)') { - parsed.signingString += - '(request-target): ' + request.method.toLowerCase() + ' ' + - request.url; - } else { - var value = request.headers[h]; - if (value === undefined) - throw new MissingHeaderError(h + ' was not in the request'); - parsed.signingString += h + ': ' + value; - } +"use strict"; - if ((i + 1) < parsed.params.headers.length) - parsed.signingString += '\n'; - } - // Check against the constraints - var date; - if (request.headers.date || request.headers['x-date']) { - if (request.headers['x-date']) { - date = new Date(request.headers['x-date']); - } else { - date = new Date(request.headers.date); - } - var now = new Date(); - var skew = Math.abs(now.getTime() - date.getTime()); - if (skew > options.clockSkew * 1000) { - throw new ExpiredRequestError('clock skew of ' + - (skew / 1000) + - 's was greater than ' + - options.clockSkew + 's'); - } - } +var loader = __nccwpck_require__(51161); +var dumper = __nccwpck_require__(68866); - options.headers.forEach(function (hdr) { - // Remember that we already checked any headers in the params - // were in the request, so if this passes we're good. - if (parsed.params.headers.indexOf(hdr.toLowerCase()) < 0) - throw new MissingHeaderError(hdr + ' was not a signed header'); - }); - if (options.algorithms) { - if (options.algorithms.indexOf(parsed.params.algorithm) === -1) - throw new InvalidParamsError(parsed.params.algorithm + - ' is not a supported algorithm'); - } +function renamed(from, to) { + return function () { + throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' + + 'Use yaml.' + to + ' instead, which is now safe by default.'); + }; +} - parsed.algorithm = parsed.params.algorithm.toUpperCase(); - parsed.keyId = parsed.params.keyId; - return parsed; - } +module.exports.Type = __nccwpck_require__(6073); +module.exports.Schema = __nccwpck_require__(21082); +module.exports.FAILSAFE_SCHEMA = __nccwpck_require__(28562); +module.exports.JSON_SCHEMA = __nccwpck_require__(1035); +module.exports.CORE_SCHEMA = __nccwpck_require__(12011); +module.exports.DEFAULT_SCHEMA = __nccwpck_require__(18759); +module.exports.load = loader.load; +module.exports.loadAll = loader.loadAll; +module.exports.dump = dumper.dump; +module.exports.YAMLException = __nccwpck_require__(68179); + +// Re-export all types in case user wants to create custom schema +module.exports.types = { + binary: __nccwpck_require__(77900), + float: __nccwpck_require__(42705), + map: __nccwpck_require__(86150), + null: __nccwpck_require__(20721), + pairs: __nccwpck_require__(96860), + set: __nccwpck_require__(79548), + timestamp: __nccwpck_require__(99212), + bool: __nccwpck_require__(64993), + int: __nccwpck_require__(11615), + merge: __nccwpck_require__(86104), + omap: __nccwpck_require__(19046), + seq: __nccwpck_require__(67283), + str: __nccwpck_require__(23619) }; +// Removed functions from JS-YAML 3.0.x +module.exports.safeLoad = renamed('safeLoad', 'load'); +module.exports.safeLoadAll = renamed('safeLoadAll', 'loadAll'); +module.exports.safeDump = renamed('safeDump', 'dump'); + /***/ }), -/***/ 38143: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 26829: +/***/ ((module) => { -// Copyright 2012 Joyent, Inc. All rights reserved. +"use strict"; -var assert = __nccwpck_require__(66631); -var crypto = __nccwpck_require__(6113); -var http = __nccwpck_require__(13685); -var util = __nccwpck_require__(73837); -var sshpk = __nccwpck_require__(87022); -var jsprim = __nccwpck_require__(6287); -var utils = __nccwpck_require__(65689); -var sprintf = (__nccwpck_require__(73837).format); -var HASH_ALGOS = utils.HASH_ALGOS; -var PK_ALGOS = utils.PK_ALGOS; -var InvalidAlgorithmError = utils.InvalidAlgorithmError; -var HttpSignatureError = utils.HttpSignatureError; -var validateAlgorithm = utils.validateAlgorithm; +function isNothing(subject) { + return (typeof subject === 'undefined') || (subject === null); +} -///--- Globals -var AUTHZ_FMT = - 'Signature keyId="%s",algorithm="%s",headers="%s",signature="%s"'; +function isObject(subject) { + return (typeof subject === 'object') && (subject !== null); +} -///--- Specific Errors -function MissingHeaderError(message) { - HttpSignatureError.call(this, message, MissingHeaderError); -} -util.inherits(MissingHeaderError, HttpSignatureError); +function toArray(sequence) { + if (Array.isArray(sequence)) return sequence; + else if (isNothing(sequence)) return []; -function StrictParsingError(message) { - HttpSignatureError.call(this, message, StrictParsingError); + return [ sequence ]; } -util.inherits(StrictParsingError, HttpSignatureError); -/* See createSigner() */ -function RequestSigner(options) { - assert.object(options, 'options'); - var alg = []; - if (options.algorithm !== undefined) { - assert.string(options.algorithm, 'options.algorithm'); - alg = validateAlgorithm(options.algorithm); - } - this.rs_alg = alg; +function extend(target, source) { + var index, length, key, sourceKeys; - /* - * RequestSigners come in two varieties: ones with an rs_signFunc, and ones - * with an rs_signer. - * - * rs_signFunc-based RequestSigners have to build up their entire signing - * string within the rs_lines array and give it to rs_signFunc as a single - * concat'd blob. rs_signer-based RequestSigners can add a line at a time to - * their signing state by using rs_signer.update(), thus only needing to - * buffer the hash function state and one line at a time. - */ - if (options.sign !== undefined) { - assert.func(options.sign, 'options.sign'); - this.rs_signFunc = options.sign; + if (source) { + sourceKeys = Object.keys(source); - } else if (alg[0] === 'hmac' && options.key !== undefined) { - assert.string(options.keyId, 'options.keyId'); - this.rs_keyId = options.keyId; + for (index = 0, length = sourceKeys.length; index < length; index += 1) { + key = sourceKeys[index]; + target[key] = source[key]; + } + } - if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key)) - throw (new TypeError('options.key for HMAC must be a string or Buffer')); + return target; +} - /* - * Make an rs_signer for HMACs, not a rs_signFunc -- HMACs digest their - * data in chunks rather than requiring it all to be given in one go - * at the end, so they are more similar to signers than signFuncs. - */ - this.rs_signer = crypto.createHmac(alg[1].toUpperCase(), options.key); - this.rs_signer.sign = function () { - var digest = this.digest('base64'); - return ({ - hashAlgorithm: alg[1], - toString: function () { return (digest); } - }); - }; - } else if (options.key !== undefined) { - var key = options.key; - if (typeof (key) === 'string' || Buffer.isBuffer(key)) - key = sshpk.parsePrivateKey(key); +function repeat(string, count) { + var result = '', cycle; - assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]), - 'options.key must be a sshpk.PrivateKey'); - this.rs_key = key; + for (cycle = 0; cycle < count; cycle += 1) { + result += string; + } - assert.string(options.keyId, 'options.keyId'); - this.rs_keyId = options.keyId; + return result; +} - if (!PK_ALGOS[key.type]) { - throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' + - 'keys are not supported')); - } - if (alg[0] !== undefined && key.type !== alg[0]) { - throw (new InvalidAlgorithmError('options.key must be a ' + - alg[0].toUpperCase() + ' key, was given a ' + - key.type.toUpperCase() + ' key instead')); - } +function isNegativeZero(number) { + return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); +} - this.rs_signer = key.createSign(alg[1]); - } else { - throw (new TypeError('options.sign (func) or options.key is required')); - } +module.exports.isNothing = isNothing; +module.exports.isObject = isObject; +module.exports.toArray = toArray; +module.exports.repeat = repeat; +module.exports.isNegativeZero = isNegativeZero; +module.exports.extend = extend; - this.rs_headers = []; - this.rs_lines = []; -} -/** - * Adds a header to be signed, with its value, into this signer. - * - * @param {String} header - * @param {String} value - * @return {String} value written - */ -RequestSigner.prototype.writeHeader = function (header, value) { - assert.string(header, 'header'); - header = header.toLowerCase(); - assert.string(value, 'value'); +/***/ }), - this.rs_headers.push(header); +/***/ 68866: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (this.rs_signFunc) { - this.rs_lines.push(header + ': ' + value); +"use strict"; - } else { - var line = header + ': ' + value; - if (this.rs_headers.length > 0) - line = '\n' + line; - this.rs_signer.update(line); - } - return (value); -}; +/*eslint-disable no-use-before-define*/ -/** - * Adds a default Date header, returning its value. - * - * @return {String} - */ -RequestSigner.prototype.writeDateHeader = function () { - return (this.writeHeader('date', jsprim.rfc1123(new Date()))); -}; +var common = __nccwpck_require__(26829); +var YAMLException = __nccwpck_require__(68179); +var DEFAULT_SCHEMA = __nccwpck_require__(18759); -/** - * Adds the request target line to be signed. - * - * @param {String} method, HTTP method (e.g. 'get', 'post', 'put') - * @param {String} path - */ -RequestSigner.prototype.writeTarget = function (method, path) { - assert.string(method, 'method'); - assert.string(path, 'path'); - method = method.toLowerCase(); - this.writeHeader('(request-target)', method + ' ' + path); -}; +var _toString = Object.prototype.toString; +var _hasOwnProperty = Object.prototype.hasOwnProperty; -/** - * Calculate the value for the Authorization header on this request - * asynchronously. - * - * @param {Func} callback (err, authz) - */ -RequestSigner.prototype.sign = function (cb) { - assert.func(cb, 'callback'); +var CHAR_BOM = 0xFEFF; +var CHAR_TAB = 0x09; /* Tab */ +var CHAR_LINE_FEED = 0x0A; /* LF */ +var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */ +var CHAR_SPACE = 0x20; /* Space */ +var CHAR_EXCLAMATION = 0x21; /* ! */ +var CHAR_DOUBLE_QUOTE = 0x22; /* " */ +var CHAR_SHARP = 0x23; /* # */ +var CHAR_PERCENT = 0x25; /* % */ +var CHAR_AMPERSAND = 0x26; /* & */ +var CHAR_SINGLE_QUOTE = 0x27; /* ' */ +var CHAR_ASTERISK = 0x2A; /* * */ +var CHAR_COMMA = 0x2C; /* , */ +var CHAR_MINUS = 0x2D; /* - */ +var CHAR_COLON = 0x3A; /* : */ +var CHAR_EQUALS = 0x3D; /* = */ +var CHAR_GREATER_THAN = 0x3E; /* > */ +var CHAR_QUESTION = 0x3F; /* ? */ +var CHAR_COMMERCIAL_AT = 0x40; /* @ */ +var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ +var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ +var CHAR_GRAVE_ACCENT = 0x60; /* ` */ +var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ +var CHAR_VERTICAL_LINE = 0x7C; /* | */ +var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ - if (this.rs_headers.length < 1) - throw (new Error('At least one header must be signed')); +var ESCAPE_SEQUENCES = {}; - var alg, authz; - if (this.rs_signFunc) { - var data = this.rs_lines.join('\n'); - var self = this; - this.rs_signFunc(data, function (err, sig) { - if (err) { - cb(err); - return; - } - try { - assert.object(sig, 'signature'); - assert.string(sig.keyId, 'signature.keyId'); - assert.string(sig.algorithm, 'signature.algorithm'); - assert.string(sig.signature, 'signature.signature'); - alg = validateAlgorithm(sig.algorithm); +ESCAPE_SEQUENCES[0x00] = '\\0'; +ESCAPE_SEQUENCES[0x07] = '\\a'; +ESCAPE_SEQUENCES[0x08] = '\\b'; +ESCAPE_SEQUENCES[0x09] = '\\t'; +ESCAPE_SEQUENCES[0x0A] = '\\n'; +ESCAPE_SEQUENCES[0x0B] = '\\v'; +ESCAPE_SEQUENCES[0x0C] = '\\f'; +ESCAPE_SEQUENCES[0x0D] = '\\r'; +ESCAPE_SEQUENCES[0x1B] = '\\e'; +ESCAPE_SEQUENCES[0x22] = '\\"'; +ESCAPE_SEQUENCES[0x5C] = '\\\\'; +ESCAPE_SEQUENCES[0x85] = '\\N'; +ESCAPE_SEQUENCES[0xA0] = '\\_'; +ESCAPE_SEQUENCES[0x2028] = '\\L'; +ESCAPE_SEQUENCES[0x2029] = '\\P'; - authz = sprintf(AUTHZ_FMT, - sig.keyId, - sig.algorithm, - self.rs_headers.join(' '), - sig.signature); - } catch (e) { - cb(e); - return; - } - cb(null, authz); - }); +var DEPRECATED_BOOLEANS_SYNTAX = [ + 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', + 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' +]; - } else { - try { - var sigObj = this.rs_signer.sign(); - } catch (e) { - cb(e); - return; - } - alg = (this.rs_alg[0] || this.rs_key.type) + '-' + sigObj.hashAlgorithm; - var signature = sigObj.toString(); - authz = sprintf(AUTHZ_FMT, - this.rs_keyId, - alg, - this.rs_headers.join(' '), - signature); - cb(null, authz); - } -}; +var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/; -///--- Exported API +function compileStyleMap(schema, map) { + var result, keys, index, length, tag, style, type; -module.exports = { - /** - * Identifies whether a given object is a request signer or not. - * - * @param {Object} object, the object to identify - * @returns {Boolean} - */ - isSigner: function (obj) { - if (typeof (obj) === 'object' && obj instanceof RequestSigner) - return (true); - return (false); - }, + if (map === null) return {}; - /** - * Creates a request signer, used to asynchronously build a signature - * for a request (does not have to be an http.ClientRequest). - * - * @param {Object} options, either: - * - {String} keyId - * - {String|Buffer} key - * - {String} algorithm (optional, required for HMAC) - * or: - * - {Func} sign (data, cb) - * @return {RequestSigner} - */ - createSigner: function createSigner(options) { - return (new RequestSigner(options)); - }, + result = {}; + keys = Object.keys(map); - /** - * Adds an 'Authorization' header to an http.ClientRequest object. - * - * Note that this API will add a Date header if it's not already set. Any - * other headers in the options.headers array MUST be present, or this - * will throw. - * - * You shouldn't need to check the return type; it's just there if you want - * to be pedantic. - * - * The optional flag indicates whether parsing should use strict enforcement - * of the version draft-cavage-http-signatures-04 of the spec or beyond. - * The default is to be loose and support - * older versions for compatibility. - * - * @param {Object} request an instance of http.ClientRequest. - * @param {Object} options signing parameters object: - * - {String} keyId required. - * - {String} key required (either a PEM or HMAC key). - * - {Array} headers optional; defaults to ['date']. - * - {String} algorithm optional (unless key is HMAC); - * default is the same as the sshpk default - * signing algorithm for the type of key given - * - {String} httpVersion optional; defaults to '1.1'. - * - {Boolean} strict optional; defaults to 'false'. - * @return {Boolean} true if Authorization (and optionally Date) were added. - * @throws {TypeError} on bad parameter types (input). - * @throws {InvalidAlgorithmError} if algorithm was bad or incompatible with - * the given key. - * @throws {sshpk.KeyParseError} if key was bad. - * @throws {MissingHeaderError} if a header to be signed was specified but - * was not present. - */ - signRequest: function signRequest(request, options) { - assert.object(request, 'request'); - assert.object(options, 'options'); - assert.optionalString(options.algorithm, 'options.algorithm'); - assert.string(options.keyId, 'options.keyId'); - assert.optionalArrayOfString(options.headers, 'options.headers'); - assert.optionalString(options.httpVersion, 'options.httpVersion'); + for (index = 0, length = keys.length; index < length; index += 1) { + tag = keys[index]; + style = String(map[tag]); - if (!request.getHeader('Date')) - request.setHeader('Date', jsprim.rfc1123(new Date())); - if (!options.headers) - options.headers = ['date']; - if (!options.httpVersion) - options.httpVersion = '1.1'; + if (tag.slice(0, 2) === '!!') { + tag = 'tag:yaml.org,2002:' + tag.slice(2); + } + type = schema.compiledTypeMap['fallback'][tag]; - var alg = []; - if (options.algorithm) { - options.algorithm = options.algorithm.toLowerCase(); - alg = validateAlgorithm(options.algorithm); + if (type && _hasOwnProperty.call(type.styleAliases, style)) { + style = type.styleAliases[style]; } - var i; - var stringToSign = ''; - for (i = 0; i < options.headers.length; i++) { - if (typeof (options.headers[i]) !== 'string') - throw new TypeError('options.headers must be an array of Strings'); + result[tag] = style; + } - var h = options.headers[i].toLowerCase(); + return result; +} - if (h === 'request-line') { - if (!options.strict) { - /** - * We allow headers from the older spec drafts if strict parsing isn't - * specified in options. - */ - stringToSign += - request.method + ' ' + request.path + ' HTTP/' + - options.httpVersion; - } else { - /* Strict parsing doesn't allow older draft headers. */ - throw (new StrictParsingError('request-line is not a valid header ' + - 'with strict parsing enabled.')); - } - } else if (h === '(request-target)') { - stringToSign += - '(request-target): ' + request.method.toLowerCase() + ' ' + - request.path; - } else { - var value = request.getHeader(h); - if (value === undefined || value === '') { - throw new MissingHeaderError(h + ' was not in the request'); - } - stringToSign += h + ': ' + value; - } +function encodeHex(character) { + var string, handle, length; + + string = character.toString(16).toUpperCase(); + + if (character <= 0xFF) { + handle = 'x'; + length = 2; + } else if (character <= 0xFFFF) { + handle = 'u'; + length = 4; + } else if (character <= 0xFFFFFFFF) { + handle = 'U'; + length = 8; + } else { + throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); + } - if ((i + 1) < options.headers.length) - stringToSign += '\n'; - } + return '\\' + handle + common.repeat('0', length - string.length) + string; +} - /* This is just for unit tests. */ - if (request.hasOwnProperty('_stringToSign')) { - request._stringToSign = stringToSign; - } - var signature; - if (alg[0] === 'hmac') { - if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key)) - throw (new TypeError('options.key must be a string or Buffer')); +var QUOTING_TYPE_SINGLE = 1, + QUOTING_TYPE_DOUBLE = 2; - var hmac = crypto.createHmac(alg[1].toUpperCase(), options.key); - hmac.update(stringToSign); - signature = hmac.digest('base64'); +function State(options) { + this.schema = options['schema'] || DEFAULT_SCHEMA; + this.indent = Math.max(1, (options['indent'] || 2)); + this.noArrayIndent = options['noArrayIndent'] || false; + this.skipInvalid = options['skipInvalid'] || false; + this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); + this.styleMap = compileStyleMap(this.schema, options['styles'] || null); + this.sortKeys = options['sortKeys'] || false; + this.lineWidth = options['lineWidth'] || 80; + this.noRefs = options['noRefs'] || false; + this.noCompatMode = options['noCompatMode'] || false; + this.condenseFlow = options['condenseFlow'] || false; + this.quotingType = options['quotingType'] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE; + this.forceQuotes = options['forceQuotes'] || false; + this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null; - } else { - var key = options.key; - if (typeof (key) === 'string' || Buffer.isBuffer(key)) - key = sshpk.parsePrivateKey(options.key); + this.implicitTypes = this.schema.compiledImplicit; + this.explicitTypes = this.schema.compiledExplicit; - assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]), - 'options.key must be a sshpk.PrivateKey'); + this.tag = null; + this.result = ''; - if (!PK_ALGOS[key.type]) { - throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' + - 'keys are not supported')); - } + this.duplicates = []; + this.usedDuplicates = null; +} - if (alg[0] !== undefined && key.type !== alg[0]) { - throw (new InvalidAlgorithmError('options.key must be a ' + - alg[0].toUpperCase() + ' key, was given a ' + - key.type.toUpperCase() + ' key instead')); - } +// Indents every line in a string. Empty lines (\n only) are not indented. +function indentString(string, spaces) { + var ind = common.repeat(' ', spaces), + position = 0, + next = -1, + result = '', + line, + length = string.length; - var signer = key.createSign(alg[1]); - signer.update(stringToSign); - var sigObj = signer.sign(); - if (!HASH_ALGOS[sigObj.hashAlgorithm]) { - throw (new InvalidAlgorithmError(sigObj.hashAlgorithm.toUpperCase() + - ' is not a supported hash algorithm')); - } - options.algorithm = key.type + '-' + sigObj.hashAlgorithm; - signature = sigObj.toString(); - assert.notStrictEqual(signature, '', 'empty signature produced'); + while (position < length) { + next = string.indexOf('\n', position); + if (next === -1) { + line = string.slice(position); + position = length; + } else { + line = string.slice(position, next + 1); + position = next + 1; } - var authzHeaderName = options.authorizationHeaderName || 'Authorization'; - - request.setHeader(authzHeaderName, sprintf(AUTHZ_FMT, - options.keyId, - options.algorithm, - options.headers.join(' '), - signature)); + if (line.length && line !== '\n') result += ind; - return true; + result += line; } -}; + return result; +} +function generateNextLine(state, level) { + return '\n' + common.repeat(' ', state.indent * level); +} -/***/ }), +function testImplicitResolving(state, str) { + var index, length, type; -/***/ 65689: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { + type = state.implicitTypes[index]; -// Copyright 2012 Joyent, Inc. All rights reserved. + if (type.resolve(str)) { + return true; + } + } -var assert = __nccwpck_require__(66631); -var sshpk = __nccwpck_require__(87022); -var util = __nccwpck_require__(73837); + return false; +} -var HASH_ALGOS = { - 'sha1': true, - 'sha256': true, - 'sha512': true -}; +// [33] s-white ::= s-space | s-tab +function isWhitespace(c) { + return c === CHAR_SPACE || c === CHAR_TAB; +} -var PK_ALGOS = { - 'rsa': true, - 'dsa': true, - 'ecdsa': true -}; +// Returns true if the character can be printed without escaping. +// From YAML 1.2: "any allowed characters known to be non-printable +// should also be escaped. [However,] This isn’t mandatory" +// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. +function isPrintable(c) { + return (0x00020 <= c && c <= 0x00007E) + || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) + || ((0x0E000 <= c && c <= 0x00FFFD) && c !== CHAR_BOM) + || (0x10000 <= c && c <= 0x10FFFF); +} -function HttpSignatureError(message, caller) { - if (Error.captureStackTrace) - Error.captureStackTrace(this, caller || HttpSignatureError); +// [34] ns-char ::= nb-char - s-white +// [27] nb-char ::= c-printable - b-char - c-byte-order-mark +// [26] b-char ::= b-line-feed | b-carriage-return +// Including s-white (for some reason, examples doesn't match specs in this aspect) +// ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark +function isNsCharOrWhitespace(c) { + return isPrintable(c) + && c !== CHAR_BOM + // - b-char + && c !== CHAR_CARRIAGE_RETURN + && c !== CHAR_LINE_FEED; +} - this.message = message; - this.name = caller.name; +// [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out +// c = flow-in ⇒ ns-plain-safe-in +// c = block-key ⇒ ns-plain-safe-out +// c = flow-key ⇒ ns-plain-safe-in +// [128] ns-plain-safe-out ::= ns-char +// [129] ns-plain-safe-in ::= ns-char - c-flow-indicator +// [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:” - “#” ) +// | ( /* An ns-char preceding */ “#” ) +// | ( “:” /* Followed by an ns-plain-safe(c) */ ) +function isPlainSafe(c, prev, inblock) { + var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c); + var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c); + return ( + // ns-plain-safe + inblock ? // c = flow-in + cIsNsCharOrWhitespace + : cIsNsCharOrWhitespace + // - c-flow-indicator + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + ) + // ns-plain-char + && c !== CHAR_SHARP // false on '#' + && !(prev === CHAR_COLON && !cIsNsChar) // false on ': ' + || (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) // change to true on '[^ ]#' + || (prev === CHAR_COLON && cIsNsChar); // change to true on ':[^ ]' } -util.inherits(HttpSignatureError, Error); -function InvalidAlgorithmError(message) { - HttpSignatureError.call(this, message, InvalidAlgorithmError); +// Simplified test for values allowed as the first character in plain style. +function isPlainSafeFirst(c) { + // Uses a subset of ns-char - c-indicator + // where ns-char = nb-char - s-white. + // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part + return isPrintable(c) && c !== CHAR_BOM + && !isWhitespace(c) // - s-white + // - (c-indicator ::= + // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” + && c !== CHAR_MINUS + && c !== CHAR_QUESTION + && c !== CHAR_COLON + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” + && c !== CHAR_SHARP + && c !== CHAR_AMPERSAND + && c !== CHAR_ASTERISK + && c !== CHAR_EXCLAMATION + && c !== CHAR_VERTICAL_LINE + && c !== CHAR_EQUALS + && c !== CHAR_GREATER_THAN + && c !== CHAR_SINGLE_QUOTE + && c !== CHAR_DOUBLE_QUOTE + // | “%” | “@” | “`”) + && c !== CHAR_PERCENT + && c !== CHAR_COMMERCIAL_AT + && c !== CHAR_GRAVE_ACCENT; } -util.inherits(InvalidAlgorithmError, HttpSignatureError); -function validateAlgorithm(algorithm) { - var alg = algorithm.toLowerCase().split('-'); +// Simplified test for values allowed as the last character in plain style. +function isPlainSafeLast(c) { + // just not whitespace or colon, it will be checked to be plain character later + return !isWhitespace(c) && c !== CHAR_COLON; +} - if (alg.length !== 2) { - throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' is not a ' + - 'valid algorithm')); +// Same as 'string'.codePointAt(pos), but works in older browsers. +function codePointAt(string, pos) { + var first = string.charCodeAt(pos), second; + if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) { + second = string.charCodeAt(pos + 1); + if (second >= 0xDC00 && second <= 0xDFFF) { + // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + } } + return first; +} - if (alg[0] !== 'hmac' && !PK_ALGOS[alg[0]]) { - throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' type keys ' + - 'are not supported')); - } +// Determines whether block indentation indicator is required. +function needIndentIndicator(string) { + var leadingSpaceRe = /^\n* /; + return leadingSpaceRe.test(string); +} - if (!HASH_ALGOS[alg[1]]) { - throw (new InvalidAlgorithmError(alg[1].toUpperCase() + ' is not a ' + - 'supported hash algorithm')); +var STYLE_PLAIN = 1, + STYLE_SINGLE = 2, + STYLE_LITERAL = 3, + STYLE_FOLDED = 4, + STYLE_DOUBLE = 5; + +// Determines which scalar styles are possible and returns the preferred style. +// lineWidth = -1 => no limit. +// Pre-conditions: str.length > 0. +// Post-conditions: +// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. +// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). +// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). +function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, + testAmbiguousType, quotingType, forceQuotes, inblock) { + + var i; + var char = 0; + var prevChar = null; + var hasLineBreak = false; + var hasFoldableLine = false; // only checked if shouldTrackWidth + var shouldTrackWidth = lineWidth !== -1; + var previousLineBreak = -1; // count the first line correctly + var plain = isPlainSafeFirst(codePointAt(string, 0)) + && isPlainSafeLast(codePointAt(string, string.length - 1)); + + if (singleLineOnly || forceQuotes) { + // Case: no block styles. + // Check for disallowed characters to rule out plain and single. + for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + plain = plain && isPlainSafe(char, prevChar, inblock); + prevChar = char; + } + } else { + // Case: block styles permitted. + for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + if (char === CHAR_LINE_FEED) { + hasLineBreak = true; + // Check if any line can be folded. + if (shouldTrackWidth) { + hasFoldableLine = hasFoldableLine || + // Foldable line = too long, and not more-indented. + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' '); + previousLineBreak = i; + } + } else if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + plain = plain && isPlainSafe(char, prevChar, inblock); + prevChar = char; + } + // in case the end is missing a \n + hasFoldableLine = hasFoldableLine || (shouldTrackWidth && + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' ')); + } + // Although every style can represent \n without escaping, prefer block styles + // for multiline, since they're more readable and they don't add empty lines. + // Also prefer folding a super-long line. + if (!hasLineBreak && !hasFoldableLine) { + // Strings interpretable as another type have to be quoted; + // e.g. the string 'true' vs. the boolean true. + if (plain && !forceQuotes && !testAmbiguousType(string)) { + return STYLE_PLAIN; + } + return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; } + // Edge case: block indentation indicator can only have one digit. + if (indentPerLevel > 9 && needIndentIndicator(string)) { + return STYLE_DOUBLE; + } + // At this point we know block styles are valid. + // Prefer literal style unless we want to fold. + if (!forceQuotes) { + return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; + } + return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; +} - return (alg); +// Note: line breaking/folding is implemented for only the folded style. +// NB. We drop the last trailing newline (if any) of a returned block scalar +// since the dumper adds its own newline. This always works: +// • No ending newline => unaffected; already using strip "-" chomping. +// • Ending newline => removed then restored. +// Importantly, this keeps the "+" chomp indicator from gaining an extra line. +function writeScalar(state, string, level, iskey, inblock) { + state.dump = (function () { + if (string.length === 0) { + return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''"; + } + if (!state.noCompatMode) { + if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) { + return state.quotingType === QUOTING_TYPE_DOUBLE ? ('"' + string + '"') : ("'" + string + "'"); + } + } + + var indent = state.indent * Math.max(1, level); // no 0-indent scalars + // As indentation gets deeper, let the width decrease monotonically + // to the lower bound min(state.lineWidth, 40). + // Note that this implies + // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. + // state.lineWidth > 40 + state.indent: width decreases until the lower bound. + // This behaves better than a constant minimum width which disallows narrower options, + // or an indent threshold which causes the width to suddenly increase. + var lineWidth = state.lineWidth === -1 + ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); + + // Without knowing if keys are implicit/explicit, assume implicit for safety. + var singleLineOnly = iskey + // No block styles in flow mode. + || (state.flowLevel > -1 && level >= state.flowLevel); + function testAmbiguity(string) { + return testImplicitResolving(state, string); + } + + switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, + testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) { + + case STYLE_PLAIN: + return string; + case STYLE_SINGLE: + return "'" + string.replace(/'/g, "''") + "'"; + case STYLE_LITERAL: + return '|' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(string, indent)); + case STYLE_FOLDED: + return '>' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); + case STYLE_DOUBLE: + return '"' + escapeString(string, lineWidth) + '"'; + default: + throw new YAMLException('impossible error: invalid scalar style'); + } + }()); } -///--- API +// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. +function blockHeader(string, indentPerLevel) { + var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; -module.exports = { + // note the special case: the string '\n' counts as a "trailing" empty line. + var clip = string[string.length - 1] === '\n'; + var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); + var chomp = keep ? '+' : (clip ? '' : '-'); - HASH_ALGOS: HASH_ALGOS, - PK_ALGOS: PK_ALGOS, + return indentIndicator + chomp + '\n'; +} - HttpSignatureError: HttpSignatureError, - InvalidAlgorithmError: InvalidAlgorithmError, +// (See the note for writeScalar.) +function dropEndingNewline(string) { + return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; +} - validateAlgorithm: validateAlgorithm, +// Note: a long line without a suitable break point will exceed the width limit. +// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. +function foldString(string, width) { + // In folded style, $k$ consecutive newlines output as $k+1$ newlines— + // unless they're before or after a more-indented line, or at the very + // beginning or end, in which case $k$ maps to $k$. + // Therefore, parse each chunk as newline(s) followed by a content line. + var lineRe = /(\n+)([^\n]*)/g; - /** - * Converts an OpenSSH public key (rsa only) to a PKCS#8 PEM file. - * - * The intent of this module is to interoperate with OpenSSL only, - * specifically the node crypto module's `verify` method. - * - * @param {String} key an OpenSSH public key. - * @return {String} PEM encoded form of the RSA public key. - * @throws {TypeError} on bad input. - * @throws {Error} on invalid ssh key formatted data. - */ - sshKeyToPEM: function sshKeyToPEM(key) { - assert.string(key, 'ssh_key'); + // first line (possibly an empty line) + var result = (function () { + var nextLF = string.indexOf('\n'); + nextLF = nextLF !== -1 ? nextLF : string.length; + lineRe.lastIndex = nextLF; + return foldLine(string.slice(0, nextLF), width); + }()); + // If we haven't reached the first content line yet, don't add an extra \n. + var prevMoreIndented = string[0] === '\n' || string[0] === ' '; + var moreIndented; - var k = sshpk.parseKey(key, 'ssh'); - return (k.toString('pem')); - }, + // rest of the lines + var match; + while ((match = lineRe.exec(string))) { + var prefix = match[1], line = match[2]; + moreIndented = (line[0] === ' '); + result += prefix + + (!prevMoreIndented && !moreIndented && line !== '' + ? '\n' : '') + + foldLine(line, width); + prevMoreIndented = moreIndented; + } + return result; +} - /** - * Generates an OpenSSH fingerprint from an ssh public key. - * - * @param {String} key an OpenSSH public key. - * @return {String} key fingerprint. - * @throws {TypeError} on bad input. - * @throws {Error} if what you passed doesn't look like an ssh public key. - */ - fingerprint: function fingerprint(key) { - assert.string(key, 'ssh_key'); +// Greedy line breaking. +// Picks the longest line under the limit each time, +// otherwise settles for the shortest line over the limit. +// NB. More-indented lines *cannot* be folded, as that would add an extra \n. +function foldLine(line, width) { + if (line === '' || line[0] === ' ') return line; - var k = sshpk.parseKey(key, 'ssh'); - return (k.fingerprint('md5').toString('hex')); - }, + // Since a more-indented line adds a \n, breaks can't be followed by a space. + var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. + var match; + // start is an inclusive index. end, curr, and next are exclusive. + var start = 0, end, curr = 0, next = 0; + var result = ''; - /** - * Converts a PKGCS#8 PEM file to an OpenSSH public key (rsa) - * - * The reverse of the above function. - */ - pemToRsaSSHKey: function pemToRsaSSHKey(pem, comment) { - assert.equal('string', typeof (pem), 'typeof pem'); + // Invariants: 0 <= start <= length-1. + // 0 <= curr <= next <= max(0, length-2). curr - start <= width. + // Inside the loop: + // A match implies length >= 2, so curr and next are <= length-2. + while ((match = breakRe.exec(line))) { + next = match.index; + // maintain invariant: curr - start <= width + if (next - start > width) { + end = (curr > start) ? curr : next; // derive end <= length-2 + result += '\n' + line.slice(start, end); + // skip the space that was output as \n + start = end + 1; // derive start <= length-1 + } + curr = next; + } - var k = sshpk.parseKey(pem, 'pem'); - k.comment = comment; - return (k.toString('ssh')); + // By the invariants, start <= length-1, so there is something left over. + // It is either the whole string or a part starting from non-whitespace. + result += '\n'; + // Insert a break if the remainder is too long and there is a break available. + if (line.length - start > width && curr > start) { + result += line.slice(start, curr) + '\n' + line.slice(curr + 1); + } else { + result += line.slice(start); } -}; + return result.slice(1); // drop extra \n joiner +} -/***/ }), +// Escapes a double-quoted string. +function escapeString(string) { + var result = ''; + var char = 0; + var escapeSeq; -/***/ 51227: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + escapeSeq = ESCAPE_SEQUENCES[char]; -// Copyright 2015 Joyent, Inc. + if (!escapeSeq && isPrintable(char)) { + result += string[i]; + if (char >= 0x10000) result += string[i + 1]; + } else { + result += escapeSeq || encodeHex(char); + } + } -var assert = __nccwpck_require__(66631); -var crypto = __nccwpck_require__(6113); -var sshpk = __nccwpck_require__(87022); -var utils = __nccwpck_require__(65689); + return result; +} -var HASH_ALGOS = utils.HASH_ALGOS; -var PK_ALGOS = utils.PK_ALGOS; -var InvalidAlgorithmError = utils.InvalidAlgorithmError; -var HttpSignatureError = utils.HttpSignatureError; -var validateAlgorithm = utils.validateAlgorithm; +function writeFlowSequence(state, level, object) { + var _result = '', + _tag = state.tag, + index, + length, + value; -///--- Exported API + for (index = 0, length = object.length; index < length; index += 1) { + value = object[index]; -module.exports = { - /** - * Verify RSA/DSA signature against public key. You are expected to pass in - * an object that was returned from `parse()`. - * - * @param {Object} parsedSignature the object you got from `parse`. - * @param {String} pubkey RSA/DSA private key PEM. - * @return {Boolean} true if valid, false otherwise. - * @throws {TypeError} if you pass in bad arguments. - * @throws {InvalidAlgorithmError} - */ - verifySignature: function verifySignature(parsedSignature, pubkey) { - assert.object(parsedSignature, 'parsedSignature'); - if (typeof (pubkey) === 'string' || Buffer.isBuffer(pubkey)) - pubkey = sshpk.parseKey(pubkey); - assert.ok(sshpk.Key.isKey(pubkey, [1, 1]), 'pubkey must be a sshpk.Key'); + if (state.replacer) { + value = state.replacer.call(object, String(index), value); + } - var alg = validateAlgorithm(parsedSignature.algorithm); - if (alg[0] === 'hmac' || alg[0] !== pubkey.type) - return (false); + // Write only valid elements, put null instead of invalid elements. + if (writeNode(state, level, value, false, false) || + (typeof value === 'undefined' && + writeNode(state, level, null, false, false))) { - var v = pubkey.createVerify(alg[1]); - v.update(parsedSignature.signingString); - return (v.verify(parsedSignature.params.signature, 'base64')); - }, + if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : ''); + _result += state.dump; + } + } - /** - * Verify HMAC against shared secret. You are expected to pass in an object - * that was returned from `parse()`. - * - * @param {Object} parsedSignature the object you got from `parse`. - * @param {String} secret HMAC shared secret. - * @return {Boolean} true if valid, false otherwise. - * @throws {TypeError} if you pass in bad arguments. - * @throws {InvalidAlgorithmError} - */ - verifyHMAC: function verifyHMAC(parsedSignature, secret) { - assert.object(parsedSignature, 'parsedHMAC'); - assert.string(secret, 'secret'); + state.tag = _tag; + state.dump = '[' + _result + ']'; +} - var alg = validateAlgorithm(parsedSignature.algorithm); - if (alg[0] !== 'hmac') - return (false); +function writeBlockSequence(state, level, object, compact) { + var _result = '', + _tag = state.tag, + index, + length, + value; - var hashAlg = alg[1].toUpperCase(); + for (index = 0, length = object.length; index < length; index += 1) { + value = object[index]; - var hmac = crypto.createHmac(hashAlg, secret); - hmac.update(parsedSignature.signingString); + if (state.replacer) { + value = state.replacer.call(object, String(index), value); + } - /* - * Now double-hash to avoid leaking timing information - there's - * no easy constant-time compare in JS, so we use this approach - * instead. See for more info: - * https://www.isecpartners.com/blog/2011/february/double-hmac- - * verification.aspx - */ - var h1 = crypto.createHmac(hashAlg, secret); - h1.update(hmac.digest()); - h1 = h1.digest(); - var h2 = crypto.createHmac(hashAlg, secret); - h2.update(new Buffer(parsedSignature.params.signature, 'base64')); - h2 = h2.digest(); + // Write only valid elements, put null instead of invalid elements. + if (writeNode(state, level + 1, value, true, true, false, true) || + (typeof value === 'undefined' && + writeNode(state, level + 1, null, true, true, false, true))) { - /* Node 0.8 returns strings from .digest(). */ - if (typeof (h1) === 'string') - return (h1 === h2); - /* And node 0.10 lacks the .equals() method on Buffers. */ - if (Buffer.isBuffer(h1) && !h1.equals) - return (h1.toString('binary') === h2.toString('binary')); + if (!compact || _result !== '') { + _result += generateNextLine(state, level); + } - return (h1.equals(h2)); + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + _result += '-'; + } else { + _result += '- '; + } + + _result += state.dump; + } } -}; + state.tag = _tag; + state.dump = _result || '[]'; // Empty sequence if no valid values. +} -/***/ }), +function writeFlowMapping(state, level, object) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + pairBuffer; -/***/ 79898: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + for (index = 0, length = objectKeyList.length; index < length; index += 1) { -"use strict"; + pairBuffer = ''; + if (_result !== '') pairBuffer += ', '; -const EventEmitter = __nccwpck_require__(82361); -const tls = __nccwpck_require__(24404); -const http2 = __nccwpck_require__(85158); -const QuickLRU = __nccwpck_require__(49273); + if (state.condenseFlow) pairBuffer += '"'; -const kCurrentStreamsCount = Symbol('currentStreamsCount'); -const kRequest = Symbol('request'); -const kOriginSet = Symbol('cachedOriginSet'); -const kGracefullyClosing = Symbol('gracefullyClosing'); + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; -const nameKeys = [ - // `http2.connect()` options - 'maxDeflateDynamicTableSize', - 'maxSessionMemory', - 'maxHeaderListPairs', - 'maxOutstandingPings', - 'maxReservedRemoteStreams', - 'maxSendHeaderBlockLength', - 'paddingStrategy', + if (state.replacer) { + objectValue = state.replacer.call(object, objectKey, objectValue); + } - // `tls.connect()` options - 'localAddress', - 'path', - 'rejectUnauthorized', - 'minDHSize', + if (!writeNode(state, level, objectKey, false, false)) { + continue; // Skip this pair because of invalid key; + } - // `tls.createSecureContext()` options - 'ca', - 'cert', - 'clientCertEngine', - 'ciphers', - 'key', - 'pfx', - 'servername', - 'minVersion', - 'maxVersion', - 'secureProtocol', - 'crl', - 'honorCipherOrder', - 'ecdhCurve', - 'dhparam', - 'secureOptions', - 'sessionIdContext' -]; + if (state.dump.length > 1024) pairBuffer += '? '; -const getSortedIndex = (array, value, compare) => { - let low = 0; - let high = array.length; + pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); - while (low < high) { - const mid = (low + high) >>> 1; + if (!writeNode(state, level, objectValue, false, false)) { + continue; // Skip this pair because of invalid value. + } - /* istanbul ignore next */ - if (compare(array[mid], value)) { - // This never gets called because we use descending sort. Better to have this anyway. - low = mid + 1; - } else { - high = mid; - } - } + pairBuffer += state.dump; - return low; -}; + // Both key and value are valid. + _result += pairBuffer; + } -const compareSessions = (a, b) => { - return a.remoteSettings.maxConcurrentStreams > b.remoteSettings.maxConcurrentStreams; -}; + state.tag = _tag; + state.dump = '{' + _result + '}'; +} -// See https://tools.ietf.org/html/rfc8336 -const closeCoveredSessions = (where, session) => { - // Clients SHOULD NOT emit new requests on any connection whose Origin - // Set is a proper subset of another connection's Origin Set, and they - // SHOULD close it once all outstanding requests are satisfied. - for (const coveredSession of where) { - if ( - // The set is a proper subset when its length is less than the other set. - coveredSession[kOriginSet].length < session[kOriginSet].length && +function writeBlockMapping(state, level, object, compact) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + explicitPair, + pairBuffer; - // And the other set includes all elements of the subset. - coveredSession[kOriginSet].every(origin => session[kOriginSet].includes(origin)) && + // Allow sorting keys so that the output file is deterministic + if (state.sortKeys === true) { + // Default sorting + objectKeyList.sort(); + } else if (typeof state.sortKeys === 'function') { + // Custom sort function + objectKeyList.sort(state.sortKeys); + } else if (state.sortKeys) { + // Something is wrong + throw new YAMLException('sortKeys must be a boolean or a function'); + } - // Makes sure that the session can handle all requests from the covered session. - coveredSession[kCurrentStreamsCount] + session[kCurrentStreamsCount] <= session.remoteSettings.maxConcurrentStreams - ) { - // This allows pending requests to finish and prevents making new requests. - gracefullyClose(coveredSession); - } - } -}; + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = ''; -// This is basically inverted `closeCoveredSessions(...)`. -const closeSessionIfCovered = (where, coveredSession) => { - for (const session of where) { - if ( - coveredSession[kOriginSet].length < session[kOriginSet].length && - coveredSession[kOriginSet].every(origin => session[kOriginSet].includes(origin)) && - coveredSession[kCurrentStreamsCount] + session[kCurrentStreamsCount] <= session.remoteSettings.maxConcurrentStreams - ) { - gracefullyClose(coveredSession); - } - } -}; + if (!compact || _result !== '') { + pairBuffer += generateNextLine(state, level); + } -const getSessions = ({agent, isFree}) => { - const result = {}; + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; - // eslint-disable-next-line guard-for-in - for (const normalizedOptions in agent.sessions) { - const sessions = agent.sessions[normalizedOptions]; + if (state.replacer) { + objectValue = state.replacer.call(object, objectKey, objectValue); + } - const filtered = sessions.filter(session => { - const result = session[Agent.kCurrentStreamsCount] < session.remoteSettings.maxConcurrentStreams; + if (!writeNode(state, level + 1, objectKey, true, true, true)) { + continue; // Skip this pair because of invalid key. + } - return isFree ? result : !result; - }); + explicitPair = (state.tag !== null && state.tag !== '?') || + (state.dump && state.dump.length > 1024); - if (filtered.length !== 0) { - result[normalizedOptions] = filtered; - } - } + if (explicitPair) { + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += '?'; + } else { + pairBuffer += '? '; + } + } - return result; -}; + pairBuffer += state.dump; -const gracefullyClose = session => { - session[kGracefullyClosing] = true; + if (explicitPair) { + pairBuffer += generateNextLine(state, level); + } - if (session[kCurrentStreamsCount] === 0) { - session.close(); - } -}; + if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { + continue; // Skip this pair because of invalid value. + } -class Agent extends EventEmitter { - constructor({timeout = 60000, maxSessions = Infinity, maxFreeSessions = 10, maxCachedTlsSessions = 100} = {}) { - super(); + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += ':'; + } else { + pairBuffer += ': '; + } - // A session is considered busy when its current streams count - // is equal to or greater than the `maxConcurrentStreams` value. + pairBuffer += state.dump; - // A session is considered free when its current streams count - // is less than the `maxConcurrentStreams` value. + // Both key and value are valid. + _result += pairBuffer; + } - // SESSIONS[NORMALIZED_OPTIONS] = []; - this.sessions = {}; + state.tag = _tag; + state.dump = _result || '{}'; // Empty mapping if no valid pairs. +} - // The queue for creating new sessions. It looks like this: - // QUEUE[NORMALIZED_OPTIONS][NORMALIZED_ORIGIN] = ENTRY_FUNCTION - // - // The entry function has `listeners`, `completed` and `destroyed` properties. - // `listeners` is an array of objects containing `resolve` and `reject` functions. - // `completed` is a boolean. It's set to true after ENTRY_FUNCTION is executed. - // `destroyed` is a boolean. If it's set to true, the session will be destroyed if hasn't connected yet. - this.queue = {}; +function detectType(state, object, explicit) { + var _result, typeList, index, length, type, style; - // Each session will use this timeout value. - this.timeout = timeout; + typeList = explicit ? state.explicitTypes : state.implicitTypes; - // Max sessions in total - this.maxSessions = maxSessions; + for (index = 0, length = typeList.length; index < length; index += 1) { + type = typeList[index]; - // Max free sessions in total - // TODO: decreasing `maxFreeSessions` should close some sessions - this.maxFreeSessions = maxFreeSessions; + if ((type.instanceOf || type.predicate) && + (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && + (!type.predicate || type.predicate(object))) { - this._freeSessionsCount = 0; - this._sessionsCount = 0; + if (explicit) { + if (type.multi && type.representName) { + state.tag = type.representName(object); + } else { + state.tag = type.tag; + } + } else { + state.tag = '?'; + } - // We don't support push streams by default. - this.settings = { - enablePush: false - }; + if (type.represent) { + style = state.styleMap[type.tag] || type.defaultStyle; - // Reusing TLS sessions increases performance. - this.tlsSessionCache = new QuickLRU({maxSize: maxCachedTlsSessions}); - } + if (_toString.call(type.represent) === '[object Function]') { + _result = type.represent(object, style); + } else if (_hasOwnProperty.call(type.represent, style)) { + _result = type.represent[style](object, style); + } else { + throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); + } - static normalizeOrigin(url, servername) { - if (typeof url === 'string') { - url = new URL(url); - } + state.dump = _result; + } - if (servername && url.hostname !== servername) { - url.hostname = servername; - } + return true; + } + } - return url.origin; - } + return false; +} - normalizeOptions(options) { - let normalized = ''; +// Serializes `object` and writes it to global `result`. +// Returns true on success, or false on invalid object. +// +function writeNode(state, level, object, block, compact, iskey, isblockseq) { + state.tag = null; + state.dump = object; - if (options) { - for (const key of nameKeys) { - if (options[key]) { - normalized += `:${options[key]}`; - } - } - } + if (!detectType(state, object, false)) { + detectType(state, object, true); + } - return normalized; - } + var type = _toString.call(state.dump); + var inblock = block; + var tagStr; - _tryToCreateNewSession(normalizedOptions, normalizedOrigin) { - if (!(normalizedOptions in this.queue) || !(normalizedOrigin in this.queue[normalizedOptions])) { - return; - } + if (block) { + block = (state.flowLevel < 0 || state.flowLevel > level); + } - const item = this.queue[normalizedOptions][normalizedOrigin]; + var objectOrArray = type === '[object Object]' || type === '[object Array]', + duplicateIndex, + duplicate; - // The entry function can be run only once. - // BUG: The session may be never created when: - // - the first condition is false AND - // - this function is never called with the same arguments in the future. - if (this._sessionsCount < this.maxSessions && !item.completed) { - item.completed = true; + if (objectOrArray) { + duplicateIndex = state.duplicates.indexOf(object); + duplicate = duplicateIndex !== -1; + } - item(); - } - } + if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { + compact = false; + } - getSession(origin, options, listeners) { - return new Promise((resolve, reject) => { - if (Array.isArray(listeners)) { - listeners = [...listeners]; + if (duplicate && state.usedDuplicates[duplicateIndex]) { + state.dump = '*ref_' + duplicateIndex; + } else { + if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { + state.usedDuplicates[duplicateIndex] = true; + } + if (type === '[object Object]') { + if (block && (Object.keys(state.dump).length !== 0)) { + writeBlockMapping(state, level, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowMapping(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object Array]') { + if (block && (state.dump.length !== 0)) { + if (state.noArrayIndent && !isblockseq && level > 0) { + writeBlockSequence(state, level - 1, state.dump, compact); + } else { + writeBlockSequence(state, level, state.dump, compact); + } + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowSequence(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object String]') { + if (state.tag !== '?') { + writeScalar(state, state.dump, level, iskey, inblock); + } + } else if (type === '[object Undefined]') { + return false; + } else { + if (state.skipInvalid) return false; + throw new YAMLException('unacceptable kind of an object to dump ' + type); + } - // Resolve the current promise ASAP, we're just moving the listeners. - // They will be executed at a different time. - resolve(); - } else { - listeners = [{resolve, reject}]; - } + if (state.tag !== null && state.tag !== '?') { + // Need to encode all characters except those allowed by the spec: + // + // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */ + // [36] ns-hex-digit ::= ns-dec-digit + // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */ + // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */ + // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-” + // [39] ns-uri-char ::= “%” ns-hex-digit ns-hex-digit | ns-word-char | “#” + // | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,” + // | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]” + // + // Also need to encode '!' because it has special meaning (end of tag prefix). + // + tagStr = encodeURI( + state.tag[0] === '!' ? state.tag.slice(1) : state.tag + ).replace(/!/g, '%21'); - const normalizedOptions = this.normalizeOptions(options); - const normalizedOrigin = Agent.normalizeOrigin(origin, options && options.servername); + if (state.tag[0] === '!') { + tagStr = '!' + tagStr; + } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') { + tagStr = '!!' + tagStr.slice(18); + } else { + tagStr = '!<' + tagStr + '>'; + } - if (normalizedOrigin === undefined) { - for (const {reject} of listeners) { - reject(new TypeError('The `origin` argument needs to be a string or an URL object')); - } + state.dump = tagStr + ' ' + state.dump; + } + } - return; - } + return true; +} - if (normalizedOptions in this.sessions) { - const sessions = this.sessions[normalizedOptions]; +function getDuplicateReferences(object, state) { + var objects = [], + duplicatesIndexes = [], + index, + length; - let maxConcurrentStreams = -1; - let currentStreamsCount = -1; - let optimalSession; + inspectNode(object, objects, duplicatesIndexes); - // We could just do this.sessions[normalizedOptions].find(...) but that isn't optimal. - // Additionally, we are looking for session which has biggest current pending streams count. - for (const session of sessions) { - const sessionMaxConcurrentStreams = session.remoteSettings.maxConcurrentStreams; + for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { + state.duplicates.push(objects[duplicatesIndexes[index]]); + } + state.usedDuplicates = new Array(length); +} - if (sessionMaxConcurrentStreams < maxConcurrentStreams) { - break; - } +function inspectNode(object, objects, duplicatesIndexes) { + var objectKeyList, + index, + length; - if (session[kOriginSet].includes(normalizedOrigin)) { - const sessionCurrentStreamsCount = session[kCurrentStreamsCount]; + if (object !== null && typeof object === 'object') { + index = objects.indexOf(object); + if (index !== -1) { + if (duplicatesIndexes.indexOf(index) === -1) { + duplicatesIndexes.push(index); + } + } else { + objects.push(object); - if ( - sessionCurrentStreamsCount >= sessionMaxConcurrentStreams || - session[kGracefullyClosing] || - // Unfortunately the `close` event isn't called immediately, - // so `session.destroyed` is `true`, but `session.closed` is `false`. - session.destroyed - ) { - continue; - } + if (Array.isArray(object)) { + for (index = 0, length = object.length; index < length; index += 1) { + inspectNode(object[index], objects, duplicatesIndexes); + } + } else { + objectKeyList = Object.keys(object); - // We only need set this once. - if (!optimalSession) { - maxConcurrentStreams = sessionMaxConcurrentStreams; - } + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); + } + } + } + } +} - // We're looking for the session which has biggest current pending stream count, - // in order to minimalize the amount of active sessions. - if (sessionCurrentStreamsCount > currentStreamsCount) { - optimalSession = session; - currentStreamsCount = sessionCurrentStreamsCount; - } - } - } +function dump(input, options) { + options = options || {}; - if (optimalSession) { - /* istanbul ignore next: safety check */ - if (listeners.length !== 1) { - for (const {reject} of listeners) { - const error = new Error( - `Expected the length of listeners to be 1, got ${listeners.length}.\n` + - 'Please report this to https://github.com/szmarczak/http2-wrapper/' - ); + var state = new State(options); - reject(error); - } + if (!state.noRefs) getDuplicateReferences(input, state); - return; - } + var value = input; - listeners[0].resolve(optimalSession); - return; - } - } + if (state.replacer) { + value = state.replacer.call({ '': value }, '', value); + } - if (normalizedOptions in this.queue) { - if (normalizedOrigin in this.queue[normalizedOptions]) { - // There's already an item in the queue, just attach ourselves to it. - this.queue[normalizedOptions][normalizedOrigin].listeners.push(...listeners); + if (writeNode(state, 0, value, true, true)) return state.dump + '\n'; - // This shouldn't be executed here. - // See the comment inside _tryToCreateNewSession. - this._tryToCreateNewSession(normalizedOptions, normalizedOrigin); - return; - } - } else { - this.queue[normalizedOptions] = {}; - } + return ''; +} - // The entry must be removed from the queue IMMEDIATELY when: - // 1. the session connects successfully, - // 2. an error occurs. - const removeFromQueue = () => { - // Our entry can be replaced. We cannot remove the new one. - if (normalizedOptions in this.queue && this.queue[normalizedOptions][normalizedOrigin] === entry) { - delete this.queue[normalizedOptions][normalizedOrigin]; +module.exports.dump = dump; - if (Object.keys(this.queue[normalizedOptions]).length === 0) { - delete this.queue[normalizedOptions]; - } - } - }; - // The main logic is here - const entry = () => { - const name = `${normalizedOrigin}:${normalizedOptions}`; - let receivedSettings = false; +/***/ }), - try { - const session = http2.connect(origin, { - createConnection: this.createConnection, - settings: this.settings, - session: this.tlsSessionCache.get(name), - ...options - }); - session[kCurrentStreamsCount] = 0; - session[kGracefullyClosing] = false; +/***/ 68179: +/***/ ((module) => { - const isFree = () => session[kCurrentStreamsCount] < session.remoteSettings.maxConcurrentStreams; - let wasFree = true; +"use strict"; +// YAML error class. http://stackoverflow.com/questions/8458984 +// - session.socket.once('session', tlsSession => { - this.tlsSessionCache.set(name, tlsSession); - }); - session.once('error', error => { - // Listeners are empty when the session successfully connected. - for (const {reject} of listeners) { - reject(error); - } - // The connection got broken, purge the cache. - this.tlsSessionCache.delete(name); - }); +function formatError(exception, compact) { + var where = '', message = exception.reason || '(unknown reason)'; - session.setTimeout(this.timeout, () => { - // Terminates all streams owned by this session. - // TODO: Maybe the streams should have a "Session timed out" error? - session.destroy(); - }); + if (!exception.mark) return message; - session.once('close', () => { - if (receivedSettings) { - // 1. If it wasn't free then no need to decrease because - // it has been decreased already in session.request(). - // 2. `stream.once('close')` won't increment the count - // because the session is already closed. - if (wasFree) { - this._freeSessionsCount--; - } + if (exception.mark.name) { + where += 'in "' + exception.mark.name + '" '; + } - this._sessionsCount--; + where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')'; - // This cannot be moved to the stream logic, - // because there may be a session that hadn't made a single request. - const where = this.sessions[normalizedOptions]; - where.splice(where.indexOf(session), 1); + if (!compact && exception.mark.snippet) { + where += '\n\n' + exception.mark.snippet; + } - if (where.length === 0) { - delete this.sessions[normalizedOptions]; - } - } else { - // Broken connection - const error = new Error('Session closed without receiving a SETTINGS frame'); - error.code = 'HTTP2WRAPPER_NOSETTINGS'; + return message + ' ' + where; +} - for (const {reject} of listeners) { - reject(error); - } - removeFromQueue(); - } +function YAMLException(reason, mark) { + // Super constructor + Error.call(this); - // There may be another session awaiting. - this._tryToCreateNewSession(normalizedOptions, normalizedOrigin); - }); + this.name = 'YAMLException'; + this.reason = reason; + this.mark = mark; + this.message = formatError(this, false); - // Iterates over the queue and processes listeners. - const processListeners = () => { - if (!(normalizedOptions in this.queue) || !isFree()) { - return; - } + // Include stack trace in error object + if (Error.captureStackTrace) { + // Chrome and NodeJS + Error.captureStackTrace(this, this.constructor); + } else { + // FF, IE 10+ and Safari 6+. Fallback for others + this.stack = (new Error()).stack || ''; + } +} - for (const origin of session[kOriginSet]) { - if (origin in this.queue[normalizedOptions]) { - const {listeners} = this.queue[normalizedOptions][origin]; - // Prevents session overloading. - while (listeners.length !== 0 && isFree()) { - // We assume `resolve(...)` calls `request(...)` *directly*, - // otherwise the session will get overloaded. - listeners.shift().resolve(session); - } +// Inherit from Error +YAMLException.prototype = Object.create(Error.prototype); +YAMLException.prototype.constructor = YAMLException; - const where = this.queue[normalizedOptions]; - if (where[origin].listeners.length === 0) { - delete where[origin]; - if (Object.keys(where).length === 0) { - delete this.queue[normalizedOptions]; - break; - } - } +YAMLException.prototype.toString = function toString(compact) { + return this.name + ': ' + formatError(this, compact); +}; - // We're no longer free, no point in continuing. - if (!isFree()) { - break; - } - } - } - }; - // The Origin Set cannot shrink. No need to check if it suddenly became covered by another one. - session.on('origin', () => { - session[kOriginSet] = session.originSet; +module.exports = YAMLException; - if (!isFree()) { - // The session is full. - return; - } - processListeners(); +/***/ }), - // Close covered sessions (if possible). - closeCoveredSessions(this.sessions[normalizedOptions], session); - }); +/***/ 51161: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - session.once('remoteSettings', () => { - // Fix Node.js bug preventing the process from exiting - session.ref(); - session.unref(); +"use strict"; - this._sessionsCount++; - // The Agent could have been destroyed already. - if (entry.destroyed) { - const error = new Error('Agent has been destroyed'); +/*eslint-disable max-len,no-use-before-define*/ - for (const listener of listeners) { - listener.reject(error); - } +var common = __nccwpck_require__(26829); +var YAMLException = __nccwpck_require__(68179); +var makeSnippet = __nccwpck_require__(96975); +var DEFAULT_SCHEMA = __nccwpck_require__(18759); - session.destroy(); - return; - } - session[kOriginSet] = session.originSet; +var _hasOwnProperty = Object.prototype.hasOwnProperty; - { - const where = this.sessions; - if (normalizedOptions in where) { - const sessions = where[normalizedOptions]; - sessions.splice(getSortedIndex(sessions, session, compareSessions), 0, session); - } else { - where[normalizedOptions] = [session]; - } - } +var CONTEXT_FLOW_IN = 1; +var CONTEXT_FLOW_OUT = 2; +var CONTEXT_BLOCK_IN = 3; +var CONTEXT_BLOCK_OUT = 4; - this._freeSessionsCount += 1; - receivedSettings = true; - this.emit('session', session); +var CHOMPING_CLIP = 1; +var CHOMPING_STRIP = 2; +var CHOMPING_KEEP = 3; - processListeners(); - removeFromQueue(); - // TODO: Close last recently used (or least used?) session - if (session[kCurrentStreamsCount] === 0 && this._freeSessionsCount > this.maxFreeSessions) { - session.close(); - } +var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; +var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; +var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; +var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; +var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; - // Check if we haven't managed to execute all listeners. - if (listeners.length !== 0) { - // Request for a new session with predefined listeners. - this.getSession(normalizedOrigin, options, listeners); - listeners.length = 0; - } - // `session.remoteSettings.maxConcurrentStreams` might get increased - session.on('remoteSettings', () => { - processListeners(); +function _class(obj) { return Object.prototype.toString.call(obj); } - // In case the Origin Set changes - closeCoveredSessions(this.sessions[normalizedOptions], session); - }); - }); +function is_EOL(c) { + return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); +} - // Shim `session.request()` in order to catch all streams - session[kRequest] = session.request; - session.request = (headers, streamOptions) => { - if (session[kGracefullyClosing]) { - throw new Error('The session is gracefully closing. No new streams are allowed.'); - } +function is_WHITE_SPACE(c) { + return (c === 0x09/* Tab */) || (c === 0x20/* Space */); +} - const stream = session[kRequest](headers, streamOptions); +function is_WS_OR_EOL(c) { + return (c === 0x09/* Tab */) || + (c === 0x20/* Space */) || + (c === 0x0A/* LF */) || + (c === 0x0D/* CR */); +} - // The process won't exit until the session is closed or all requests are gone. - session.ref(); +function is_FLOW_INDICATOR(c) { + return c === 0x2C/* , */ || + c === 0x5B/* [ */ || + c === 0x5D/* ] */ || + c === 0x7B/* { */ || + c === 0x7D/* } */; +} - ++session[kCurrentStreamsCount]; +function fromHexCode(c) { + var lc; - if (session[kCurrentStreamsCount] === session.remoteSettings.maxConcurrentStreams) { - this._freeSessionsCount--; - } + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } - stream.once('close', () => { - wasFree = isFree(); + /*eslint-disable no-bitwise*/ + lc = c | 0x20; - --session[kCurrentStreamsCount]; + if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { + return lc - 0x61 + 10; + } - if (!session.destroyed && !session.closed) { - closeSessionIfCovered(this.sessions[normalizedOptions], session); + return -1; +} - if (isFree() && !session.closed) { - if (!wasFree) { - this._freeSessionsCount++; +function escapedHexLen(c) { + if (c === 0x78/* x */) { return 2; } + if (c === 0x75/* u */) { return 4; } + if (c === 0x55/* U */) { return 8; } + return 0; +} - wasFree = true; - } +function fromDecimalCode(c) { + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } - const isEmpty = session[kCurrentStreamsCount] === 0; + return -1; +} - if (isEmpty) { - session.unref(); - } +function simpleEscapeSequence(c) { + /* eslint-disable indent */ + return (c === 0x30/* 0 */) ? '\x00' : + (c === 0x61/* a */) ? '\x07' : + (c === 0x62/* b */) ? '\x08' : + (c === 0x74/* t */) ? '\x09' : + (c === 0x09/* Tab */) ? '\x09' : + (c === 0x6E/* n */) ? '\x0A' : + (c === 0x76/* v */) ? '\x0B' : + (c === 0x66/* f */) ? '\x0C' : + (c === 0x72/* r */) ? '\x0D' : + (c === 0x65/* e */) ? '\x1B' : + (c === 0x20/* Space */) ? ' ' : + (c === 0x22/* " */) ? '\x22' : + (c === 0x2F/* / */) ? '/' : + (c === 0x5C/* \ */) ? '\x5C' : + (c === 0x4E/* N */) ? '\x85' : + (c === 0x5F/* _ */) ? '\xA0' : + (c === 0x4C/* L */) ? '\u2028' : + (c === 0x50/* P */) ? '\u2029' : ''; +} - if ( - isEmpty && - ( - this._freeSessionsCount > this.maxFreeSessions || - session[kGracefullyClosing] - ) - ) { - session.close(); - } else { - closeCoveredSessions(this.sessions[normalizedOptions], session); - processListeners(); - } - } - } - }); +function charFromCodepoint(c) { + if (c <= 0xFFFF) { + return String.fromCharCode(c); + } + // Encode UTF-16 surrogate pair + // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF + return String.fromCharCode( + ((c - 0x010000) >> 10) + 0xD800, + ((c - 0x010000) & 0x03FF) + 0xDC00 + ); +} - return stream; - }; - } catch (error) { - for (const listener of listeners) { - listener.reject(error); - } +// set a property of a literal object, while protecting against prototype pollution, +// see https://github.com/nodeca/js-yaml/issues/164 for more details +function setProperty(object, key, value) { + // used for this specific key only because Object.defineProperty is slow + if (key === '__proto__') { + Object.defineProperty(object, key, { + configurable: true, + enumerable: true, + writable: true, + value: value + }); + } else { + object[key] = value; + } +} - removeFromQueue(); - } - }; +var simpleEscapeCheck = new Array(256); // integer, for fast access +var simpleEscapeMap = new Array(256); +for (var i = 0; i < 256; i++) { + simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; + simpleEscapeMap[i] = simpleEscapeSequence(i); +} - entry.listeners = listeners; - entry.completed = false; - entry.destroyed = false; - this.queue[normalizedOptions][normalizedOrigin] = entry; - this._tryToCreateNewSession(normalizedOptions, normalizedOrigin); - }); - } +function State(input, options) { + this.input = input; - request(origin, options, headers, streamOptions) { - return new Promise((resolve, reject) => { - this.getSession(origin, options, [{ - reject, - resolve: session => { - try { - resolve(session.request(headers, streamOptions)); - } catch (error) { - reject(error); - } - } - }]); - }); - } + this.filename = options['filename'] || null; + this.schema = options['schema'] || DEFAULT_SCHEMA; + this.onWarning = options['onWarning'] || null; + // (Hidden) Remove? makes the loader to expect YAML 1.1 documents + // if such documents have no explicit %YAML directive + this.legacy = options['legacy'] || false; - createConnection(origin, options) { - return Agent.connect(origin, options); - } + this.json = options['json'] || false; + this.listener = options['listener'] || null; - static connect(origin, options) { - options.ALPNProtocols = ['h2']; + this.implicitTypes = this.schema.compiledImplicit; + this.typeMap = this.schema.compiledTypeMap; - const port = origin.port || 443; - const host = origin.hostname || origin.host; + this.length = input.length; + this.position = 0; + this.line = 0; + this.lineStart = 0; + this.lineIndent = 0; - if (typeof options.servername === 'undefined') { - options.servername = host; - } + // position of first leading tab in the current line, + // used to make sure there are no tabs in the indentation + this.firstTabInLine = -1; - return tls.connect(port, host, options); - } + this.documents = []; - closeFreeSessions() { - for (const sessions of Object.values(this.sessions)) { - for (const session of sessions) { - if (session[kCurrentStreamsCount] === 0) { - session.close(); - } - } - } - } + /* + this.version; + this.checkLineBreaks; + this.tagMap; + this.anchorMap; + this.tag; + this.anchor; + this.kind; + this.result;*/ - destroy(reason) { - for (const sessions of Object.values(this.sessions)) { - for (const session of sessions) { - session.destroy(reason); - } - } +} - for (const entriesOfAuthority of Object.values(this.queue)) { - for (const entry of Object.values(entriesOfAuthority)) { - entry.destroyed = true; - } - } - // New requests should NOT attach to destroyed sessions - this.queue = {}; - } +function generateError(state, message) { + var mark = { + name: state.filename, + buffer: state.input.slice(0, -1), // omit trailing \0 + position: state.position, + line: state.line, + column: state.position - state.lineStart + }; - get freeSessions() { - return getSessions({agent: this, isFree: true}); - } + mark.snippet = makeSnippet(mark); - get busySessions() { - return getSessions({agent: this, isFree: false}); - } + return new YAMLException(message, mark); } -Agent.kCurrentStreamsCount = kCurrentStreamsCount; -Agent.kGracefullyClosing = kGracefullyClosing; +function throwError(state, message) { + throw generateError(state, message); +} -module.exports = { - Agent, - globalAgent: new Agent() -}; +function throwWarning(state, message) { + if (state.onWarning) { + state.onWarning.call(null, generateError(state, message)); + } +} -/***/ }), +var directiveHandlers = { -/***/ 97167: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + YAML: function handleYamlDirective(state, name, args) { -"use strict"; + var match, major, minor; -const http = __nccwpck_require__(13685); -const https = __nccwpck_require__(95687); -const resolveALPN = __nccwpck_require__(46624); -const QuickLRU = __nccwpck_require__(49273); -const Http2ClientRequest = __nccwpck_require__(59632); -const calculateServerName = __nccwpck_require__(51982); -const urlToOptions = __nccwpck_require__(92686); + if (state.version !== null) { + throwError(state, 'duplication of %YAML directive'); + } -const cache = new QuickLRU({maxSize: 100}); -const queue = new Map(); + if (args.length !== 1) { + throwError(state, 'YAML directive accepts exactly one argument'); + } -const installSocket = (agent, socket, options) => { - socket._httpMessage = {shouldKeepAlive: true}; + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); - const onFree = () => { - agent.emit('free', socket, options); - }; + if (match === null) { + throwError(state, 'ill-formed argument of the YAML directive'); + } - socket.on('free', onFree); + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); - const onClose = () => { - agent.removeSocket(socket, options); - }; + if (major !== 1) { + throwError(state, 'unacceptable YAML version of the document'); + } - socket.on('close', onClose); + state.version = args[0]; + state.checkLineBreaks = (minor < 2); - const onRemove = () => { - agent.removeSocket(socket, options); - socket.off('close', onClose); - socket.off('free', onFree); - socket.off('agentRemove', onRemove); - }; + if (minor !== 1 && minor !== 2) { + throwWarning(state, 'unsupported YAML version of the document'); + } + }, - socket.on('agentRemove', onRemove); + TAG: function handleTagDirective(state, name, args) { - agent.emit('free', socket, options); -}; + var handle, prefix; -const resolveProtocol = async options => { - const name = `${options.host}:${options.port}:${options.ALPNProtocols.sort()}`; + if (args.length !== 2) { + throwError(state, 'TAG directive accepts exactly two arguments'); + } - if (!cache.has(name)) { - if (queue.has(name)) { - const result = await queue.get(name); - return result.alpnProtocol; - } + handle = args[0]; + prefix = args[1]; - const {path, agent} = options; - options.path = options.socketPath; + if (!PATTERN_TAG_HANDLE.test(handle)) { + throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); + } - const resultPromise = resolveALPN(options); - queue.set(name, resultPromise); + if (_hasOwnProperty.call(state.tagMap, handle)) { + throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + } - try { - const {socket, alpnProtocol} = await resultPromise; - cache.set(name, alpnProtocol); + if (!PATTERN_TAG_URI.test(prefix)) { + throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + } - options.path = path; + try { + prefix = decodeURIComponent(prefix); + } catch (err) { + throwError(state, 'tag prefix is malformed: ' + prefix); + } - if (alpnProtocol === 'h2') { - // https://github.com/nodejs/node/issues/33343 - socket.destroy(); - } else { - const {globalAgent} = https; - const defaultCreateConnection = https.Agent.prototype.createConnection; + state.tagMap[handle] = prefix; + } +}; - if (agent) { - if (agent.createConnection === defaultCreateConnection) { - installSocket(agent, socket, options); - } else { - socket.destroy(); - } - } else if (globalAgent.createConnection === defaultCreateConnection) { - installSocket(globalAgent, socket, options); - } else { - socket.destroy(); - } - } - queue.delete(name); +function captureSegment(state, start, end, checkJson) { + var _position, _length, _character, _result; - return alpnProtocol; - } catch (error) { - queue.delete(name); + if (start < end) { + _result = state.input.slice(start, end); - throw error; - } - } + if (checkJson) { + for (_position = 0, _length = _result.length; _position < _length; _position += 1) { + _character = _result.charCodeAt(_position); + if (!(_character === 0x09 || + (0x20 <= _character && _character <= 0x10FFFF))) { + throwError(state, 'expected valid JSON character'); + } + } + } else if (PATTERN_NON_PRINTABLE.test(_result)) { + throwError(state, 'the stream contains non-printable characters'); + } - return cache.get(name); -}; + state.result += _result; + } +} -module.exports = async (input, options, callback) => { - if (typeof input === 'string' || input instanceof URL) { - input = urlToOptions(new URL(input)); - } +function mergeMappings(state, destination, source, overridableKeys) { + var sourceKeys, key, index, quantity; - if (typeof options === 'function') { - callback = options; - options = undefined; - } + if (!common.isObject(source)) { + throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); + } - options = { - ALPNProtocols: ['h2', 'http/1.1'], - ...input, - ...options, - resolveSocket: true - }; + sourceKeys = Object.keys(source); - if (!Array.isArray(options.ALPNProtocols) || options.ALPNProtocols.length === 0) { - throw new Error('The `ALPNProtocols` option must be an Array with at least one entry'); - } + for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { + key = sourceKeys[index]; - options.protocol = options.protocol || 'https:'; - const isHttps = options.protocol === 'https:'; + if (!_hasOwnProperty.call(destination, key)) { + setProperty(destination, key, source[key]); + overridableKeys[key] = true; + } + } +} - options.host = options.hostname || options.host || 'localhost'; - options.session = options.tlsSession; - options.servername = options.servername || calculateServerName(options); - options.port = options.port || (isHttps ? 443 : 80); - options._defaultAgent = isHttps ? https.globalAgent : http.globalAgent; +function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, + startLine, startLineStart, startPos) { - const agents = options.agent; + var index, quantity; - if (agents) { - if (agents.addRequest) { - throw new Error('The `options.agent` object can contain only `http`, `https` or `http2` properties'); - } + // The output is a plain object here, so keys can only be strings. + // We need to convert keyNode to a string, but doing so can hang the process + // (deeply nested arrays that explode exponentially using aliases). + if (Array.isArray(keyNode)) { + keyNode = Array.prototype.slice.call(keyNode); - options.agent = agents[isHttps ? 'https' : 'http']; - } + for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { + if (Array.isArray(keyNode[index])) { + throwError(state, 'nested arrays are not supported inside keys'); + } - if (isHttps) { - const protocol = await resolveProtocol(options); + if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { + keyNode[index] = '[object Object]'; + } + } + } - if (protocol === 'h2') { - if (agents) { - options.agent = agents.http2; - } + // Avoid code execution in load() via toString property + // (still use its own toString for arrays, timestamps, + // and whatever user schema extensions happen to have @@toStringTag) + if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { + keyNode = '[object Object]'; + } - return new Http2ClientRequest(options, callback); - } - } - return http.request(options, callback); -}; + keyNode = String(keyNode); -module.exports.protocolCache = cache; + if (_result === null) { + _result = {}; + } + if (keyTag === 'tag:yaml.org,2002:merge') { + if (Array.isArray(valueNode)) { + for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { + mergeMappings(state, _result, valueNode[index], overridableKeys); + } + } else { + mergeMappings(state, _result, valueNode, overridableKeys); + } + } else { + if (!state.json && + !_hasOwnProperty.call(overridableKeys, keyNode) && + _hasOwnProperty.call(_result, keyNode)) { + state.line = startLine || state.line; + state.lineStart = startLineStart || state.lineStart; + state.position = startPos || state.position; + throwError(state, 'duplicated mapping key'); + } -/***/ }), + setProperty(_result, keyNode, valueNode); + delete overridableKeys[keyNode]; + } -/***/ 59632: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return _result; +} -"use strict"; +function readLineBreak(state) { + var ch; -const http2 = __nccwpck_require__(85158); -const {Writable} = __nccwpck_require__(12781); -const {Agent, globalAgent} = __nccwpck_require__(79898); -const IncomingMessage = __nccwpck_require__(82575); -const urlToOptions = __nccwpck_require__(92686); -const proxyEvents = __nccwpck_require__(81818); -const isRequestPseudoHeader = __nccwpck_require__(11199); -const { - ERR_INVALID_ARG_TYPE, - ERR_INVALID_PROTOCOL, - ERR_HTTP_HEADERS_SENT, - ERR_INVALID_HTTP_TOKEN, - ERR_HTTP_INVALID_HEADER_VALUE, - ERR_INVALID_CHAR -} = __nccwpck_require__(7087); + ch = state.input.charCodeAt(state.position); -const { - HTTP2_HEADER_STATUS, - HTTP2_HEADER_METHOD, - HTTP2_HEADER_PATH, - HTTP2_METHOD_CONNECT -} = http2.constants; + if (ch === 0x0A/* LF */) { + state.position++; + } else if (ch === 0x0D/* CR */) { + state.position++; + if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { + state.position++; + } + } else { + throwError(state, 'a line break is expected'); + } -const kHeaders = Symbol('headers'); -const kOrigin = Symbol('origin'); -const kSession = Symbol('session'); -const kOptions = Symbol('options'); -const kFlushedHeaders = Symbol('flushedHeaders'); -const kJobs = Symbol('jobs'); + state.line += 1; + state.lineStart = state.position; + state.firstTabInLine = -1; +} -const isValidHttpToken = /^[\^`\-\w!#$%&*+.|~]+$/; -const isInvalidHeaderValue = /[^\t\u0020-\u007E\u0080-\u00FF]/; +function skipSeparationSpace(state, allowComments, checkIndent) { + var lineBreaks = 0, + ch = state.input.charCodeAt(state.position); -class ClientRequest extends Writable { - constructor(input, options, callback) { - super({ - autoDestroy: false - }); + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) { + state.firstTabInLine = state.position; + } + ch = state.input.charCodeAt(++state.position); + } - const hasInput = typeof input === 'string' || input instanceof URL; - if (hasInput) { - input = urlToOptions(input instanceof URL ? input : new URL(input)); - } + if (allowComments && ch === 0x23/* # */) { + do { + ch = state.input.charCodeAt(++state.position); + } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); + } - if (typeof options === 'function' || options === undefined) { - // (options, callback) - callback = options; - options = hasInput ? input : {...input}; - } else { - // (input, options, callback) - options = {...input, ...options}; - } + if (is_EOL(ch)) { + readLineBreak(state); - if (options.h2session) { - this[kSession] = options.h2session; - } else if (options.agent === false) { - this.agent = new Agent({maxFreeSessions: 0}); - } else if (typeof options.agent === 'undefined' || options.agent === null) { - if (typeof options.createConnection === 'function') { - // This is a workaround - we don't have to create the session on our own. - this.agent = new Agent({maxFreeSessions: 0}); - this.agent.createConnection = options.createConnection; - } else { - this.agent = globalAgent; - } - } else if (typeof options.agent.request === 'function') { - this.agent = options.agent; - } else { - throw new ERR_INVALID_ARG_TYPE('options.agent', ['Agent-like Object', 'undefined', 'false'], options.agent); - } + ch = state.input.charCodeAt(state.position); + lineBreaks++; + state.lineIndent = 0; - if (options.protocol && options.protocol !== 'https:') { - throw new ERR_INVALID_PROTOCOL(options.protocol, 'https:'); - } + while (ch === 0x20/* Space */) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + } else { + break; + } + } - const port = options.port || options.defaultPort || (this.agent && this.agent.defaultPort) || 443; - const host = options.hostname || options.host || 'localhost'; + if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { + throwWarning(state, 'deficient indentation'); + } - // Don't enforce the origin via options. It may be changed in an Agent. - delete options.hostname; - delete options.host; - delete options.port; + return lineBreaks; +} - const {timeout} = options; - options.timeout = undefined; +function testDocumentSeparator(state) { + var _position = state.position, + ch; - this[kHeaders] = Object.create(null); - this[kJobs] = []; + ch = state.input.charCodeAt(_position); - this.socket = null; - this.connection = null; + // Condition state.position === state.lineStart is tested + // in parent on each call, for efficiency. No needs to test here again. + if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && + ch === state.input.charCodeAt(_position + 1) && + ch === state.input.charCodeAt(_position + 2)) { - this.method = options.method || 'GET'; - this.path = options.path; + _position += 3; - this.res = null; - this.aborted = false; - this.reusedSocket = false; + ch = state.input.charCodeAt(_position); - if (options.headers) { - for (const [header, value] of Object.entries(options.headers)) { - this.setHeader(header, value); - } - } + if (ch === 0 || is_WS_OR_EOL(ch)) { + return true; + } + } - if (options.auth && !('authorization' in this[kHeaders])) { - this[kHeaders].authorization = 'Basic ' + Buffer.from(options.auth).toString('base64'); - } + return false; +} - options.session = options.tlsSession; - options.path = options.socketPath; +function writeFoldedLines(state, count) { + if (count === 1) { + state.result += ' '; + } else if (count > 1) { + state.result += common.repeat('\n', count - 1); + } +} - this[kOptions] = options; - // Clients that generate HTTP/2 requests directly SHOULD use the :authority pseudo-header field instead of the Host header field. - if (port === 443) { - this[kOrigin] = `https://${host}`; +function readPlainScalar(state, nodeIndent, withinFlowCollection) { + var preceding, + following, + captureStart, + captureEnd, + hasPendingContent, + _line, + _lineStart, + _lineIndent, + _kind = state.kind, + _result = state.result, + ch; - if (!(':authority' in this[kHeaders])) { - this[kHeaders][':authority'] = host; - } - } else { - this[kOrigin] = `https://${host}:${port}`; + ch = state.input.charCodeAt(state.position); - if (!(':authority' in this[kHeaders])) { - this[kHeaders][':authority'] = `${host}:${port}`; - } - } + if (is_WS_OR_EOL(ch) || + is_FLOW_INDICATOR(ch) || + ch === 0x23/* # */ || + ch === 0x26/* & */ || + ch === 0x2A/* * */ || + ch === 0x21/* ! */ || + ch === 0x7C/* | */ || + ch === 0x3E/* > */ || + ch === 0x27/* ' */ || + ch === 0x22/* " */ || + ch === 0x25/* % */ || + ch === 0x40/* @ */ || + ch === 0x60/* ` */) { + return false; + } - if (timeout) { - this.setTimeout(timeout); - } + if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { + following = state.input.charCodeAt(state.position + 1); - if (callback) { - this.once('response', callback); - } + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + return false; + } + } - this[kFlushedHeaders] = false; - } + state.kind = 'scalar'; + state.result = ''; + captureStart = captureEnd = state.position; + hasPendingContent = false; - get method() { - return this[kHeaders][HTTP2_HEADER_METHOD]; - } + while (ch !== 0) { + if (ch === 0x3A/* : */) { + following = state.input.charCodeAt(state.position + 1); - set method(value) { - if (value) { - this[kHeaders][HTTP2_HEADER_METHOD] = value.toUpperCase(); - } - } + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + break; + } - get path() { - return this[kHeaders][HTTP2_HEADER_PATH]; - } + } else if (ch === 0x23/* # */) { + preceding = state.input.charCodeAt(state.position - 1); - set path(value) { - if (value) { - this[kHeaders][HTTP2_HEADER_PATH] = value; - } - } + if (is_WS_OR_EOL(preceding)) { + break; + } - get _mustNotHaveABody() { - return this.method === 'GET' || this.method === 'HEAD' || this.method === 'DELETE'; - } + } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || + withinFlowCollection && is_FLOW_INDICATOR(ch)) { + break; - _write(chunk, encoding, callback) { - // https://github.com/nodejs/node/blob/654df09ae0c5e17d1b52a900a545f0664d8c7627/lib/internal/http2/util.js#L148-L156 - if (this._mustNotHaveABody) { - callback(new Error('The GET, HEAD and DELETE methods must NOT have a body')); - /* istanbul ignore next: Node.js 12 throws directly */ - return; - } + } else if (is_EOL(ch)) { + _line = state.line; + _lineStart = state.lineStart; + _lineIndent = state.lineIndent; + skipSeparationSpace(state, false, -1); - this.flushHeaders(); + if (state.lineIndent >= nodeIndent) { + hasPendingContent = true; + ch = state.input.charCodeAt(state.position); + continue; + } else { + state.position = captureEnd; + state.line = _line; + state.lineStart = _lineStart; + state.lineIndent = _lineIndent; + break; + } + } - const callWrite = () => this._request.write(chunk, encoding, callback); - if (this._request) { - callWrite(); - } else { - this[kJobs].push(callWrite); - } - } + if (hasPendingContent) { + captureSegment(state, captureStart, captureEnd, false); + writeFoldedLines(state, state.line - _line); + captureStart = captureEnd = state.position; + hasPendingContent = false; + } - _final(callback) { - if (this.destroyed) { - return; - } + if (!is_WHITE_SPACE(ch)) { + captureEnd = state.position + 1; + } - this.flushHeaders(); + ch = state.input.charCodeAt(++state.position); + } - const callEnd = () => { - // For GET, HEAD and DELETE - if (this._mustNotHaveABody) { - callback(); - return; - } + captureSegment(state, captureStart, captureEnd, false); - this._request.end(callback); - }; + if (state.result) { + return true; + } - if (this._request) { - callEnd(); - } else { - this[kJobs].push(callEnd); - } - } + state.kind = _kind; + state.result = _result; + return false; +} - abort() { - if (this.res && this.res.complete) { - return; - } +function readSingleQuotedScalar(state, nodeIndent) { + var ch, + captureStart, captureEnd; - if (!this.aborted) { - process.nextTick(() => this.emit('abort')); - } + ch = state.input.charCodeAt(state.position); - this.aborted = true; + if (ch !== 0x27/* ' */) { + return false; + } - this.destroy(); - } + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; - _destroy(error, callback) { - if (this.res) { - this.res._dump(); - } + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x27/* ' */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); - if (this._request) { - this._request.destroy(); - } + if (ch === 0x27/* ' */) { + captureStart = state.position; + state.position++; + captureEnd = state.position; + } else { + return true; + } - callback(error); - } + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; - async flushHeaders() { - if (this[kFlushedHeaders] || this.destroyed) { - return; - } + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a single quoted scalar'); - this[kFlushedHeaders] = true; + } else { + state.position++; + captureEnd = state.position; + } + } - const isConnectMethod = this.method === HTTP2_METHOD_CONNECT; + throwError(state, 'unexpected end of the stream within a single quoted scalar'); +} - // The real magic is here - const onStream = stream => { - this._request = stream; +function readDoubleQuotedScalar(state, nodeIndent) { + var captureStart, + captureEnd, + hexLength, + hexResult, + tmp, + ch; - if (this.destroyed) { - stream.destroy(); - return; - } + ch = state.input.charCodeAt(state.position); - // Forwards `timeout`, `continue`, `close` and `error` events to this instance. - if (!isConnectMethod) { - proxyEvents(stream, this, ['timeout', 'continue', 'close', 'error']); - } + if (ch !== 0x22/* " */) { + return false; + } - // Wait for the `finish` event. We don't want to emit the `response` event - // before `request.end()` is called. - const waitForEnd = fn => { - return (...args) => { - if (!this.writable && !this.destroyed) { - fn(...args); - } else { - this.once('finish', () => { - fn(...args); - }); - } - }; - }; + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; - // This event tells we are ready to listen for the data. - stream.once('response', waitForEnd((headers, flags, rawHeaders) => { - // If we were to emit raw request stream, it would be as fast as the native approach. - // Note that wrapping the raw stream in a Proxy instance won't improve the performance (already tested it). - const response = new IncomingMessage(this.socket, stream.readableHighWaterMark); - this.res = response; + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x22/* " */) { + captureSegment(state, captureStart, state.position, true); + state.position++; + return true; - response.req = this; - response.statusCode = headers[HTTP2_HEADER_STATUS]; - response.headers = headers; - response.rawHeaders = rawHeaders; + } else if (ch === 0x5C/* \ */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); - response.once('end', () => { - if (this.aborted) { - response.aborted = true; - response.emit('aborted'); - } else { - response.complete = true; + if (is_EOL(ch)) { + skipSeparationSpace(state, false, nodeIndent); - // Has no effect, just be consistent with the Node.js behavior - response.socket = null; - response.connection = null; - } - }); + // TODO: rework to inline fn with no type cast? + } else if (ch < 256 && simpleEscapeCheck[ch]) { + state.result += simpleEscapeMap[ch]; + state.position++; - if (isConnectMethod) { - response.upgrade = true; + } else if ((tmp = escapedHexLen(ch)) > 0) { + hexLength = tmp; + hexResult = 0; - // The HTTP1 API says the socket is detached here, - // but we can't do that so we pass the original HTTP2 request. - if (this.emit('connect', response, stream, Buffer.alloc(0))) { - this.emit('close'); - } else { - // No listeners attached, destroy the original request. - stream.destroy(); - } - } else { - // Forwards data - stream.on('data', chunk => { - if (!response._dumped && !response.push(chunk)) { - stream.pause(); - } - }); + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position); - stream.once('end', () => { - response.push(null); - }); + if ((tmp = fromHexCode(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp; - if (!this.emit('response', response)) { - // No listeners attached, dump the response. - response._dump(); - } - } - })); + } else { + throwError(state, 'expected hexadecimal character'); + } + } - // Emits `information` event - stream.once('headers', waitForEnd( - headers => this.emit('information', {statusCode: headers[HTTP2_HEADER_STATUS]}) - )); + state.result += charFromCodepoint(hexResult); - stream.once('trailers', waitForEnd((trailers, flags, rawTrailers) => { - const {res} = this; + state.position++; - // Assigns trailers to the response object. - res.trailers = trailers; - res.rawTrailers = rawTrailers; - })); + } else { + throwError(state, 'unknown escape sequence'); + } - const {socket} = stream.session; - this.socket = socket; - this.connection = socket; + captureStart = captureEnd = state.position; - for (const job of this[kJobs]) { - job(); - } + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; - this.emit('socket', this.socket); - }; + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a double quoted scalar'); - // Makes a HTTP2 request - if (this[kSession]) { - try { - onStream(this[kSession].request(this[kHeaders])); - } catch (error) { - this.emit('error', error); - } - } else { - this.reusedSocket = true; + } else { + state.position++; + captureEnd = state.position; + } + } - try { - onStream(await this.agent.request(this[kOrigin], this[kOptions], this[kHeaders])); - } catch (error) { - this.emit('error', error); - } - } - } + throwError(state, 'unexpected end of the stream within a double quoted scalar'); +} - getHeader(name) { - if (typeof name !== 'string') { - throw new ERR_INVALID_ARG_TYPE('name', 'string', name); - } +function readFlowCollection(state, nodeIndent) { + var readNext = true, + _line, + _lineStart, + _pos, + _tag = state.tag, + _result, + _anchor = state.anchor, + following, + terminator, + isPair, + isExplicitPair, + isMapping, + overridableKeys = Object.create(null), + keyNode, + keyTag, + valueNode, + ch; - return this[kHeaders][name.toLowerCase()]; - } + ch = state.input.charCodeAt(state.position); - get headersSent() { - return this[kFlushedHeaders]; - } + if (ch === 0x5B/* [ */) { + terminator = 0x5D;/* ] */ + isMapping = false; + _result = []; + } else if (ch === 0x7B/* { */) { + terminator = 0x7D;/* } */ + isMapping = true; + _result = {}; + } else { + return false; + } - removeHeader(name) { - if (typeof name !== 'string') { - throw new ERR_INVALID_ARG_TYPE('name', 'string', name); - } + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } - if (this.headersSent) { - throw new ERR_HTTP_HEADERS_SENT('remove'); - } + ch = state.input.charCodeAt(++state.position); - delete this[kHeaders][name.toLowerCase()]; - } + while (ch !== 0) { + skipSeparationSpace(state, true, nodeIndent); - setHeader(name, value) { - if (this.headersSent) { - throw new ERR_HTTP_HEADERS_SENT('set'); - } + ch = state.input.charCodeAt(state.position); - if (typeof name !== 'string' || (!isValidHttpToken.test(name) && !isRequestPseudoHeader(name))) { - throw new ERR_INVALID_HTTP_TOKEN('Header name', name); - } + if (ch === terminator) { + state.position++; + state.tag = _tag; + state.anchor = _anchor; + state.kind = isMapping ? 'mapping' : 'sequence'; + state.result = _result; + return true; + } else if (!readNext) { + throwError(state, 'missed comma between flow collection entries'); + } else if (ch === 0x2C/* , */) { + // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4 + throwError(state, "expected the node content, but found ','"); + } - if (typeof value === 'undefined') { - throw new ERR_HTTP_INVALID_HEADER_VALUE(value, name); - } + keyTag = keyNode = valueNode = null; + isPair = isExplicitPair = false; - if (isInvalidHeaderValue.test(value)) { - throw new ERR_INVALID_CHAR('header content', name); - } + if (ch === 0x3F/* ? */) { + following = state.input.charCodeAt(state.position + 1); - this[kHeaders][name.toLowerCase()] = value; - } + if (is_WS_OR_EOL(following)) { + isPair = isExplicitPair = true; + state.position++; + skipSeparationSpace(state, true, nodeIndent); + } + } - setNoDelay() { - // HTTP2 sockets cannot be malformed, do nothing. - } + _line = state.line; // Save the current line. + _lineStart = state.lineStart; + _pos = state.position; + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + keyTag = state.tag; + keyNode = state.result; + skipSeparationSpace(state, true, nodeIndent); - setSocketKeepAlive() { - // HTTP2 sockets cannot be malformed, do nothing. - } + ch = state.input.charCodeAt(state.position); - setTimeout(ms, callback) { - const applyTimeout = () => this._request.setTimeout(ms, callback); + if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { + isPair = true; + ch = state.input.charCodeAt(++state.position); + skipSeparationSpace(state, true, nodeIndent); + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + valueNode = state.result; + } - if (this._request) { - applyTimeout(); - } else { - this[kJobs].push(applyTimeout); - } + if (isMapping) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); + } else if (isPair) { + _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); + } else { + _result.push(keyNode); + } - return this; - } + skipSeparationSpace(state, true, nodeIndent); - get maxHeadersCount() { - if (!this.destroyed && this._request) { - return this._request.session.localSettings.maxHeaderListSize; - } + ch = state.input.charCodeAt(state.position); - return undefined; - } + if (ch === 0x2C/* , */) { + readNext = true; + ch = state.input.charCodeAt(++state.position); + } else { + readNext = false; + } + } - set maxHeadersCount(_value) { - // Updating HTTP2 settings would affect all requests, do nothing. - } + throwError(state, 'unexpected end of the stream within a flow collection'); } -module.exports = ClientRequest; +function readBlockScalar(state, nodeIndent) { + var captureStart, + folding, + chomping = CHOMPING_CLIP, + didReadContent = false, + detectedIndent = false, + textIndent = nodeIndent, + emptyLines = 0, + atMoreIndented = false, + tmp, + ch; + ch = state.input.charCodeAt(state.position); -/***/ }), + if (ch === 0x7C/* | */) { + folding = false; + } else if (ch === 0x3E/* > */) { + folding = true; + } else { + return false; + } -/***/ 82575: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + state.kind = 'scalar'; + state.result = ''; -"use strict"; + while (ch !== 0) { + ch = state.input.charCodeAt(++state.position); -const {Readable} = __nccwpck_require__(12781); + if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { + if (CHOMPING_CLIP === chomping) { + chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; + } else { + throwError(state, 'repeat of a chomping mode identifier'); + } -class IncomingMessage extends Readable { - constructor(socket, highWaterMark) { - super({ - highWaterMark, - autoDestroy: false - }); + } else if ((tmp = fromDecimalCode(ch)) >= 0) { + if (tmp === 0) { + throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); + } else if (!detectedIndent) { + textIndent = nodeIndent + tmp - 1; + detectedIndent = true; + } else { + throwError(state, 'repeat of an indentation width identifier'); + } - this.statusCode = null; - this.statusMessage = ''; - this.httpVersion = '2.0'; - this.httpVersionMajor = 2; - this.httpVersionMinor = 0; - this.headers = {}; - this.trailers = {}; - this.req = null; + } else { + break; + } + } - this.aborted = false; - this.complete = false; - this.upgrade = null; + if (is_WHITE_SPACE(ch)) { + do { ch = state.input.charCodeAt(++state.position); } + while (is_WHITE_SPACE(ch)); - this.rawHeaders = []; - this.rawTrailers = []; + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (!is_EOL(ch) && (ch !== 0)); + } + } - this.socket = socket; - this.connection = socket; + while (ch !== 0) { + readLineBreak(state); + state.lineIndent = 0; - this._dumped = false; - } + ch = state.input.charCodeAt(state.position); - _destroy(error) { - this.req._request.destroy(error); - } + while ((!detectedIndent || state.lineIndent < textIndent) && + (ch === 0x20/* Space */)) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } - setTimeout(ms, callback) { - this.req.setTimeout(ms, callback); - return this; - } + if (!detectedIndent && state.lineIndent > textIndent) { + textIndent = state.lineIndent; + } - _dump() { - if (!this._dumped) { - this._dumped = true; + if (is_EOL(ch)) { + emptyLines++; + continue; + } - this.removeAllListeners('data'); - this.resume(); - } - } + // End of the scalar. + if (state.lineIndent < textIndent) { - _read() { - if (this.req) { - this.req._request.resume(); - } - } -} + // Perform the chomping. + if (chomping === CHOMPING_KEEP) { + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } else if (chomping === CHOMPING_CLIP) { + if (didReadContent) { // i.e. only if the scalar is not empty. + state.result += '\n'; + } + } -module.exports = IncomingMessage; + // Break this `while` cycle and go to the funciton's epilogue. + break; + } + // Folded style: use fancy rules to handle line breaks. + if (folding) { -/***/ }), + // Lines starting with white space characters (more-indented lines) are not folded. + if (is_WHITE_SPACE(ch)) { + atMoreIndented = true; + // except for the first content line (cf. Example 8.1) + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); -/***/ 54645: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // End of more-indented block. + } else if (atMoreIndented) { + atMoreIndented = false; + state.result += common.repeat('\n', emptyLines + 1); -"use strict"; + // Just one line break - perceive as the same line. + } else if (emptyLines === 0) { + if (didReadContent) { // i.e. only if we have already read some scalar content. + state.result += ' '; + } -const http2 = __nccwpck_require__(85158); -const agent = __nccwpck_require__(79898); -const ClientRequest = __nccwpck_require__(59632); -const IncomingMessage = __nccwpck_require__(82575); -const auto = __nccwpck_require__(97167); + // Several line breaks - perceive as different lines. + } else { + state.result += common.repeat('\n', emptyLines); + } -const request = (url, options, callback) => { - return new ClientRequest(url, options, callback); -}; + // Literal style: just add exact number of line breaks between content lines. + } else { + // Keep all line breaks except the header line break. + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } -const get = (url, options, callback) => { - // eslint-disable-next-line unicorn/prevent-abbreviations - const req = new ClientRequest(url, options, callback); - req.end(); + didReadContent = true; + detectedIndent = true; + emptyLines = 0; + captureStart = state.position; - return req; -}; + while (!is_EOL(ch) && (ch !== 0)) { + ch = state.input.charCodeAt(++state.position); + } -module.exports = { - ...http2, - ClientRequest, - IncomingMessage, - ...agent, - request, - get, - auto -}; + captureSegment(state, captureStart, state.position, false); + } + return true; +} -/***/ }), +function readBlockSequence(state, nodeIndent) { + var _line, + _tag = state.tag, + _anchor = state.anchor, + _result = [], + following, + detected = false, + ch; -/***/ 51982: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // there is a leading tab before this token, so it can't be a block sequence/mapping; + // it can still be flow sequence/mapping or a scalar + if (state.firstTabInLine !== -1) return false; -"use strict"; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } -const net = __nccwpck_require__(41808); -/* istanbul ignore file: https://github.com/nodejs/node/blob/v13.0.1/lib/_http_agent.js */ + ch = state.input.charCodeAt(state.position); -module.exports = options => { - let servername = options.host; - const hostHeader = options.headers && options.headers.host; + while (ch !== 0) { + if (state.firstTabInLine !== -1) { + state.position = state.firstTabInLine; + throwError(state, 'tab characters must not be used in indentation'); + } - if (hostHeader) { - if (hostHeader.startsWith('[')) { - const index = hostHeader.indexOf(']'); - if (index === -1) { - servername = hostHeader; - } else { - servername = hostHeader.slice(1, -1); - } - } else { - servername = hostHeader.split(':', 1)[0]; - } - } + if (ch !== 0x2D/* - */) { + break; + } - if (net.isIP(servername)) { - return ''; - } + following = state.input.charCodeAt(state.position + 1); - return servername; -}; + if (!is_WS_OR_EOL(following)) { + break; + } + detected = true; + state.position++; -/***/ }), + if (skipSeparationSpace(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null); + ch = state.input.charCodeAt(state.position); + continue; + } + } -/***/ 7087: -/***/ ((module) => { + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); + _result.push(state.result); + skipSeparationSpace(state, true, -1); -"use strict"; + ch = state.input.charCodeAt(state.position); -/* istanbul ignore file: https://github.com/nodejs/node/blob/master/lib/internal/errors.js */ + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a sequence entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } -const makeError = (Base, key, getMessage) => { - module.exports[key] = class NodeError extends Base { - constructor(...args) { - super(typeof getMessage === 'string' ? getMessage : getMessage(args)); - this.name = `${super.name} [${key}]`; - this.code = key; - } - }; -}; + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'sequence'; + state.result = _result; + return true; + } + return false; +} -makeError(TypeError, 'ERR_INVALID_ARG_TYPE', args => { - const type = args[0].includes('.') ? 'property' : 'argument'; +function readBlockMapping(state, nodeIndent, flowIndent) { + var following, + allowCompact, + _line, + _keyLine, + _keyLineStart, + _keyPos, + _tag = state.tag, + _anchor = state.anchor, + _result = {}, + overridableKeys = Object.create(null), + keyTag = null, + keyNode = null, + valueNode = null, + atExplicitKey = false, + detected = false, + ch; - let valid = args[1]; - const isManyTypes = Array.isArray(valid); + // there is a leading tab before this token, so it can't be a block sequence/mapping; + // it can still be flow sequence/mapping or a scalar + if (state.firstTabInLine !== -1) return false; - if (isManyTypes) { - valid = `${valid.slice(0, -1).join(', ')} or ${valid.slice(-1)}`; - } + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } - return `The "${args[0]}" ${type} must be ${isManyTypes ? 'one of' : 'of'} type ${valid}. Received ${typeof args[2]}`; -}); + ch = state.input.charCodeAt(state.position); -makeError(TypeError, 'ERR_INVALID_PROTOCOL', args => { - return `Protocol "${args[0]}" not supported. Expected "${args[1]}"`; -}); + while (ch !== 0) { + if (!atExplicitKey && state.firstTabInLine !== -1) { + state.position = state.firstTabInLine; + throwError(state, 'tab characters must not be used in indentation'); + } -makeError(Error, 'ERR_HTTP_HEADERS_SENT', args => { - return `Cannot ${args[0]} headers after they are sent to the client`; -}); + following = state.input.charCodeAt(state.position + 1); + _line = state.line; // Save the current line. -makeError(TypeError, 'ERR_INVALID_HTTP_TOKEN', args => { - return `${args[0]} must be a valid HTTP token [${args[1]}]`; -}); + // + // Explicit notation case. There are two separate blocks: + // first for the key (denoted by "?") and second for the value (denoted by ":") + // + if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { -makeError(TypeError, 'ERR_HTTP_INVALID_HEADER_VALUE', args => { - return `Invalid value "${args[0]} for header "${args[1]}"`; -}); + if (ch === 0x3F/* ? */) { + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } -makeError(TypeError, 'ERR_INVALID_CHAR', args => { - return `Invalid character in ${args[0]} [${args[1]}]`; -}); + detected = true; + atExplicitKey = true; + allowCompact = true; + } else if (atExplicitKey) { + // i.e. 0x3A/* : */ === character after the explicit key. + atExplicitKey = false; + allowCompact = true; -/***/ }), + } else { + throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); + } -/***/ 11199: -/***/ ((module) => { + state.position += 1; + ch = following; -"use strict"; + // + // Implicit notation case. Flow-style node as the key first, then ":", and the value. + // + } else { + _keyLine = state.line; + _keyLineStart = state.lineStart; + _keyPos = state.position; + if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { + // Neither implicit nor explicit notation. + // Reading is done. Go to the epilogue. + break; + } -module.exports = header => { - switch (header) { - case ':method': - case ':scheme': - case ':authority': - case ':path': - return true; - default: - return false; - } -}; + if (state.line === _line) { + ch = state.input.charCodeAt(state.position); + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } -/***/ }), + if (ch === 0x3A/* : */) { + ch = state.input.charCodeAt(++state.position); -/***/ 81818: -/***/ ((module) => { + if (!is_WS_OR_EOL(ch)) { + throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); + } -"use strict"; + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } + detected = true; + atExplicitKey = false; + allowCompact = false; + keyTag = state.tag; + keyNode = state.result; -module.exports = (from, to, events) => { - for (const event of events) { - from.on(event, (...args) => to.emit(event, ...args)); - } -}; + } else if (detected) { + throwError(state, 'can not read an implicit mapping pair; a colon is missed'); + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } -/***/ }), + } else if (detected) { + throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); -/***/ 92686: -/***/ ((module) => { + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + } -"use strict"; + // + // Common reading code for both explicit and implicit notations. + // + if (state.line === _line || state.lineIndent > nodeIndent) { + if (atExplicitKey) { + _keyLine = state.line; + _keyLineStart = state.lineStart; + _keyPos = state.position; + } -/* istanbul ignore file: https://github.com/nodejs/node/blob/a91293d4d9ab403046ab5eb022332e4e3d249bd3/lib/internal/url.js#L1257 */ + if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { + if (atExplicitKey) { + keyNode = state.result; + } else { + valueNode = state.result; + } + } -module.exports = url => { - const options = { - protocol: url.protocol, - hostname: typeof url.hostname === 'string' && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname, - host: url.host, - hash: url.hash, - search: url.search, - pathname: url.pathname, - href: url.href, - path: `${url.pathname || ''}${url.search || ''}` - }; + if (!atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } - if (typeof url.port === 'string' && url.port.length !== 0) { - options.port = Number(url.port); - } + skipSeparationSpace(state, true, -1); + ch = state.input.charCodeAt(state.position); + } - if (url.username || url.password) { - options.auth = `${url.username || ''}:${url.password || ''}`; - } + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a mapping entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } - return options; -}; + // + // Epilogue. + // + // Special case: last mapping's node contains only the key in explicit notation. + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + } -/***/ }), + // Expose the resulting mapping. + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'mapping'; + state.result = _result; + } -/***/ 28213: -/***/ ((__unused_webpack_module, exports) => { + return detected; +} -"use strict"; -Object.defineProperty(exports, "__esModule", ({value:true}));exports.SIGNALS=void 0; +function readTagProperty(state) { + var _position, + isVerbatim = false, + isNamed = false, + tagHandle, + tagName, + ch; -const SIGNALS=[ -{ -name:"SIGHUP", -number:1, -action:"terminate", -description:"Terminal closed", -standard:"posix"}, + ch = state.input.charCodeAt(state.position); -{ -name:"SIGINT", -number:2, -action:"terminate", -description:"User interruption with CTRL-C", -standard:"ansi"}, + if (ch !== 0x21/* ! */) return false; -{ -name:"SIGQUIT", -number:3, -action:"core", -description:"User interruption with CTRL-\\", -standard:"posix"}, + if (state.tag !== null) { + throwError(state, 'duplication of a tag property'); + } -{ -name:"SIGILL", -number:4, -action:"core", -description:"Invalid machine instruction", -standard:"ansi"}, + ch = state.input.charCodeAt(++state.position); -{ -name:"SIGTRAP", -number:5, -action:"core", -description:"Debugger breakpoint", -standard:"posix"}, + if (ch === 0x3C/* < */) { + isVerbatim = true; + ch = state.input.charCodeAt(++state.position); -{ -name:"SIGABRT", -number:6, -action:"core", -description:"Aborted", -standard:"ansi"}, + } else if (ch === 0x21/* ! */) { + isNamed = true; + tagHandle = '!!'; + ch = state.input.charCodeAt(++state.position); -{ -name:"SIGIOT", -number:6, -action:"core", -description:"Aborted", -standard:"bsd"}, + } else { + tagHandle = '!'; + } -{ -name:"SIGBUS", -number:7, -action:"core", -description: -"Bus error due to misaligned, non-existing address or paging error", -standard:"bsd"}, + _position = state.position; -{ -name:"SIGEMT", -number:7, -action:"terminate", -description:"Command should be emulated but is not implemented", -standard:"other"}, + if (isVerbatim) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && ch !== 0x3E/* > */); -{ -name:"SIGFPE", -number:8, -action:"core", -description:"Floating point arithmetic error", -standard:"ansi"}, + if (state.position < state.length) { + tagName = state.input.slice(_position, state.position); + ch = state.input.charCodeAt(++state.position); + } else { + throwError(state, 'unexpected end of the stream within a verbatim tag'); + } + } else { + while (ch !== 0 && !is_WS_OR_EOL(ch)) { -{ -name:"SIGKILL", -number:9, -action:"terminate", -description:"Forced termination", -standard:"posix", -forced:true}, + if (ch === 0x21/* ! */) { + if (!isNamed) { + tagHandle = state.input.slice(_position - 1, state.position + 1); -{ -name:"SIGUSR1", -number:10, -action:"terminate", -description:"Application-specific signal", -standard:"posix"}, + if (!PATTERN_TAG_HANDLE.test(tagHandle)) { + throwError(state, 'named tag handle cannot contain such characters'); + } -{ -name:"SIGSEGV", -number:11, -action:"core", -description:"Segmentation fault", -standard:"ansi"}, + isNamed = true; + _position = state.position + 1; + } else { + throwError(state, 'tag suffix cannot contain exclamation marks'); + } + } -{ -name:"SIGUSR2", -number:12, -action:"terminate", -description:"Application-specific signal", -standard:"posix"}, + ch = state.input.charCodeAt(++state.position); + } -{ -name:"SIGPIPE", -number:13, -action:"terminate", -description:"Broken pipe or socket", -standard:"posix"}, + tagName = state.input.slice(_position, state.position); -{ -name:"SIGALRM", -number:14, -action:"terminate", -description:"Timeout or timer", -standard:"posix"}, + if (PATTERN_FLOW_INDICATORS.test(tagName)) { + throwError(state, 'tag suffix cannot contain flow indicator characters'); + } + } -{ -name:"SIGTERM", -number:15, -action:"terminate", -description:"Termination", -standard:"ansi"}, + if (tagName && !PATTERN_TAG_URI.test(tagName)) { + throwError(state, 'tag name cannot contain such characters: ' + tagName); + } -{ -name:"SIGSTKFLT", -number:16, -action:"terminate", -description:"Stack is empty or overflowed", -standard:"other"}, + try { + tagName = decodeURIComponent(tagName); + } catch (err) { + throwError(state, 'tag name is malformed: ' + tagName); + } -{ -name:"SIGCHLD", -number:17, -action:"ignore", -description:"Child process terminated, paused or unpaused", -standard:"posix"}, + if (isVerbatim) { + state.tag = tagName; -{ -name:"SIGCLD", -number:17, -action:"ignore", -description:"Child process terminated, paused or unpaused", -standard:"other"}, + } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { + state.tag = state.tagMap[tagHandle] + tagName; -{ -name:"SIGCONT", -number:18, -action:"unpause", -description:"Unpaused", -standard:"posix", -forced:true}, + } else if (tagHandle === '!') { + state.tag = '!' + tagName; -{ -name:"SIGSTOP", -number:19, -action:"pause", -description:"Paused", -standard:"posix", -forced:true}, + } else if (tagHandle === '!!') { + state.tag = 'tag:yaml.org,2002:' + tagName; -{ -name:"SIGTSTP", -number:20, -action:"pause", -description:"Paused using CTRL-Z or \"suspend\"", -standard:"posix"}, + } else { + throwError(state, 'undeclared tag handle "' + tagHandle + '"'); + } -{ -name:"SIGTTIN", -number:21, -action:"pause", -description:"Background process cannot read terminal input", -standard:"posix"}, + return true; +} -{ -name:"SIGBREAK", -number:21, -action:"terminate", -description:"User interruption with CTRL-BREAK", -standard:"other"}, +function readAnchorProperty(state) { + var _position, + ch; -{ -name:"SIGTTOU", -number:22, -action:"pause", -description:"Background process cannot write to terminal output", -standard:"posix"}, + ch = state.input.charCodeAt(state.position); -{ -name:"SIGURG", -number:23, -action:"ignore", -description:"Socket received out-of-band data", -standard:"bsd"}, + if (ch !== 0x26/* & */) return false; -{ -name:"SIGXCPU", -number:24, -action:"core", -description:"Process timed out", -standard:"bsd"}, + if (state.anchor !== null) { + throwError(state, 'duplication of an anchor property'); + } -{ -name:"SIGXFSZ", -number:25, -action:"core", -description:"File too big", -standard:"bsd"}, + ch = state.input.charCodeAt(++state.position); + _position = state.position; -{ -name:"SIGVTALRM", -number:26, -action:"terminate", -description:"Timeout or timer", -standard:"bsd"}, + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } -{ -name:"SIGPROF", -number:27, -action:"terminate", -description:"Timeout or timer", -standard:"bsd"}, + if (state.position === _position) { + throwError(state, 'name of an anchor node must contain at least one character'); + } -{ -name:"SIGWINCH", -number:28, -action:"ignore", -description:"Terminal window size changed", -standard:"bsd"}, + state.anchor = state.input.slice(_position, state.position); + return true; +} -{ -name:"SIGIO", -number:29, -action:"terminate", -description:"I/O is available", -standard:"other"}, +function readAlias(state) { + var _position, alias, + ch; -{ -name:"SIGPOLL", -number:29, -action:"terminate", -description:"Watched event", -standard:"other"}, + ch = state.input.charCodeAt(state.position); -{ -name:"SIGINFO", -number:29, -action:"ignore", -description:"Request for process information", -standard:"other"}, + if (ch !== 0x2A/* * */) return false; -{ -name:"SIGPWR", -number:30, -action:"terminate", -description:"Device running out of power", -standard:"systemv"}, + ch = state.input.charCodeAt(++state.position); + _position = state.position; -{ -name:"SIGSYS", -number:31, -action:"core", -description:"Invalid system call", -standard:"other"}, + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } -{ -name:"SIGUNUSED", -number:31, -action:"terminate", -description:"Invalid system call", -standard:"other"}];exports.SIGNALS=SIGNALS; -//# sourceMappingURL=core.js.map + if (state.position === _position) { + throwError(state, 'name of an alias node must contain at least one character'); + } -/***/ }), + alias = state.input.slice(_position, state.position); -/***/ 2779: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (!_hasOwnProperty.call(state.anchorMap, alias)) { + throwError(state, 'unidentified alias "' + alias + '"'); + } -"use strict"; -Object.defineProperty(exports, "__esModule", ({value:true}));exports.signalsByNumber=exports.signalsByName=void 0;var _os=__nccwpck_require__(22037); + state.result = state.anchorMap[alias]; + skipSeparationSpace(state, true, -1); + return true; +} -var _signals=__nccwpck_require__(86435); -var _realtime=__nccwpck_require__(25295); +function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { + var allowBlockStyles, + allowBlockScalars, + allowBlockCollections, + indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } + } -const signalsByName=getSignalsByName();exports.signalsByName=signalsByName; + if (indentStatus === 1) { + while (readTagProperty(state) || readAnchorProperty(state)) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + allowBlockCollections = allowBlockStyles; + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } else { + allowBlockCollections = false; + } + } + } + if (allowBlockCollections) { + allowBlockCollections = atNewLine || allowCompact; + } + if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { + if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { + flowIndent = parentIndent; + } else { + flowIndent = parentIndent + 1; + } -const getSignalsByNumber=function(){ -const signals=(0,_signals.getSignals)(); -const length=_realtime.SIGRTMAX+1; -const signalsA=Array.from({length},(value,number)=> -getSignalByNumber(number,signals)); + blockIndent = state.position - state.lineStart; -return Object.assign({},...signalsA); -}; + if (indentStatus === 1) { + if (allowBlockCollections && + (readBlockSequence(state, blockIndent) || + readBlockMapping(state, blockIndent, flowIndent)) || + readFlowCollection(state, flowIndent)) { + hasContent = true; + } else { + if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || + readSingleQuotedScalar(state, flowIndent) || + readDoubleQuotedScalar(state, flowIndent)) { + hasContent = true; -const getSignalByNumber=function(number,signals){ -const signal=findSignalByNumber(number,signals); + } else if (readAlias(state)) { + hasContent = true; -if(signal===undefined){ -return{}; -} + if (state.tag !== null || state.anchor !== null) { + throwError(state, 'alias node should not have any properties'); + } -const{name,description,supported,action,forced,standard}=signal; -return{ -[number]:{ -name, -number, -description, -supported, -action, -forced, -standard}}; + } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { + hasContent = true; + if (state.tag === null) { + state.tag = '?'; + } + } -}; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else if (indentStatus === 0) { + // Special case: block sequences are allowed to have same indentation level as the parent. + // http://www.yaml.org/spec/1.2/spec.html#id2799784 + hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); + } + } + if (state.tag === null) { + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } else if (state.tag === '?') { + // Implicit resolving is not allowed for non-scalar types, and '?' + // non-specific tag is only automatically assigned to plain scalars. + // + // We only need to check kind conformity in case user explicitly assigns '?' + // tag, for example like this: "! [0]" + // + if (state.result !== null && state.kind !== 'scalar') { + throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); + } -const findSignalByNumber=function(number,signals){ -const signal=signals.find(({name})=>_os.constants.signals[name]===number); + for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { + type = state.implicitTypes[typeIndex]; -if(signal!==undefined){ -return signal; -} + if (type.resolve(state.result)) { // `state.result` updated in resolver if matched + state.result = type.construct(state.result); + state.tag = type.tag; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + break; + } + } + } else if (state.tag !== '!') { + if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { + type = state.typeMap[state.kind || 'fallback'][state.tag]; + } else { + // looking for multi type + type = null; + typeList = state.typeMap.multi[state.kind || 'fallback']; -return signals.find(signalA=>signalA.number===number); -}; + for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) { + if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { + type = typeList[typeIndex]; + break; + } + } + } -const signalsByNumber=getSignalsByNumber();exports.signalsByNumber=signalsByNumber; -//# sourceMappingURL=main.js.map + if (!type) { + throwError(state, 'unknown tag !<' + state.tag + '>'); + } -/***/ }), + if (state.result !== null && type.kind !== state.kind) { + throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); + } -/***/ 25295: -/***/ ((__unused_webpack_module, exports) => { + if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched + throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); + } else { + state.result = type.construct(state.result, state.tag); + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } -"use strict"; -Object.defineProperty(exports, "__esModule", ({value:true}));exports.SIGRTMAX=exports.getRealtimeSignals=void 0; -const getRealtimeSignals=function(){ -const length=SIGRTMAX-SIGRTMIN+1; -return Array.from({length},getRealtimeSignal); -};exports.getRealtimeSignals=getRealtimeSignals; + if (state.listener !== null) { + state.listener('close', state); + } + return state.tag !== null || state.anchor !== null || hasContent; +} -const getRealtimeSignal=function(value,index){ -return{ -name:`SIGRT${index+1}`, -number:SIGRTMIN+index, -action:"terminate", -description:"Application-specific signal (realtime)", -standard:"posix"}; +function readDocument(state) { + var documentStart = state.position, + _position, + directiveName, + directiveArgs, + hasDirectives = false, + ch; -}; + state.version = null; + state.checkLineBreaks = state.legacy; + state.tagMap = Object.create(null); + state.anchorMap = Object.create(null); -const SIGRTMIN=34; -const SIGRTMAX=64;exports.SIGRTMAX=SIGRTMAX; -//# sourceMappingURL=realtime.js.map + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + skipSeparationSpace(state, true, -1); -/***/ }), + ch = state.input.charCodeAt(state.position); -/***/ 86435: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (state.lineIndent > 0 || ch !== 0x25/* % */) { + break; + } -"use strict"; -Object.defineProperty(exports, "__esModule", ({value:true}));exports.getSignals=void 0;var _os=__nccwpck_require__(22037); + hasDirectives = true; + ch = state.input.charCodeAt(++state.position); + _position = state.position; -var _core=__nccwpck_require__(28213); -var _realtime=__nccwpck_require__(25295); + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + directiveName = state.input.slice(_position, state.position); + directiveArgs = []; + if (directiveName.length < 1) { + throwError(state, 'directive name must not be less than one character in length'); + } -const getSignals=function(){ -const realtimeSignals=(0,_realtime.getRealtimeSignals)(); -const signals=[..._core.SIGNALS,...realtimeSignals].map(normalizeSignal); -return signals; -};exports.getSignals=getSignals; + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && !is_EOL(ch)); + break; + } + if (is_EOL(ch)) break; + _position = state.position; + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + directiveArgs.push(state.input.slice(_position, state.position)); + } + if (ch !== 0) readLineBreak(state); -const normalizeSignal=function({ -name, -number:defaultNumber, -description, -action, -forced=false, -standard}) -{ -const{ -signals:{[name]:constantSignal}}= -_os.constants; -const supported=constantSignal!==undefined; -const number=supported?constantSignal:defaultNumber; -return{name,number,description,supported,action,forced,standard}; -}; -//# sourceMappingURL=signals.js.map + if (_hasOwnProperty.call(directiveHandlers, directiveName)) { + directiveHandlers[directiveName](state, directiveName, directiveArgs); + } else { + throwWarning(state, 'unknown document directive "' + directiveName + '"'); + } + } -/***/ }), + skipSeparationSpace(state, true, -1); -/***/ 98043: -/***/ ((module) => { + if (state.lineIndent === 0 && + state.input.charCodeAt(state.position) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { + state.position += 3; + skipSeparationSpace(state, true, -1); -"use strict"; + } else if (hasDirectives) { + throwError(state, 'directives end mark is expected'); + } + composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); + skipSeparationSpace(state, true, -1); -module.exports = (string, count = 1, options) => { - options = { - indent: ' ', - includeEmptyLines: false, - ...options - }; + if (state.checkLineBreaks && + PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { + throwWarning(state, 'non-ASCII line breaks are interpreted as content'); + } - if (typeof string !== 'string') { - throw new TypeError( - `Expected \`input\` to be a \`string\`, got \`${typeof string}\`` - ); - } + state.documents.push(state.result); - if (typeof count !== 'number') { - throw new TypeError( - `Expected \`count\` to be a \`number\`, got \`${typeof count}\`` - ); - } + if (state.position === state.lineStart && testDocumentSeparator(state)) { - if (typeof options.indent !== 'string') { - throw new TypeError( - `Expected \`options.indent\` to be a \`string\`, got \`${typeof options.indent}\`` - ); - } + if (state.input.charCodeAt(state.position) === 0x2E/* . */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + } + return; + } - if (count === 0) { - return string; - } + if (state.position < (state.length - 1)) { + throwError(state, 'end of the stream or a document separator is expected'); + } else { + return; + } +} - const regex = options.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm; - return string.replace(regex, options.indent.repeat(count)); -}; +function loadDocuments(input, options) { + input = String(input); + options = options || {}; + if (input.length !== 0) { -/***/ }), + // Add tailing `\n` if not exists + if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && + input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { + input += '\n'; + } -/***/ 52492: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Strip BOM + if (input.charCodeAt(0) === 0xFEFF) { + input = input.slice(1); + } + } -var wrappy = __nccwpck_require__(62940) -var reqs = Object.create(null) -var once = __nccwpck_require__(1223) + var state = new State(input, options); -module.exports = wrappy(inflight) + var nullpos = input.indexOf('\0'); -function inflight (key, cb) { - if (reqs[key]) { - reqs[key].push(cb) - return null - } else { - reqs[key] = [cb] - return makeres(key) + if (nullpos !== -1) { + state.position = nullpos; + throwError(state, 'null byte is not allowed in input'); } -} -function makeres (key) { - return once(function RES () { - var cbs = reqs[key] - var len = cbs.length - var args = slice(arguments) + // Use 0 as string terminator. That significantly simplifies bounds check. + state.input += '\0'; - // XXX It's somewhat ambiguous whether a new callback added in this - // pass should be queued for later execution if something in the - // list of callbacks throws, or if it should just be discarded. - // However, it's such an edge case that it hardly matters, and either - // choice is likely as surprising as the other. - // As it happens, we do go ahead and schedule it for later execution. - try { - for (var i = 0; i < len; i++) { - cbs[i].apply(null, args) - } - } finally { - if (cbs.length > len) { - // added more in the interim. - // de-zalgo, just in case, but don't call again. - cbs.splice(0, len) - process.nextTick(function () { - RES.apply(null, args) - }) - } else { - delete reqs[key] - } - } - }) -} + while (state.input.charCodeAt(state.position) === 0x20/* Space */) { + state.lineIndent += 1; + state.position += 1; + } -function slice (args) { - var length = args.length - var array = [] + while (state.position < (state.length - 1)) { + readDocument(state); + } - for (var i = 0; i < length; i++) array[i] = args[i] - return array + return state.documents; } -/***/ }), +function loadAll(input, iterator, options) { + if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { + options = iterator; + iterator = null; + } -/***/ 44124: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var documents = loadDocuments(input, options); -try { - var util = __nccwpck_require__(73837); - /* istanbul ignore next */ - if (typeof util.inherits !== 'function') throw ''; - module.exports = util.inherits; -} catch (e) { - /* istanbul ignore next */ - module.exports = __nccwpck_require__(8544); -} + if (typeof iterator !== 'function') { + return documents; + } + for (var index = 0, length = documents.length; index < length; index += 1) { + iterator(documents[index]); + } +} -/***/ }), -/***/ 8544: -/***/ ((module) => { +function load(input, options) { + var documents = loadDocuments(input, options); -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }) - } - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } + if (documents.length === 0) { + /*eslint-disable no-undefined*/ + return undefined; + } else if (documents.length === 1) { + return documents[0]; } + throw new YAMLException('expected a single document in the stream, but found more'); } +module.exports.loadAll = loadAll; +module.exports.load = load; + + /***/ }), -/***/ 41554: -/***/ ((module) => { +/***/ 21082: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const isStream = stream => - stream !== null && - typeof stream === 'object' && - typeof stream.pipe === 'function'; +/*eslint-disable max-len*/ -isStream.writable = stream => - isStream(stream) && - stream.writable !== false && - typeof stream._write === 'function' && - typeof stream._writableState === 'object'; +var YAMLException = __nccwpck_require__(68179); +var Type = __nccwpck_require__(6073); -isStream.readable = stream => - isStream(stream) && - stream.readable !== false && - typeof stream._read === 'function' && - typeof stream._readableState === 'object'; -isStream.duplex = stream => - isStream.writable(stream) && - isStream.readable(stream); +function compileList(schema, name) { + var result = []; -isStream.transform = stream => - isStream.duplex(stream) && - typeof stream._transform === 'function'; + schema[name].forEach(function (currentType) { + var newIndex = result.length; -module.exports = isStream; + result.forEach(function (previousType, previousIndex) { + if (previousType.tag === currentType.tag && + previousType.kind === currentType.kind && + previousType.multi === currentType.multi) { + newIndex = previousIndex; + } + }); -/***/ }), + result[newIndex] = currentType; + }); -/***/ 10657: -/***/ ((module) => { + return result; +} -module.exports = isTypedArray -isTypedArray.strict = isStrictTypedArray -isTypedArray.loose = isLooseTypedArray -var toString = Object.prototype.toString -var names = { - '[object Int8Array]': true - , '[object Int16Array]': true - , '[object Int32Array]': true - , '[object Uint8Array]': true - , '[object Uint8ClampedArray]': true - , '[object Uint16Array]': true - , '[object Uint32Array]': true - , '[object Float32Array]': true - , '[object Float64Array]': true -} +function compileMap(/* lists... */) { + var result = { + scalar: {}, + sequence: {}, + mapping: {}, + fallback: {}, + multi: { + scalar: [], + sequence: [], + mapping: [], + fallback: [] + } + }, index, length; -function isTypedArray(arr) { - return ( - isStrictTypedArray(arr) - || isLooseTypedArray(arr) - ) -} + function collectType(type) { + if (type.multi) { + result.multi[type.kind].push(type); + result.multi['fallback'].push(type); + } else { + result[type.kind][type.tag] = result['fallback'][type.tag] = type; + } + } -function isStrictTypedArray(arr) { - return ( - arr instanceof Int8Array - || arr instanceof Int16Array - || arr instanceof Int32Array - || arr instanceof Uint8Array - || arr instanceof Uint8ClampedArray - || arr instanceof Uint16Array - || arr instanceof Uint32Array - || arr instanceof Float32Array - || arr instanceof Float64Array - ) + for (index = 0, length = arguments.length; index < length; index += 1) { + arguments[index].forEach(collectType); + } + return result; } -function isLooseTypedArray(arr) { - return names[toString.call(arr)] + +function Schema(definition) { + return this.extend(definition); } -/***/ }), +Schema.prototype.extend = function extend(definition) { + var implicit = []; + var explicit = []; -/***/ 97126: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (definition instanceof Type) { + // Schema.extend(type) + explicit.push(definition); -var fs = __nccwpck_require__(57147) -var core -if (process.platform === 'win32' || global.TESTING_WINDOWS) { - core = __nccwpck_require__(42001) -} else { - core = __nccwpck_require__(9728) -} + } else if (Array.isArray(definition)) { + // Schema.extend([ type1, type2, ... ]) + explicit = explicit.concat(definition); -module.exports = isexe -isexe.sync = sync + } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { + // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] }) + if (definition.implicit) implicit = implicit.concat(definition.implicit); + if (definition.explicit) explicit = explicit.concat(definition.explicit); -function isexe (path, options, cb) { - if (typeof options === 'function') { - cb = options - options = {} + } else { + throw new YAMLException('Schema.extend argument should be a Type, [ Type ], ' + + 'or a schema definition ({ implicit: [...], explicit: [...] })'); } - if (!cb) { - if (typeof Promise !== 'function') { - throw new TypeError('callback not provided') + implicit.forEach(function (type) { + if (!(type instanceof Type)) { + throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); } - return new Promise(function (resolve, reject) { - isexe(path, options || {}, function (er, is) { - if (er) { - reject(er) - } else { - resolve(is) - } - }) - }) - } + if (type.loadKind && type.loadKind !== 'scalar') { + throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); + } - core(path, options || {}, function (er, is) { - // ignore EACCES because that just means we aren't allowed to run it - if (er) { - if (er.code === 'EACCES' || options && options.ignoreErrors) { - er = null - is = false - } + if (type.multi) { + throw new YAMLException('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.'); } - cb(er, is) - }) -} + }); -function sync (path, options) { - // my kingdom for a filtered catch - try { - return core.sync(path, options || {}) - } catch (er) { - if (options && options.ignoreErrors || er.code === 'EACCES') { - return false - } else { - throw er + explicit.forEach(function (type) { + if (!(type instanceof Type)) { + throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); } - } -} + }); + var result = Object.create(Schema.prototype); -/***/ }), + result.implicit = (this.implicit || []).concat(implicit); + result.explicit = (this.explicit || []).concat(explicit); -/***/ 9728: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + result.compiledImplicit = compileList(result, 'implicit'); + result.compiledExplicit = compileList(result, 'explicit'); + result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); -module.exports = isexe -isexe.sync = sync + return result; +}; -var fs = __nccwpck_require__(57147) -function isexe (path, options, cb) { - fs.stat(path, function (er, stat) { - cb(er, er ? false : checkStat(stat, options)) - }) -} +module.exports = Schema; -function sync (path, options) { - return checkStat(fs.statSync(path), options) -} -function checkStat (stat, options) { - return stat.isFile() && checkMode(stat, options) -} +/***/ }), -function checkMode (stat, options) { - var mod = stat.mode - var uid = stat.uid - var gid = stat.gid +/***/ 12011: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var myUid = options.uid !== undefined ? - options.uid : process.getuid && process.getuid() - var myGid = options.gid !== undefined ? - options.gid : process.getgid && process.getgid() +"use strict"; +// Standard YAML's Core schema. +// http://www.yaml.org/spec/1.2/spec.html#id2804923 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, Core schema has no distinctions from JSON schema is JS-YAML. - var u = parseInt('100', 8) - var g = parseInt('010', 8) - var o = parseInt('001', 8) - var ug = u | g - var ret = (mod & o) || - (mod & g) && gid === myGid || - (mod & u) && uid === myUid || - (mod & ug) && myUid === 0 - return ret -} -/***/ }), +module.exports = __nccwpck_require__(1035); -/***/ 42001: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports = isexe -isexe.sync = sync +/***/ }), -var fs = __nccwpck_require__(57147) +/***/ 18759: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function checkPathExt (path, options) { - var pathext = options.pathExt !== undefined ? - options.pathExt : process.env.PATHEXT +"use strict"; +// JS-YAML's default schema for `safeLoad` function. +// It is not described in the YAML specification. +// +// This schema is based on standard YAML's Core schema and includes most of +// extra types described at YAML tag repository. (http://yaml.org/type/) - if (!pathext) { - return true - } - pathext = pathext.split(';') - if (pathext.indexOf('') !== -1) { - return true - } - for (var i = 0; i < pathext.length; i++) { - var p = pathext[i].toLowerCase() - if (p && path.substr(-p.length).toLowerCase() === p) { - return true - } - } - return false -} -function checkStat (stat, path, options) { - if (!stat.isSymbolicLink() && !stat.isFile()) { - return false - } - return checkPathExt(path, options) -} -function isexe (path, options, cb) { - fs.stat(path, function (er, stat) { - cb(er, er ? false : checkStat(stat, path, options)) - }) -} -function sync (path, options) { - return checkStat(fs.statSync(path), path, options) -} +module.exports = (__nccwpck_require__(12011).extend)({ + implicit: [ + __nccwpck_require__(99212), + __nccwpck_require__(86104) + ], + explicit: [ + __nccwpck_require__(77900), + __nccwpck_require__(19046), + __nccwpck_require__(96860), + __nccwpck_require__(79548) + ] +}); /***/ }), -/***/ 64713: +/***/ 28562: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +// Standard YAML's Failsafe schema. +// http://www.yaml.org/spec/1.2/spec.html#id2802346 -module.exports = __nccwpck_require__(88867); -/***/ }), -/***/ 83362: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var stream = __nccwpck_require__(12781) +var Schema = __nccwpck_require__(21082); -function isStream (obj) { - return obj instanceof stream.Stream -} +module.exports = new Schema({ + explicit: [ + __nccwpck_require__(23619), + __nccwpck_require__(67283), + __nccwpck_require__(86150) + ] +}); -function isReadable (obj) { - return isStream(obj) && typeof obj._read == 'function' && typeof obj._readableState == 'object' -} +/***/ }), +/***/ 1035: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function isWritable (obj) { - return isStream(obj) && typeof obj._write == 'function' && typeof obj._writableState == 'object' -} +"use strict"; +// Standard YAML's JSON schema. +// http://www.yaml.org/spec/1.2/spec.html#id2803231 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, this schema is not such strict as defined in the YAML specification. +// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. -function isDuplex (obj) { - return isReadable(obj) && isWritable(obj) -} -module.exports = isStream -module.exports.isReadable = isReadable -module.exports.isWritable = isWritable -module.exports.isDuplex = isDuplex + +module.exports = (__nccwpck_require__(28562).extend)({ + implicit: [ + __nccwpck_require__(20721), + __nccwpck_require__(64993), + __nccwpck_require__(11615), + __nccwpck_require__(42705) + ] +}); /***/ }), -/***/ 21917: +/***/ 96975: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var loader = __nccwpck_require__(51161); -var dumper = __nccwpck_require__(68866); +var common = __nccwpck_require__(26829); -function renamed(from, to) { - return function () { - throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' + - 'Use yaml.' + to + ' instead, which is now safe by default.'); +// get snippet for a single line, respecting maxLength +function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { + var head = ''; + var tail = ''; + var maxHalfLength = Math.floor(maxLineLength / 2) - 1; + + if (position - lineStart > maxHalfLength) { + head = ' ... '; + lineStart = position - maxHalfLength + head.length; + } + + if (lineEnd - position > maxHalfLength) { + tail = ' ...'; + lineEnd = position + maxHalfLength - tail.length; + } + + return { + str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail, + pos: position - lineStart + head.length // relative position }; } -module.exports.Type = __nccwpck_require__(6073); -module.exports.Schema = __nccwpck_require__(21082); -module.exports.FAILSAFE_SCHEMA = __nccwpck_require__(28562); -module.exports.JSON_SCHEMA = __nccwpck_require__(1035); -module.exports.CORE_SCHEMA = __nccwpck_require__(12011); -module.exports.DEFAULT_SCHEMA = __nccwpck_require__(18759); -module.exports.load = loader.load; -module.exports.loadAll = loader.loadAll; -module.exports.dump = dumper.dump; -module.exports.YAMLException = __nccwpck_require__(68179); +function padStart(string, max) { + return common.repeat(' ', max - string.length) + string; +} -// Re-export all types in case user wants to create custom schema -module.exports.types = { - binary: __nccwpck_require__(77900), - float: __nccwpck_require__(42705), - map: __nccwpck_require__(86150), - null: __nccwpck_require__(20721), - pairs: __nccwpck_require__(96860), - set: __nccwpck_require__(79548), - timestamp: __nccwpck_require__(99212), - bool: __nccwpck_require__(64993), - int: __nccwpck_require__(11615), - merge: __nccwpck_require__(86104), - omap: __nccwpck_require__(19046), - seq: __nccwpck_require__(67283), - str: __nccwpck_require__(23619) -}; -// Removed functions from JS-YAML 3.0.x -module.exports.safeLoad = renamed('safeLoad', 'load'); -module.exports.safeLoadAll = renamed('safeLoadAll', 'loadAll'); -module.exports.safeDump = renamed('safeDump', 'dump'); +function makeSnippet(mark, options) { + options = Object.create(options || null); + if (!mark.buffer) return null; -/***/ }), + if (!options.maxLength) options.maxLength = 79; + if (typeof options.indent !== 'number') options.indent = 1; + if (typeof options.linesBefore !== 'number') options.linesBefore = 3; + if (typeof options.linesAfter !== 'number') options.linesAfter = 2; -/***/ 26829: -/***/ ((module) => { + var re = /\r?\n|\r|\0/g; + var lineStarts = [ 0 ]; + var lineEnds = []; + var match; + var foundLineNo = -1; -"use strict"; + while ((match = re.exec(mark.buffer))) { + lineEnds.push(match.index); + lineStarts.push(match.index + match[0].length); + if (mark.position <= match.index && foundLineNo < 0) { + foundLineNo = lineStarts.length - 2; + } + } + if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; -function isNothing(subject) { - return (typeof subject === 'undefined') || (subject === null); -} + var result = '', i, line; + var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; + var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); + + for (i = 1; i <= options.linesBefore; i++) { + if (foundLineNo - i < 0) break; + line = getLine( + mark.buffer, + lineStarts[foundLineNo - i], + lineEnds[foundLineNo - i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), + maxLineLength + ); + result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n' + result; + } + line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); + result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n'; + result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n'; -function isObject(subject) { - return (typeof subject === 'object') && (subject !== null); + for (i = 1; i <= options.linesAfter; i++) { + if (foundLineNo + i >= lineEnds.length) break; + line = getLine( + mark.buffer, + lineStarts[foundLineNo + i], + lineEnds[foundLineNo + i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), + maxLineLength + ); + result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n'; + } + + return result.replace(/\n$/, ''); } -function toArray(sequence) { - if (Array.isArray(sequence)) return sequence; - else if (isNothing(sequence)) return []; +module.exports = makeSnippet; - return [ sequence ]; -} +/***/ }), -function extend(target, source) { - var index, length, key, sourceKeys; +/***/ 6073: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (source) { - sourceKeys = Object.keys(source); +"use strict"; - for (index = 0, length = sourceKeys.length; index < length; index += 1) { - key = sourceKeys[index]; - target[key] = source[key]; - } - } - return target; -} +var YAMLException = __nccwpck_require__(68179); + +var TYPE_CONSTRUCTOR_OPTIONS = [ + 'kind', + 'multi', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'representName', + 'defaultStyle', + 'styleAliases' +]; +var YAML_NODE_KINDS = [ + 'scalar', + 'sequence', + 'mapping' +]; -function repeat(string, count) { - var result = '', cycle; +function compileStyleAliases(map) { + var result = {}; - for (cycle = 0; cycle < count; cycle += 1) { - result += string; + if (map !== null) { + Object.keys(map).forEach(function (style) { + map[style].forEach(function (alias) { + result[String(alias)] = style; + }); + }); } return result; } +function Type(tag, options) { + options = options || {}; -function isNegativeZero(number) { - return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); -} + Object.keys(options).forEach(function (name) { + if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { + throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); + } + }); + + // TODO: Add tag format check. + this.options = options; // keep original options in case user wants to extend this type later + this.tag = tag; + this.kind = options['kind'] || null; + this.resolve = options['resolve'] || function () { return true; }; + this.construct = options['construct'] || function (data) { return data; }; + this.instanceOf = options['instanceOf'] || null; + this.predicate = options['predicate'] || null; + this.represent = options['represent'] || null; + this.representName = options['representName'] || null; + this.defaultStyle = options['defaultStyle'] || null; + this.multi = options['multi'] || false; + this.styleAliases = compileStyleAliases(options['styleAliases'] || null); + if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { + throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + } +} -module.exports.isNothing = isNothing; -module.exports.isObject = isObject; -module.exports.toArray = toArray; -module.exports.repeat = repeat; -module.exports.isNegativeZero = isNegativeZero; -module.exports.extend = extend; +module.exports = Type; /***/ }), -/***/ 68866: +/***/ 77900: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/*eslint-disable no-use-before-define*/ - -var common = __nccwpck_require__(26829); -var YAMLException = __nccwpck_require__(68179); -var DEFAULT_SCHEMA = __nccwpck_require__(18759); - -var _toString = Object.prototype.toString; -var _hasOwnProperty = Object.prototype.hasOwnProperty; - -var CHAR_BOM = 0xFEFF; -var CHAR_TAB = 0x09; /* Tab */ -var CHAR_LINE_FEED = 0x0A; /* LF */ -var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */ -var CHAR_SPACE = 0x20; /* Space */ -var CHAR_EXCLAMATION = 0x21; /* ! */ -var CHAR_DOUBLE_QUOTE = 0x22; /* " */ -var CHAR_SHARP = 0x23; /* # */ -var CHAR_PERCENT = 0x25; /* % */ -var CHAR_AMPERSAND = 0x26; /* & */ -var CHAR_SINGLE_QUOTE = 0x27; /* ' */ -var CHAR_ASTERISK = 0x2A; /* * */ -var CHAR_COMMA = 0x2C; /* , */ -var CHAR_MINUS = 0x2D; /* - */ -var CHAR_COLON = 0x3A; /* : */ -var CHAR_EQUALS = 0x3D; /* = */ -var CHAR_GREATER_THAN = 0x3E; /* > */ -var CHAR_QUESTION = 0x3F; /* ? */ -var CHAR_COMMERCIAL_AT = 0x40; /* @ */ -var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ -var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ -var CHAR_GRAVE_ACCENT = 0x60; /* ` */ -var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ -var CHAR_VERTICAL_LINE = 0x7C; /* | */ -var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ +/*eslint-disable no-bitwise*/ -var ESCAPE_SEQUENCES = {}; -ESCAPE_SEQUENCES[0x00] = '\\0'; -ESCAPE_SEQUENCES[0x07] = '\\a'; -ESCAPE_SEQUENCES[0x08] = '\\b'; -ESCAPE_SEQUENCES[0x09] = '\\t'; -ESCAPE_SEQUENCES[0x0A] = '\\n'; -ESCAPE_SEQUENCES[0x0B] = '\\v'; -ESCAPE_SEQUENCES[0x0C] = '\\f'; -ESCAPE_SEQUENCES[0x0D] = '\\r'; -ESCAPE_SEQUENCES[0x1B] = '\\e'; -ESCAPE_SEQUENCES[0x22] = '\\"'; -ESCAPE_SEQUENCES[0x5C] = '\\\\'; -ESCAPE_SEQUENCES[0x85] = '\\N'; -ESCAPE_SEQUENCES[0xA0] = '\\_'; -ESCAPE_SEQUENCES[0x2028] = '\\L'; -ESCAPE_SEQUENCES[0x2029] = '\\P'; +var Type = __nccwpck_require__(6073); -var DEPRECATED_BOOLEANS_SYNTAX = [ - 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', - 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' -]; -var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/; +// [ 64, 65, 66 ] -> [ padding, CR, LF ] +var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; -function compileStyleMap(schema, map) { - var result, keys, index, length, tag, style, type; - if (map === null) return {}; +function resolveYamlBinary(data) { + if (data === null) return false; - result = {}; - keys = Object.keys(map); + var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; - for (index = 0, length = keys.length; index < length; index += 1) { - tag = keys[index]; - style = String(map[tag]); + // Convert one by one. + for (idx = 0; idx < max; idx++) { + code = map.indexOf(data.charAt(idx)); - if (tag.slice(0, 2) === '!!') { - tag = 'tag:yaml.org,2002:' + tag.slice(2); - } - type = schema.compiledTypeMap['fallback'][tag]; + // Skip CR/LF + if (code > 64) continue; - if (type && _hasOwnProperty.call(type.styleAliases, style)) { - style = type.styleAliases[style]; - } + // Fail on illegal characters + if (code < 0) return false; - result[tag] = style; + bitlen += 6; } - return result; + // If there are any bits left, source was corrupted + return (bitlen % 8) === 0; } -function encodeHex(character) { - var string, handle, length; +function constructYamlBinary(data) { + var idx, tailbits, + input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan + max = input.length, + map = BASE64_MAP, + bits = 0, + result = []; - string = character.toString(16).toUpperCase(); + // Collect by 6*4 bits (3 bytes) - if (character <= 0xFF) { - handle = 'x'; - length = 2; - } else if (character <= 0xFFFF) { - handle = 'u'; - length = 4; - } else if (character <= 0xFFFFFFFF) { - handle = 'U'; - length = 8; - } else { - throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); + for (idx = 0; idx < max; idx++) { + if ((idx % 4 === 0) && idx) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } + + bits = (bits << 6) | map.indexOf(input.charAt(idx)); } - return '\\' + handle + common.repeat('0', length - string.length) + string; -} + // Dump tail + tailbits = (max % 4) * 6; -var QUOTING_TYPE_SINGLE = 1, - QUOTING_TYPE_DOUBLE = 2; + if (tailbits === 0) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } else if (tailbits === 18) { + result.push((bits >> 10) & 0xFF); + result.push((bits >> 2) & 0xFF); + } else if (tailbits === 12) { + result.push((bits >> 4) & 0xFF); + } -function State(options) { - this.schema = options['schema'] || DEFAULT_SCHEMA; - this.indent = Math.max(1, (options['indent'] || 2)); - this.noArrayIndent = options['noArrayIndent'] || false; - this.skipInvalid = options['skipInvalid'] || false; - this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); - this.styleMap = compileStyleMap(this.schema, options['styles'] || null); - this.sortKeys = options['sortKeys'] || false; - this.lineWidth = options['lineWidth'] || 80; - this.noRefs = options['noRefs'] || false; - this.noCompatMode = options['noCompatMode'] || false; - this.condenseFlow = options['condenseFlow'] || false; - this.quotingType = options['quotingType'] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE; - this.forceQuotes = options['forceQuotes'] || false; - this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null; + return new Uint8Array(result); +} - this.implicitTypes = this.schema.compiledImplicit; - this.explicitTypes = this.schema.compiledExplicit; +function representYamlBinary(object /*, style*/) { + var result = '', bits = 0, idx, tail, + max = object.length, + map = BASE64_MAP; - this.tag = null; - this.result = ''; + // Convert every three bytes to 4 ASCII characters. - this.duplicates = []; - this.usedDuplicates = null; -} + for (idx = 0; idx < max; idx++) { + if ((idx % 3 === 0) && idx) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } -// Indents every line in a string. Empty lines (\n only) are not indented. -function indentString(string, spaces) { - var ind = common.repeat(' ', spaces), - position = 0, - next = -1, - result = '', - line, - length = string.length; + bits = (bits << 8) + object[idx]; + } - while (position < length) { - next = string.indexOf('\n', position); - if (next === -1) { - line = string.slice(position); - position = length; - } else { - line = string.slice(position, next + 1); - position = next + 1; - } + // Dump tail - if (line.length && line !== '\n') result += ind; + tail = max % 3; - result += line; + if (tail === 0) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } else if (tail === 2) { + result += map[(bits >> 10) & 0x3F]; + result += map[(bits >> 4) & 0x3F]; + result += map[(bits << 2) & 0x3F]; + result += map[64]; + } else if (tail === 1) { + result += map[(bits >> 2) & 0x3F]; + result += map[(bits << 4) & 0x3F]; + result += map[64]; + result += map[64]; } return result; } -function generateNextLine(state, level) { - return '\n' + common.repeat(' ', state.indent * level); +function isBinary(obj) { + return Object.prototype.toString.call(obj) === '[object Uint8Array]'; } -function testImplicitResolving(state, str) { - var index, length, type; +module.exports = new Type('tag:yaml.org,2002:binary', { + kind: 'scalar', + resolve: resolveYamlBinary, + construct: constructYamlBinary, + predicate: isBinary, + represent: representYamlBinary +}); - for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { - type = state.implicitTypes[index]; - if (type.resolve(str)) { - return true; - } - } +/***/ }), - return false; -} +/***/ 64993: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// [33] s-white ::= s-space | s-tab -function isWhitespace(c) { - return c === CHAR_SPACE || c === CHAR_TAB; -} +"use strict"; -// Returns true if the character can be printed without escaping. -// From YAML 1.2: "any allowed characters known to be non-printable -// should also be escaped. [However,] This isn’t mandatory" -// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. -function isPrintable(c) { - return (0x00020 <= c && c <= 0x00007E) - || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) - || ((0x0E000 <= c && c <= 0x00FFFD) && c !== CHAR_BOM) - || (0x10000 <= c && c <= 0x10FFFF); -} -// [34] ns-char ::= nb-char - s-white -// [27] nb-char ::= c-printable - b-char - c-byte-order-mark -// [26] b-char ::= b-line-feed | b-carriage-return -// Including s-white (for some reason, examples doesn't match specs in this aspect) -// ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark -function isNsCharOrWhitespace(c) { - return isPrintable(c) - && c !== CHAR_BOM - // - b-char - && c !== CHAR_CARRIAGE_RETURN - && c !== CHAR_LINE_FEED; -} +var Type = __nccwpck_require__(6073); -// [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out -// c = flow-in ⇒ ns-plain-safe-in -// c = block-key ⇒ ns-plain-safe-out -// c = flow-key ⇒ ns-plain-safe-in -// [128] ns-plain-safe-out ::= ns-char -// [129] ns-plain-safe-in ::= ns-char - c-flow-indicator -// [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:” - “#” ) -// | ( /* An ns-char preceding */ “#” ) -// | ( “:” /* Followed by an ns-plain-safe(c) */ ) -function isPlainSafe(c, prev, inblock) { - var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c); - var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c); - return ( - // ns-plain-safe - inblock ? // c = flow-in - cIsNsCharOrWhitespace - : cIsNsCharOrWhitespace - // - c-flow-indicator - && c !== CHAR_COMMA - && c !== CHAR_LEFT_SQUARE_BRACKET - && c !== CHAR_RIGHT_SQUARE_BRACKET - && c !== CHAR_LEFT_CURLY_BRACKET - && c !== CHAR_RIGHT_CURLY_BRACKET - ) - // ns-plain-char - && c !== CHAR_SHARP // false on '#' - && !(prev === CHAR_COLON && !cIsNsChar) // false on ': ' - || (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) // change to true on '[^ ]#' - || (prev === CHAR_COLON && cIsNsChar); // change to true on ':[^ ]' -} +function resolveYamlBoolean(data) { + if (data === null) return false; -// Simplified test for values allowed as the first character in plain style. -function isPlainSafeFirst(c) { - // Uses a subset of ns-char - c-indicator - // where ns-char = nb-char - s-white. - // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part - return isPrintable(c) && c !== CHAR_BOM - && !isWhitespace(c) // - s-white - // - (c-indicator ::= - // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” - && c !== CHAR_MINUS - && c !== CHAR_QUESTION - && c !== CHAR_COLON - && c !== CHAR_COMMA - && c !== CHAR_LEFT_SQUARE_BRACKET - && c !== CHAR_RIGHT_SQUARE_BRACKET - && c !== CHAR_LEFT_CURLY_BRACKET - && c !== CHAR_RIGHT_CURLY_BRACKET - // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” - && c !== CHAR_SHARP - && c !== CHAR_AMPERSAND - && c !== CHAR_ASTERISK - && c !== CHAR_EXCLAMATION - && c !== CHAR_VERTICAL_LINE - && c !== CHAR_EQUALS - && c !== CHAR_GREATER_THAN - && c !== CHAR_SINGLE_QUOTE - && c !== CHAR_DOUBLE_QUOTE - // | “%” | “@” | “`”) - && c !== CHAR_PERCENT - && c !== CHAR_COMMERCIAL_AT - && c !== CHAR_GRAVE_ACCENT; -} + var max = data.length; -// Simplified test for values allowed as the last character in plain style. -function isPlainSafeLast(c) { - // just not whitespace or colon, it will be checked to be plain character later - return !isWhitespace(c) && c !== CHAR_COLON; + return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || + (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); } -// Same as 'string'.codePointAt(pos), but works in older browsers. -function codePointAt(string, pos) { - var first = string.charCodeAt(pos), second; - if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) { - second = string.charCodeAt(pos + 1); - if (second >= 0xDC00 && second <= 0xDFFF) { - // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae - return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; - } - } - return first; +function constructYamlBoolean(data) { + return data === 'true' || + data === 'True' || + data === 'TRUE'; } -// Determines whether block indentation indicator is required. -function needIndentIndicator(string) { - var leadingSpaceRe = /^\n* /; - return leadingSpaceRe.test(string); +function isBoolean(object) { + return Object.prototype.toString.call(object) === '[object Boolean]'; } -var STYLE_PLAIN = 1, - STYLE_SINGLE = 2, - STYLE_LITERAL = 3, - STYLE_FOLDED = 4, - STYLE_DOUBLE = 5; +module.exports = new Type('tag:yaml.org,2002:bool', { + kind: 'scalar', + resolve: resolveYamlBoolean, + construct: constructYamlBoolean, + predicate: isBoolean, + represent: { + lowercase: function (object) { return object ? 'true' : 'false'; }, + uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, + camelcase: function (object) { return object ? 'True' : 'False'; } + }, + defaultStyle: 'lowercase' +}); -// Determines which scalar styles are possible and returns the preferred style. -// lineWidth = -1 => no limit. -// Pre-conditions: str.length > 0. -// Post-conditions: -// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. -// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). -// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). -function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, - testAmbiguousType, quotingType, forceQuotes, inblock) { - var i; - var char = 0; - var prevChar = null; - var hasLineBreak = false; - var hasFoldableLine = false; // only checked if shouldTrackWidth - var shouldTrackWidth = lineWidth !== -1; - var previousLineBreak = -1; // count the first line correctly - var plain = isPlainSafeFirst(codePointAt(string, 0)) - && isPlainSafeLast(codePointAt(string, string.length - 1)); +/***/ }), - if (singleLineOnly || forceQuotes) { - // Case: no block styles. - // Check for disallowed characters to rule out plain and single. - for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { - char = codePointAt(string, i); - if (!isPrintable(char)) { - return STYLE_DOUBLE; - } - plain = plain && isPlainSafe(char, prevChar, inblock); - prevChar = char; - } - } else { - // Case: block styles permitted. - for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { - char = codePointAt(string, i); - if (char === CHAR_LINE_FEED) { - hasLineBreak = true; - // Check if any line can be folded. - if (shouldTrackWidth) { - hasFoldableLine = hasFoldableLine || - // Foldable line = too long, and not more-indented. - (i - previousLineBreak - 1 > lineWidth && - string[previousLineBreak + 1] !== ' '); - previousLineBreak = i; - } - } else if (!isPrintable(char)) { - return STYLE_DOUBLE; - } - plain = plain && isPlainSafe(char, prevChar, inblock); - prevChar = char; - } - // in case the end is missing a \n - hasFoldableLine = hasFoldableLine || (shouldTrackWidth && - (i - previousLineBreak - 1 > lineWidth && - string[previousLineBreak + 1] !== ' ')); - } - // Although every style can represent \n without escaping, prefer block styles - // for multiline, since they're more readable and they don't add empty lines. - // Also prefer folding a super-long line. - if (!hasLineBreak && !hasFoldableLine) { - // Strings interpretable as another type have to be quoted; - // e.g. the string 'true' vs. the boolean true. - if (plain && !forceQuotes && !testAmbiguousType(string)) { - return STYLE_PLAIN; - } - return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; +/***/ 42705: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var common = __nccwpck_require__(26829); +var Type = __nccwpck_require__(6073); + +var YAML_FLOAT_PATTERN = new RegExp( + // 2.5e4, 2.5 and integers + '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + + // .2e4, .2 + // special case, seems not from spec + '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + + // .inf + '|[-+]?\\.(?:inf|Inf|INF)' + + // .nan + '|\\.(?:nan|NaN|NAN))$'); + +function resolveYamlFloat(data) { + if (data === null) return false; + + if (!YAML_FLOAT_PATTERN.test(data) || + // Quick hack to not allow integers end with `_` + // Probably should update regexp & check speed + data[data.length - 1] === '_') { + return false; } - // Edge case: block indentation indicator can only have one digit. - if (indentPerLevel > 9 && needIndentIndicator(string)) { - return STYLE_DOUBLE; + + return true; +} + +function constructYamlFloat(data) { + var value, sign; + + value = data.replace(/_/g, '').toLowerCase(); + sign = value[0] === '-' ? -1 : 1; + + if ('+-'.indexOf(value[0]) >= 0) { + value = value.slice(1); } - // At this point we know block styles are valid. - // Prefer literal style unless we want to fold. - if (!forceQuotes) { - return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; + + if (value === '.inf') { + return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; + + } else if (value === '.nan') { + return NaN; } - return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; + return sign * parseFloat(value, 10); } -// Note: line breaking/folding is implemented for only the folded style. -// NB. We drop the last trailing newline (if any) of a returned block scalar -// since the dumper adds its own newline. This always works: -// • No ending newline => unaffected; already using strip "-" chomping. -// • Ending newline => removed then restored. -// Importantly, this keeps the "+" chomp indicator from gaining an extra line. -function writeScalar(state, string, level, iskey, inblock) { - state.dump = (function () { - if (string.length === 0) { - return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''"; - } - if (!state.noCompatMode) { - if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) { - return state.quotingType === QUOTING_TYPE_DOUBLE ? ('"' + string + '"') : ("'" + string + "'"); - } - } - - var indent = state.indent * Math.max(1, level); // no 0-indent scalars - // As indentation gets deeper, let the width decrease monotonically - // to the lower bound min(state.lineWidth, 40). - // Note that this implies - // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. - // state.lineWidth > 40 + state.indent: width decreases until the lower bound. - // This behaves better than a constant minimum width which disallows narrower options, - // or an indent threshold which causes the width to suddenly increase. - var lineWidth = state.lineWidth === -1 - ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); - // Without knowing if keys are implicit/explicit, assume implicit for safety. - var singleLineOnly = iskey - // No block styles in flow mode. - || (state.flowLevel > -1 && level >= state.flowLevel); - function testAmbiguity(string) { - return testImplicitResolving(state, string); - } +var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; - switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, - testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) { +function representYamlFloat(object, style) { + var res; - case STYLE_PLAIN: - return string; - case STYLE_SINGLE: - return "'" + string.replace(/'/g, "''") + "'"; - case STYLE_LITERAL: - return '|' + blockHeader(string, state.indent) - + dropEndingNewline(indentString(string, indent)); - case STYLE_FOLDED: - return '>' + blockHeader(string, state.indent) - + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); - case STYLE_DOUBLE: - return '"' + escapeString(string, lineWidth) + '"'; - default: - throw new YAMLException('impossible error: invalid scalar style'); + if (isNaN(object)) { + switch (style) { + case 'lowercase': return '.nan'; + case 'uppercase': return '.NAN'; + case 'camelcase': return '.NaN'; } - }()); -} + } else if (Number.POSITIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '.inf'; + case 'uppercase': return '.INF'; + case 'camelcase': return '.Inf'; + } + } else if (Number.NEGATIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '-.inf'; + case 'uppercase': return '-.INF'; + case 'camelcase': return '-.Inf'; + } + } else if (common.isNegativeZero(object)) { + return '-0.0'; + } -// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. -function blockHeader(string, indentPerLevel) { - var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; + res = object.toString(10); - // note the special case: the string '\n' counts as a "trailing" empty line. - var clip = string[string.length - 1] === '\n'; - var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); - var chomp = keep ? '+' : (clip ? '' : '-'); + // JS stringifier can build scientific format without dots: 5e-100, + // while YAML requres dot: 5.e-100. Fix it with simple hack - return indentIndicator + chomp + '\n'; + return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; } -// (See the note for writeScalar.) -function dropEndingNewline(string) { - return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; +function isFloat(object) { + return (Object.prototype.toString.call(object) === '[object Number]') && + (object % 1 !== 0 || common.isNegativeZero(object)); } -// Note: a long line without a suitable break point will exceed the width limit. -// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. -function foldString(string, width) { - // In folded style, $k$ consecutive newlines output as $k+1$ newlines— - // unless they're before or after a more-indented line, or at the very - // beginning or end, in which case $k$ maps to $k$. - // Therefore, parse each chunk as newline(s) followed by a content line. - var lineRe = /(\n+)([^\n]*)/g; +module.exports = new Type('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: 'lowercase' +}); - // first line (possibly an empty line) - var result = (function () { - var nextLF = string.indexOf('\n'); - nextLF = nextLF !== -1 ? nextLF : string.length; - lineRe.lastIndex = nextLF; - return foldLine(string.slice(0, nextLF), width); - }()); - // If we haven't reached the first content line yet, don't add an extra \n. - var prevMoreIndented = string[0] === '\n' || string[0] === ' '; - var moreIndented; - // rest of the lines - var match; - while ((match = lineRe.exec(string))) { - var prefix = match[1], line = match[2]; - moreIndented = (line[0] === ' '); - result += prefix - + (!prevMoreIndented && !moreIndented && line !== '' - ? '\n' : '') - + foldLine(line, width); - prevMoreIndented = moreIndented; - } +/***/ }), - return result; +/***/ 11615: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var common = __nccwpck_require__(26829); +var Type = __nccwpck_require__(6073); + +function isHexCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || + ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || + ((0x61/* a */ <= c) && (c <= 0x66/* f */)); } -// Greedy line breaking. -// Picks the longest line under the limit each time, -// otherwise settles for the shortest line over the limit. -// NB. More-indented lines *cannot* be folded, as that would add an extra \n. -function foldLine(line, width) { - if (line === '' || line[0] === ' ') return line; +function isOctCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); +} - // Since a more-indented line adds a \n, breaks can't be followed by a space. - var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. - var match; - // start is an inclusive index. end, curr, and next are exclusive. - var start = 0, end, curr = 0, next = 0; - var result = ''; +function isDecCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); +} - // Invariants: 0 <= start <= length-1. - // 0 <= curr <= next <= max(0, length-2). curr - start <= width. - // Inside the loop: - // A match implies length >= 2, so curr and next are <= length-2. - while ((match = breakRe.exec(line))) { - next = match.index; - // maintain invariant: curr - start <= width - if (next - start > width) { - end = (curr > start) ? curr : next; // derive end <= length-2 - result += '\n' + line.slice(start, end); - // skip the space that was output as \n - start = end + 1; // derive start <= length-1 - } - curr = next; - } +function resolveYamlInteger(data) { + if (data === null) return false; - // By the invariants, start <= length-1, so there is something left over. - // It is either the whole string or a part starting from non-whitespace. - result += '\n'; - // Insert a break if the remainder is too long and there is a break available. - if (line.length - start > width && curr > start) { - result += line.slice(start, curr) + '\n' + line.slice(curr + 1); - } else { - result += line.slice(start); + var max = data.length, + index = 0, + hasDigits = false, + ch; + + if (!max) return false; + + ch = data[index]; + + // sign + if (ch === '-' || ch === '+') { + ch = data[++index]; } - return result.slice(1); // drop extra \n joiner -} + if (ch === '0') { + // 0 + if (index + 1 === max) return true; + ch = data[++index]; -// Escapes a double-quoted string. -function escapeString(string) { - var result = ''; - var char = 0; - var escapeSeq; + // base 2, base 8, base 16 - for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { - char = codePointAt(string, i); - escapeSeq = ESCAPE_SEQUENCES[char]; + if (ch === 'b') { + // base 2 + index++; - if (!escapeSeq && isPrintable(char)) { - result += string[i]; - if (char >= 0x10000) result += string[i + 1]; - } else { - result += escapeSeq || encodeHex(char); + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch !== '0' && ch !== '1') return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; } - } - return result; -} -function writeFlowSequence(state, level, object) { - var _result = '', - _tag = state.tag, - index, - length, - value; + if (ch === 'x') { + // base 16 + index++; - for (index = 0, length = object.length; index < length; index += 1) { - value = object[index]; + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isHexCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } - if (state.replacer) { - value = state.replacer.call(object, String(index), value); + + if (ch === 'o') { + // base 8 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isOctCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; } + } - // Write only valid elements, put null instead of invalid elements. - if (writeNode(state, level, value, false, false) || - (typeof value === 'undefined' && - writeNode(state, level, null, false, false))) { + // base 10 (except 0) - if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : ''); - _result += state.dump; + // value should not start with `_`; + if (ch === '_') return false; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isDecCode(data.charCodeAt(index))) { + return false; } + hasDigits = true; } - state.tag = _tag; - state.dump = '[' + _result + ']'; -} + // Should have digits and should not end with `_` + if (!hasDigits || ch === '_') return false; -function writeBlockSequence(state, level, object, compact) { - var _result = '', - _tag = state.tag, - index, - length, - value; + return true; +} - for (index = 0, length = object.length; index < length; index += 1) { - value = object[index]; +function constructYamlInteger(data) { + var value = data, sign = 1, ch; - if (state.replacer) { - value = state.replacer.call(object, String(index), value); - } + if (value.indexOf('_') !== -1) { + value = value.replace(/_/g, ''); + } - // Write only valid elements, put null instead of invalid elements. - if (writeNode(state, level + 1, value, true, true, false, true) || - (typeof value === 'undefined' && - writeNode(state, level + 1, null, true, true, false, true))) { + ch = value[0]; - if (!compact || _result !== '') { - _result += generateNextLine(state, level); - } + if (ch === '-' || ch === '+') { + if (ch === '-') sign = -1; + value = value.slice(1); + ch = value[0]; + } - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - _result += '-'; - } else { - _result += '- '; - } + if (value === '0') return 0; - _result += state.dump; - } + if (ch === '0') { + if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); + if (value[1] === 'x') return sign * parseInt(value.slice(2), 16); + if (value[1] === 'o') return sign * parseInt(value.slice(2), 8); } - state.tag = _tag; - state.dump = _result || '[]'; // Empty sequence if no valid values. + return sign * parseInt(value, 10); } -function writeFlowMapping(state, level, object) { - var _result = '', - _tag = state.tag, - objectKeyList = Object.keys(object), - index, - length, - objectKey, - objectValue, - pairBuffer; +function isInteger(object) { + return (Object.prototype.toString.call(object)) === '[object Number]' && + (object % 1 === 0 && !common.isNegativeZero(object)); +} - for (index = 0, length = objectKeyList.length; index < length; index += 1) { +module.exports = new Type('tag:yaml.org,2002:int', { + kind: 'scalar', + resolve: resolveYamlInteger, + construct: constructYamlInteger, + predicate: isInteger, + represent: { + binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, + octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); }, + decimal: function (obj) { return obj.toString(10); }, + /* eslint-disable max-len */ + hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } + }, + defaultStyle: 'decimal', + styleAliases: { + binary: [ 2, 'bin' ], + octal: [ 8, 'oct' ], + decimal: [ 10, 'dec' ], + hexadecimal: [ 16, 'hex' ] + } +}); - pairBuffer = ''; - if (_result !== '') pairBuffer += ', '; - if (state.condenseFlow) pairBuffer += '"'; +/***/ }), - objectKey = objectKeyList[index]; - objectValue = object[objectKey]; +/***/ 86150: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (state.replacer) { - objectValue = state.replacer.call(object, objectKey, objectValue); - } +"use strict"; - if (!writeNode(state, level, objectKey, false, false)) { - continue; // Skip this pair because of invalid key; - } - if (state.dump.length > 1024) pairBuffer += '? '; +var Type = __nccwpck_require__(6073); - pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); +module.exports = new Type('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return data !== null ? data : {}; } +}); - if (!writeNode(state, level, objectValue, false, false)) { - continue; // Skip this pair because of invalid value. - } - pairBuffer += state.dump; +/***/ }), - // Both key and value are valid. - _result += pairBuffer; - } +/***/ 86104: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - state.tag = _tag; - state.dump = '{' + _result + '}'; +"use strict"; + + +var Type = __nccwpck_require__(6073); + +function resolveYamlMerge(data) { + return data === '<<' || data === null; } -function writeBlockMapping(state, level, object, compact) { - var _result = '', - _tag = state.tag, - objectKeyList = Object.keys(object), - index, - length, - objectKey, - objectValue, - explicitPair, - pairBuffer; +module.exports = new Type('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge +}); - // Allow sorting keys so that the output file is deterministic - if (state.sortKeys === true) { - // Default sorting - objectKeyList.sort(); - } else if (typeof state.sortKeys === 'function') { - // Custom sort function - objectKeyList.sort(state.sortKeys); - } else if (state.sortKeys) { - // Something is wrong - throw new YAMLException('sortKeys must be a boolean or a function'); - } - for (index = 0, length = objectKeyList.length; index < length; index += 1) { - pairBuffer = ''; +/***/ }), - if (!compact || _result !== '') { - pairBuffer += generateNextLine(state, level); - } +/***/ 20721: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - objectKey = objectKeyList[index]; - objectValue = object[objectKey]; +"use strict"; - if (state.replacer) { - objectValue = state.replacer.call(object, objectKey, objectValue); - } - if (!writeNode(state, level + 1, objectKey, true, true, true)) { - continue; // Skip this pair because of invalid key. - } +var Type = __nccwpck_require__(6073); - explicitPair = (state.tag !== null && state.tag !== '?') || - (state.dump && state.dump.length > 1024); +function resolveYamlNull(data) { + if (data === null) return true; - if (explicitPair) { - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - pairBuffer += '?'; - } else { - pairBuffer += '? '; - } - } + var max = data.length; - pairBuffer += state.dump; + return (max === 1 && data === '~') || + (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); +} - if (explicitPair) { - pairBuffer += generateNextLine(state, level); - } +function constructYamlNull() { + return null; +} - if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { - continue; // Skip this pair because of invalid value. - } +function isNull(object) { + return object === null; +} - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - pairBuffer += ':'; - } else { - pairBuffer += ': '; - } +module.exports = new Type('tag:yaml.org,2002:null', { + kind: 'scalar', + resolve: resolveYamlNull, + construct: constructYamlNull, + predicate: isNull, + represent: { + canonical: function () { return '~'; }, + lowercase: function () { return 'null'; }, + uppercase: function () { return 'NULL'; }, + camelcase: function () { return 'Null'; }, + empty: function () { return ''; } + }, + defaultStyle: 'lowercase' +}); - pairBuffer += state.dump; - // Both key and value are valid. - _result += pairBuffer; - } +/***/ }), - state.tag = _tag; - state.dump = _result || '{}'; // Empty mapping if no valid pairs. -} +/***/ 19046: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function detectType(state, object, explicit) { - var _result, typeList, index, length, type, style; +"use strict"; - typeList = explicit ? state.explicitTypes : state.implicitTypes; - for (index = 0, length = typeList.length; index < length; index += 1) { - type = typeList[index]; +var Type = __nccwpck_require__(6073); - if ((type.instanceOf || type.predicate) && - (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && - (!type.predicate || type.predicate(object))) { +var _hasOwnProperty = Object.prototype.hasOwnProperty; +var _toString = Object.prototype.toString; - if (explicit) { - if (type.multi && type.representName) { - state.tag = type.representName(object); - } else { - state.tag = type.tag; - } - } else { - state.tag = '?'; - } +function resolveYamlOmap(data) { + if (data === null) return true; - if (type.represent) { - style = state.styleMap[type.tag] || type.defaultStyle; + var objectKeys = [], index, length, pair, pairKey, pairHasKey, + object = data; - if (_toString.call(type.represent) === '[object Function]') { - _result = type.represent(object, style); - } else if (_hasOwnProperty.call(type.represent, style)) { - _result = type.represent[style](object, style); - } else { - throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); - } + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + pairHasKey = false; - state.dump = _result; - } + if (_toString.call(pair) !== '[object Object]') return false; - return true; + for (pairKey in pair) { + if (_hasOwnProperty.call(pair, pairKey)) { + if (!pairHasKey) pairHasKey = true; + else return false; + } } + + if (!pairHasKey) return false; + + if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); + else return false; } - return false; + return true; } -// Serializes `object` and writes it to global `result`. -// Returns true on success, or false on invalid object. -// -function writeNode(state, level, object, block, compact, iskey, isblockseq) { - state.tag = null; - state.dump = object; +function constructYamlOmap(data) { + return data !== null ? data : []; +} - if (!detectType(state, object, false)) { - detectType(state, object, true); - } +module.exports = new Type('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap, + construct: constructYamlOmap +}); - var type = _toString.call(state.dump); - var inblock = block; - var tagStr; - if (block) { - block = (state.flowLevel < 0 || state.flowLevel > level); - } +/***/ }), - var objectOrArray = type === '[object Object]' || type === '[object Array]', - duplicateIndex, - duplicate; +/***/ 96860: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (objectOrArray) { - duplicateIndex = state.duplicates.indexOf(object); - duplicate = duplicateIndex !== -1; - } +"use strict"; - if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { - compact = false; - } - if (duplicate && state.usedDuplicates[duplicateIndex]) { - state.dump = '*ref_' + duplicateIndex; - } else { - if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { - state.usedDuplicates[duplicateIndex] = true; - } - if (type === '[object Object]') { - if (block && (Object.keys(state.dump).length !== 0)) { - writeBlockMapping(state, level, state.dump, compact); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + state.dump; - } - } else { - writeFlowMapping(state, level, state.dump); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; - } - } - } else if (type === '[object Array]') { - if (block && (state.dump.length !== 0)) { - if (state.noArrayIndent && !isblockseq && level > 0) { - writeBlockSequence(state, level - 1, state.dump, compact); - } else { - writeBlockSequence(state, level, state.dump, compact); - } - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + state.dump; - } - } else { - writeFlowSequence(state, level, state.dump); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; - } - } - } else if (type === '[object String]') { - if (state.tag !== '?') { - writeScalar(state, state.dump, level, iskey, inblock); - } - } else if (type === '[object Undefined]') { - return false; - } else { - if (state.skipInvalid) return false; - throw new YAMLException('unacceptable kind of an object to dump ' + type); - } +var Type = __nccwpck_require__(6073); - if (state.tag !== null && state.tag !== '?') { - // Need to encode all characters except those allowed by the spec: - // - // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */ - // [36] ns-hex-digit ::= ns-dec-digit - // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */ - // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */ - // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-” - // [39] ns-uri-char ::= “%” ns-hex-digit ns-hex-digit | ns-word-char | “#” - // | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,” - // | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]” - // - // Also need to encode '!' because it has special meaning (end of tag prefix). - // - tagStr = encodeURI( - state.tag[0] === '!' ? state.tag.slice(1) : state.tag - ).replace(/!/g, '%21'); +var _toString = Object.prototype.toString; - if (state.tag[0] === '!') { - tagStr = '!' + tagStr; - } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') { - tagStr = '!!' + tagStr.slice(18); - } else { - tagStr = '!<' + tagStr + '>'; - } +function resolveYamlPairs(data) { + if (data === null) return true; - state.dump = tagStr + ' ' + state.dump; - } + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + if (_toString.call(pair) !== '[object Object]') return false; + + keys = Object.keys(pair); + + if (keys.length !== 1) return false; + + result[index] = [ keys[0], pair[keys[0]] ]; } return true; } -function getDuplicateReferences(object, state) { - var objects = [], - duplicatesIndexes = [], - index, - length; +function constructYamlPairs(data) { + if (data === null) return []; - inspectNode(object, objects, duplicatesIndexes); + var index, length, pair, keys, result, + object = data; - for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { - state.duplicates.push(objects[duplicatesIndexes[index]]); + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + keys = Object.keys(pair); + + result[index] = [ keys[0], pair[keys[0]] ]; } - state.usedDuplicates = new Array(length); + + return result; } -function inspectNode(object, objects, duplicatesIndexes) { - var objectKeyList, - index, - length; +module.exports = new Type('tag:yaml.org,2002:pairs', { + kind: 'sequence', + resolve: resolveYamlPairs, + construct: constructYamlPairs +}); - if (object !== null && typeof object === 'object') { - index = objects.indexOf(object); - if (index !== -1) { - if (duplicatesIndexes.indexOf(index) === -1) { - duplicatesIndexes.push(index); - } - } else { - objects.push(object); - if (Array.isArray(object)) { - for (index = 0, length = object.length; index < length; index += 1) { - inspectNode(object[index], objects, duplicatesIndexes); - } - } else { - objectKeyList = Object.keys(object); +/***/ }), - for (index = 0, length = objectKeyList.length; index < length; index += 1) { - inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); - } - } +/***/ 67283: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var Type = __nccwpck_require__(6073); + +module.exports = new Type('tag:yaml.org,2002:seq', { + kind: 'sequence', + construct: function (data) { return data !== null ? data : []; } +}); + + +/***/ }), + +/***/ 79548: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var Type = __nccwpck_require__(6073); + +var _hasOwnProperty = Object.prototype.hasOwnProperty; + +function resolveYamlSet(data) { + if (data === null) return true; + + var key, object = data; + + for (key in object) { + if (_hasOwnProperty.call(object, key)) { + if (object[key] !== null) return false; } } + + return true; } -function dump(input, options) { - options = options || {}; +function constructYamlSet(data) { + return data !== null ? data : {}; +} - var state = new State(options); +module.exports = new Type('tag:yaml.org,2002:set', { + kind: 'mapping', + resolve: resolveYamlSet, + construct: constructYamlSet +}); - if (!state.noRefs) getDuplicateReferences(input, state); - var value = input; +/***/ }), - if (state.replacer) { - value = state.replacer.call({ '': value }, '', value); - } +/***/ 23619: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (writeNode(state, 0, value, true, true)) return state.dump + '\n'; +"use strict"; - return ''; -} -module.exports.dump = dump; +var Type = __nccwpck_require__(6073); + +module.exports = new Type('tag:yaml.org,2002:str', { + kind: 'scalar', + construct: function (data) { return data !== null ? data : ''; } +}); /***/ }), -/***/ 68179: -/***/ ((module) => { +/***/ 99212: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -// YAML error class. http://stackoverflow.com/questions/8458984 -// +var Type = __nccwpck_require__(6073); -function formatError(exception, compact) { - var where = '', message = exception.reason || '(unknown reason)'; +var YAML_DATE_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9])' + // [2] month + '-([0-9][0-9])$'); // [3] day - if (!exception.mark) return message; +var YAML_TIMESTAMP_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9]?)' + // [2] month + '-([0-9][0-9]?)' + // [3] day + '(?:[Tt]|[ \\t]+)' + // ... + '([0-9][0-9]?)' + // [4] hour + ':([0-9][0-9])' + // [5] minute + ':([0-9][0-9])' + // [6] second + '(?:\\.([0-9]*))?' + // [7] fraction + '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour + '(?::([0-9][0-9]))?))?$'); // [11] tz_minute - if (exception.mark.name) { - where += 'in "' + exception.mark.name + '" '; - } +function resolveYamlTimestamp(data) { + if (data === null) return false; + if (YAML_DATE_REGEXP.exec(data) !== null) return true; + if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; + return false; +} - where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')'; +function constructYamlTimestamp(data) { + var match, year, month, day, hour, minute, second, fraction = 0, + delta = null, tz_hour, tz_minute, date; - if (!compact && exception.mark.snippet) { - where += '\n\n' + exception.mark.snippet; + match = YAML_DATE_REGEXP.exec(data); + if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); + + if (match === null) throw new Error('Date resolve error'); + + // match: [1] year [2] month [3] day + + year = +(match[1]); + month = +(match[2]) - 1; // JS month starts with 0 + day = +(match[3]); + + if (!match[4]) { // no hour + return new Date(Date.UTC(year, month, day)); } - return message + ' ' + where; -} + // match: [4] hour [5] minute [6] second [7] fraction + hour = +(match[4]); + minute = +(match[5]); + second = +(match[6]); -function YAMLException(reason, mark) { - // Super constructor - Error.call(this); + if (match[7]) { + fraction = match[7].slice(0, 3); + while (fraction.length < 3) { // milli-seconds + fraction += '0'; + } + fraction = +fraction; + } - this.name = 'YAMLException'; - this.reason = reason; - this.mark = mark; - this.message = formatError(this, false); + // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute - // Include stack trace in error object - if (Error.captureStackTrace) { - // Chrome and NodeJS - Error.captureStackTrace(this, this.constructor); - } else { - // FF, IE 10+ and Safari 6+. Fallback for others - this.stack = (new Error()).stack || ''; + if (match[9]) { + tz_hour = +(match[10]); + tz_minute = +(match[11] || 0); + delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds + if (match[9] === '-') delta = -delta; } + + date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); + + if (delta) date.setTime(date.getTime() - delta); + + return date; } +function representYamlTimestamp(object /*, style*/) { + return object.toISOString(); +} -// Inherit from Error -YAMLException.prototype = Object.create(Error.prototype); -YAMLException.prototype.constructor = YAMLException; +module.exports = new Type('tag:yaml.org,2002:timestamp', { + kind: 'scalar', + resolve: resolveYamlTimestamp, + construct: constructYamlTimestamp, + instanceOf: Date, + represent: representYamlTimestamp +}); -YAMLException.prototype.toString = function toString(compact) { - return this.name + ': ' + formatError(this, compact); -}; +/***/ }), + +/***/ 85587: +/***/ (function(module, exports) { +(function(){ -module.exports = YAMLException; + // 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; + } + + BigInteger.prototype.DB = dbits; + BigInteger.prototype.DM = ((1<= 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; + } + 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)< { + // (protected) clamp off excess high words + function bnpClamp() { + var c = this.s&this.DM; + while(this.t > 0 && this[this.t-1] == c) --this.t; + } -"use strict"; + // (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; } -/*eslint-disable max-len,no-use-before-define*/ + // (public) |this| + function bnAbs() { return (this.s<0)?this.negate():this; } -var common = __nccwpck_require__(26829); -var YAMLException = __nccwpck_require__(68179); -var makeSnippet = __nccwpck_require__(96975); -var DEFAULT_SCHEMA = __nccwpck_require__(18759); + // (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; + } -var _hasOwnProperty = Object.prototype.hasOwnProperty; + // (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)); + } + // (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; + } -var CONTEXT_FLOW_IN = 1; -var CONTEXT_FLOW_OUT = 2; -var CONTEXT_BLOCK_IN = 3; -var CONTEXT_BLOCK_OUT = 4; + // (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; + } + // (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(); + } -var CHOMPING_CLIP = 1; -var CHOMPING_STRIP = 2; -var CHOMPING_KEEP = 3; + // (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(); + } -var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; -var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; -var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; -var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; -var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; + // (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); + } + // (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(); + } -function _class(obj) { return Object.prototype.toString.call(obj); } + // (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); + } -function is_EOL(c) { - return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); -} + // (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; + } -function is_WHITE_SPACE(c) { - return (c === 0x09/* Tab */) || (c === 0x20/* Space */); -} + // 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); } -function is_WS_OR_EOL(c) { - return (c === 0x09/* Tab */) || - (c === 0x20/* Space */) || - (c === 0x0A/* LF */) || - (c === 0x0D/* CR */); -} + Classic.prototype.convert = cConvert; + Classic.prototype.revert = cRevert; + Classic.prototype.reduce = cReduce; + Classic.prototype.mulTo = cMulTo; + Classic.prototype.sqrTo = cSqrTo; -function is_FLOW_INDICATOR(c) { - return c === 0x2C/* , */ || - c === 0x5B/* [ */ || - c === 0x5D/* ] */ || - c === 0x7B/* { */ || - c === 0x7D/* } */; -} + // (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; + } -function fromHexCode(c) { - var lc; + // 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 ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { - return c - 0x30; - } + // 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; + } - /*eslint-disable no-bitwise*/ - lc = c | 0x20; + // x/R mod m + function montRevert(x) { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; + } - if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { - return lc - 0x61 + 10; - } + // 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 -1; -} + // r = "x^2/R mod m"; x != r + function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); } -function escapedHexLen(c) { - if (c === 0x78/* x */) { return 2; } - if (c === 0x75/* u */) { return 4; } - if (c === 0x55/* U */) { return 8; } - return 0; -} + // r = "xy/R mod m"; x,y != r + function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } -function fromDecimalCode(c) { - if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { - return c - 0x30; - } + Montgomery.prototype.convert = montConvert; + Montgomery.prototype.revert = montRevert; + Montgomery.prototype.reduce = montReduce; + Montgomery.prototype.mulTo = montMulTo; + Montgomery.prototype.sqrTo = montSqrTo; - return -1; -} + // (protected) true iff this is even + function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; } -function simpleEscapeSequence(c) { - /* eslint-disable indent */ - return (c === 0x30/* 0 */) ? '\x00' : - (c === 0x61/* a */) ? '\x07' : - (c === 0x62/* b */) ? '\x08' : - (c === 0x74/* t */) ? '\x09' : - (c === 0x09/* Tab */) ? '\x09' : - (c === 0x6E/* n */) ? '\x0A' : - (c === 0x76/* v */) ? '\x0B' : - (c === 0x66/* f */) ? '\x0C' : - (c === 0x72/* r */) ? '\x0D' : - (c === 0x65/* e */) ? '\x1B' : - (c === 0x20/* Space */) ? ' ' : - (c === 0x22/* " */) ? '\x22' : - (c === 0x2F/* / */) ? '/' : - (c === 0x5C/* \ */) ? '\x5C' : - (c === 0x4E/* N */) ? '\x85' : - (c === 0x5F/* _ */) ? '\xA0' : - (c === 0x4C/* L */) ? '\u2028' : - (c === 0x50/* P */) ? '\u2029' : ''; -} + // (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); + } -function charFromCodepoint(c) { - if (c <= 0xFFFF) { - return String.fromCharCode(c); - } - // Encode UTF-16 surrogate pair - // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF - return String.fromCharCode( - ((c - 0x010000) >> 10) + 0xD800, - ((c - 0x010000) & 0x03FF) + 0xDC00 - ); -} + // (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); + } -var simpleEscapeCheck = new Array(256); // integer, for fast access -var simpleEscapeMap = new Array(256); -for (var i = 0; i < 256; i++) { - simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; - simpleEscapeMap[i] = simpleEscapeSequence(i); -} + // 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; -function State(input, options) { - this.input = input; + // "constants" + BigInteger.ZERO = nbv(0); + BigInteger.ONE = nbv(1); - this.filename = options['filename'] || null; - this.schema = options['schema'] || DEFAULT_SCHEMA; - this.onWarning = options['onWarning'] || null; - // (Hidden) Remove? makes the loader to expect YAML 1.1 documents - // if such documents have no explicit %YAML directive - this.legacy = options['legacy'] || false; + // Copyright (c) 2005-2009 Tom Wu + // All Rights Reserved. + // See "LICENSE" for details. - this.json = options['json'] || false; - this.listener = options['listener'] || null; + // Extended JavaScript BN functions, required for RSA private ops. - this.implicitTypes = this.schema.compiledImplicit; - this.typeMap = this.schema.compiledTypeMap; + // Version 1.1: new BigInteger("0", 10) returns "proper" zero + // Version 1.2: square() API, isProbablePrime fix - this.length = input.length; - this.position = 0; - this.line = 0; - this.lineStart = 0; - this.lineIndent = 0; + // (public) + function bnClone() { var r = nbi(); this.copyTo(r); return r; } - // position of first leading tab in the current line, - // used to make sure there are no tabs in the indentation - this.firstTabInLine = -1; + // (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; } - /* - this.version; - this.checkLineBreaks; - this.tagMap; - this.anchorMap; - this.tag; - this.anchor; - this.kind; - this.result;*/ + // (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)); } + // (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; + } -function generateError(state, message) { - var mark = { - name: state.filename, - buffer: state.input.slice(0, -1), // omit trailing \0 - position: state.position, - line: state.line, - column: state.position - state.lineStart - }; + // (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; + } - mark.snippet = makeSnippet(mark); + // (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); + } - return new YAMLException(message, mark); -} + // (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 r; + } -function throwWarning(state, message) { - if (state.onWarning) { - state.onWarning.call(null, generateError(state, message)); - } -} + 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(); + } -var directiveHandlers = { + // (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; } - YAML: function handleYamlDirective(state, name, args) { + // (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; } - var match, major, minor; + // (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; } - if (state.version !== null) { - throwError(state, 'duplication of %YAML directive'); - } + // (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; } - if (args.length !== 1) { - throwError(state, 'YAML directive accepts exactly one argument'); + // (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; } - match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); - - if (match === null) { - throwError(state, 'ill-formed argument of the YAML directive'); + // (public) this << n + function bnShiftLeft(n) { + var r = nbi(); + if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); + return r; } - major = parseInt(match[1], 10); - minor = parseInt(match[2], 10); - - if (major !== 1) { - throwError(state, 'unacceptable YAML version of the document'); + // (public) this >> n + function bnShiftRight(n) { + var r = nbi(); + if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); + return r; } - state.version = args[0]; - state.checkLineBreaks = (minor < 2); - - if (minor !== 1 && minor !== 2) { - throwWarning(state, 'unsupported YAML version of the document'); + // 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; } - }, - - TAG: function handleTagDirective(state, name, args) { - - var handle, prefix; - if (args.length !== 2) { - throwError(state, 'TAG directive accepts exactly two arguments'); + // (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; } - handle = args[0]; - prefix = args[1]; - - if (!PATTERN_TAG_HANDLE.test(handle)) { - throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); + // return number of 1 bits in x + function cbit(x) { + var r = 0; + while(x != 0) { x &= x-1; ++r; } + return r; } - if (_hasOwnProperty.call(state.tagMap, handle)) { - throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + // (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 (!PATTERN_TAG_URI.test(prefix)) { - throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + // (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); } - try { - prefix = decodeURIComponent(prefix); - } catch (err) { - throwError(state, 'tag prefix is malformed: ' + prefix); + // (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 if (PATTERN_NON_PRINTABLE.test(_result)) { - throwError(state, 'the stream contains non-printable characters'); + 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(); } - state.result += _result; - } -} - -function mergeMappings(state, destination, source, overridableKeys) { - var sourceKeys, key, index, quantity; - - if (!common.isObject(source)) { - throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); - } + // (public) this + a + function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } - sourceKeys = Object.keys(source); + // (public) this - a + function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } - for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { - key = sourceKeys[index]; + // (public) this * a + function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } - if (!_hasOwnProperty.call(destination, key)) { - destination[key] = source[key]; - overridableKeys[key] = true; - } - } -} + // (public) this^2 + function bnSquare() { var r = nbi(); this.squareTo(r); return r; } -function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, - startLine, startLineStart, startPos) { + // (public) this / a + function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } - var index, quantity; + // (public) this % a + function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } - // The output is a plain object here, so keys can only be strings. - // We need to convert keyNode to a string, but doing so can hang the process - // (deeply nested arrays that explode exponentially using aliases). - if (Array.isArray(keyNode)) { - keyNode = Array.prototype.slice.call(keyNode); + // (public) [this/a,this%a] + function bnDivideAndRemainder(a) { + var q = nbi(), r = nbi(); + this.divRemTo(a,q,r); + return new Array(q,r); + } - for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { - if (Array.isArray(keyNode[index])) { - throwError(state, 'nested arrays are not supported inside keys'); - } + // (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(); + } - if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { - keyNode[index] = '[object Object]'; + // (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]; } } - } - // Avoid code execution in load() via toString property - // (still use its own toString for arrays, timestamps, - // and whatever user schema extensions happen to have @@toStringTag) - if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { - keyNode = '[object Object]'; - } + // 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()); } - keyNode = String(keyNode); + // (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(); + } - if (_result === null) { - _result = {}; - } + // (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 (keyTag === 'tag:yaml.org,2002:merge') { - if (Array.isArray(valueNode)) { - for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { - mergeMappings(state, _result, valueNode[index], overridableKeys); - } - } else { - mergeMappings(state, _result, valueNode, overridableKeys); + // 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; } - } else { - if (!state.json && - !_hasOwnProperty.call(overridableKeys, keyNode) && - _hasOwnProperty.call(_result, keyNode)) { - state.line = startLine || state.line; - state.lineStart = startLineStart || state.lineStart; - state.position = startPos || state.position; - throwError(state, 'duplicated mapping key'); + + 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; } } - // used for this specific key only because Object.defineProperty is slow - if (keyNode === '__proto__') { - Object.defineProperty(_result, keyNode, { - configurable: true, - enumerable: true, - writable: true, - value: valueNode - }); - } else { - _result[keyNode] = valueNode; + 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); } - delete overridableKeys[keyNode]; - } - return _result; -} + // r = x^2 mod m; x != r + function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } -function readLineBreak(state) { - var ch; + // 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; + } + } + + 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); + } - ch = state.input.charCodeAt(state.position); + 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); + } - if (ch === 0x0A/* LF */) { - state.position++; - } else if (ch === 0x0D/* CR */) { - state.position++; - if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { - state.position++; + while(j >= 0 && (e[j]&(1< 0) { + x.rShiftTo(g,x); + y.rShiftTo(g,y); } - ch = state.input.charCodeAt(++state.position); + 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 (allowComments && ch === 0x23/* # */) { - do { - ch = state.input.charCodeAt(++state.position); - } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); + // (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 (is_EOL(ch)) { - readLineBreak(state); + // (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(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; + } - ch = state.input.charCodeAt(state.position); - lineBreaks++; - state.lineIndent = 0; + 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]; - while (ch === 0x20/* Space */) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); + // (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; } - } else { - break; + 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); } - } - if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { - throwWarning(state, 'deficient indentation'); - } - - return lineBreaks; -} + // (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; + } -function testDocumentSeparator(state) { - var _position = state.position, - ch; + // 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; - ch = state.input.charCodeAt(_position); + // 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; - // Condition state.position === state.lineStart is tested - // in parent on each call, for efficiency. No needs to test here again. - if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && - ch === state.input.charCodeAt(_position + 1) && - ch === state.input.charCodeAt(_position + 2)) { + // JSBN-specific extension + BigInteger.prototype.square = bnSquare; - _position += 3; + // Expose the Barrett function + BigInteger.prototype.Barrett = Barrett - ch = state.input.charCodeAt(_position); + // BigInteger interfaces not implemented in jsbn: - if (ch === 0 || is_WS_OR_EOL(ch)) { - return true; - } - } + // BigInteger(int signum, byte[] magnitude) + // double doubleValue() + // float floatValue() + // int hashCode() + // long longValue() + // static BigInteger valueOf(long val) - return false; -} + // Random number generator - requires a PRNG backend, e.g. prng4.js -function writeFoldedLines(state, count) { - if (count === 1) { - state.result += ' '; - } else if (count > 1) { - state.result += common.repeat('\n', count - 1); - } -} + // For best results, put code like + // + // in your main HTML document. + var rng_state; + var rng_pool; + var rng_pptr; -function readPlainScalar(state, nodeIndent, withinFlowCollection) { - var preceding, - following, - captureStart, - captureEnd, - hasPendingContent, - _line, - _lineStart, - _lineIndent, - _kind = state.kind, - _result = state.result, - ch; + // 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; + } - ch = state.input.charCodeAt(state.position); + // Mix in the current time (w/milliseconds) into the pool + function rng_seed_time() { + rng_seed_int(new Date().getTime()); + } - if (is_WS_OR_EOL(ch) || - is_FLOW_INDICATOR(ch) || - ch === 0x23/* # */ || - ch === 0x26/* & */ || - ch === 0x2A/* * */ || - ch === 0x21/* ! */ || - ch === 0x7C/* | */ || - ch === 0x3E/* > */ || - ch === 0x27/* ' */ || - ch === 0x22/* " */ || - ch === 0x25/* % */ || - ch === 0x40/* @ */ || - ch === 0x60/* ` */) { - return false; - } + // 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 (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { - following = state.input.charCodeAt(state.position + 1); + 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(); + } - if (is_WS_OR_EOL(following) || - withinFlowCollection && is_FLOW_INDICATOR(following)) { - return false; - } - } + function rng_get_bytes(ba) { + var i; + for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte(); + } - state.kind = 'scalar'; - state.result = ''; - captureStart = captureEnd = state.position; - hasPendingContent = false; + function SecureRandom() {} - while (ch !== 0) { - if (ch === 0x3A/* : */) { - following = state.input.charCodeAt(state.position + 1); + SecureRandom.prototype.nextBytes = rng_get_bytes; - if (is_WS_OR_EOL(following) || - withinFlowCollection && is_FLOW_INDICATOR(following)) { - break; - } + // prng4.js - uses Arcfour as a PRNG - } else if (ch === 0x23/* # */) { - preceding = state.input.charCodeAt(state.position - 1); + function Arcfour() { + this.i = 0; + this.j = 0; + this.S = new Array(); + } - if (is_WS_OR_EOL(preceding)) { - break; - } + // 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; + } - } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || - withinFlowCollection && is_FLOW_INDICATOR(ch)) { - break; + 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]; + } - } else if (is_EOL(ch)) { - _line = state.line; - _lineStart = state.lineStart; - _lineIndent = state.lineIndent; - skipSeparationSpace(state, false, -1); + Arcfour.prototype.init = ARC4init; + Arcfour.prototype.next = ARC4next; - if (state.lineIndent >= nodeIndent) { - hasPendingContent = true; - ch = state.input.charCodeAt(state.position); - continue; - } else { - state.position = captureEnd; - state.line = _line; - state.lineStart = _lineStart; - state.lineIndent = _lineIndent; - break; - } - } + // Plug in your RNG constructor here + function prng_newstate() { + return new Arcfour(); + } - if (hasPendingContent) { - captureSegment(state, captureStart, captureEnd, false); - writeFoldedLines(state, state.line - _line); - captureStart = captureEnd = state.position; - hasPendingContent = false; - } + // 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; - if (!is_WHITE_SPACE(ch)) { - captureEnd = state.position + 1; - } + BigInteger.SecureRandom = SecureRandom; + BigInteger.BigInteger = BigInteger; + if (true) { + exports = module.exports = BigInteger; + } else {} - ch = state.input.charCodeAt(++state.position); - } +}).call(this); - captureSegment(state, captureStart, captureEnd, false); - if (state.result) { - return true; - } +/***/ }), - state.kind = _kind; - state.result = _result; - return false; -} +/***/ 22820: +/***/ ((__unused_webpack_module, exports) => { -function readSingleQuotedScalar(state, nodeIndent) { - var ch, - captureStart, captureEnd; +//TODO: handle reviver/dehydrate function like normal +//and handle indentation, like normal. +//if anyone needs this... please send pull request. - ch = state.input.charCodeAt(state.position); +exports.stringify = function stringify (o) { + if('undefined' == typeof o) return o - if (ch !== 0x27/* ' */) { - return false; - } + if(o && Buffer.isBuffer(o)) + return JSON.stringify(':base64:' + o.toString('base64')) - state.kind = 'scalar'; - state.result = ''; - state.position++; - captureStart = captureEnd = state.position; + if(o && o.toJSON) + o = o.toJSON() - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 0x27/* ' */) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); + if(o && 'object' === typeof o) { + var s = '' + var array = Array.isArray(o) + s = array ? '[' : '{' + var first = true - if (ch === 0x27/* ' */) { - captureStart = state.position; - state.position++; - captureEnd = state.position; - } else { - return true; + for(var k in o) { + var ignore = 'function' == typeof o[k] || (!array && 'undefined' === typeof o[k]) + if(Object.hasOwnProperty.call(o, k) && !ignore) { + if(!first) + s += ',' + first = false + if (array) { + if(o[k] == undefined) + s += 'null' + else + s += stringify(o[k]) + } else if (o[k] !== void(0)) { + s += stringify(k) + ':' + stringify(o[k]) + } } + } - } else if (is_EOL(ch)) { - captureSegment(state, captureStart, captureEnd, true); - writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); - captureStart = captureEnd = state.position; + s += array ? ']' : '}' - } else if (state.position === state.lineStart && testDocumentSeparator(state)) { - throwError(state, 'unexpected end of the document within a single quoted scalar'); + return s + } else if ('string' === typeof o) { + return JSON.stringify(/^:/.test(o) ? ':' + o : o) + } else if ('undefined' === typeof o) { + return 'null'; + } else + return JSON.stringify(o) +} - } else { - state.position++; - captureEnd = state.position; +exports.parse = function (s) { + return JSON.parse(s, function (key, value) { + if('string' === typeof value) { + if(/^:base64:/.test(value)) + return Buffer.from(value.substring(8), 'base64') + else + return /^:/.test(value) ? value.substring(1) : value } - } - - throwError(state, 'unexpected end of the stream within a single quoted scalar'); + return value + }) } -function readDoubleQuotedScalar(state, nodeIndent) { - var captureStart, - captureEnd, - hexLength, - hexResult, - tmp, - ch; - ch = state.input.charCodeAt(state.position); +/***/ }), - if (ch !== 0x22/* " */) { - return false; - } +/***/ 52533: +/***/ ((module) => { - state.kind = 'scalar'; - state.result = ''; - state.position++; - captureStart = captureEnd = state.position; +"use strict"; - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 0x22/* " */) { - captureSegment(state, captureStart, state.position, true); - state.position++; - return true; - } else if (ch === 0x5C/* \ */) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); +var traverse = module.exports = function (schema, opts, cb) { + // Legacy support for v0.3.1 and earlier. + if (typeof opts == 'function') { + cb = opts; + opts = {}; + } - if (is_EOL(ch)) { - skipSeparationSpace(state, false, nodeIndent); + cb = opts.cb || cb; + var pre = (typeof cb == 'function') ? cb : cb.pre || function() {}; + var post = cb.post || function() {}; - // TODO: rework to inline fn with no type cast? - } else if (ch < 256 && simpleEscapeCheck[ch]) { - state.result += simpleEscapeMap[ch]; - state.position++; + _traverse(opts, pre, post, schema, '', schema); +}; - } else if ((tmp = escapedHexLen(ch)) > 0) { - hexLength = tmp; - hexResult = 0; - for (; hexLength > 0; hexLength--) { - ch = state.input.charCodeAt(++state.position); +traverse.keywords = { + additionalItems: true, + items: true, + contains: true, + additionalProperties: true, + propertyNames: true, + not: true +}; - if ((tmp = fromHexCode(ch)) >= 0) { - hexResult = (hexResult << 4) + tmp; +traverse.arrayKeywords = { + items: true, + allOf: true, + anyOf: true, + oneOf: true +}; - } else { - throwError(state, 'expected hexadecimal character'); - } - } +traverse.propsKeywords = { + definitions: true, + properties: true, + patternProperties: true, + dependencies: true +}; - state.result += charFromCodepoint(hexResult); +traverse.skipKeywords = { + default: true, + enum: true, + const: true, + required: true, + maximum: true, + minimum: true, + exclusiveMaximum: true, + exclusiveMinimum: true, + multipleOf: true, + maxLength: true, + minLength: true, + pattern: true, + format: true, + maxItems: true, + minItems: true, + uniqueItems: true, + maxProperties: true, + minProperties: true +}; - state.position++; - } else { - throwError(state, 'unknown escape sequence'); +function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (schema && typeof schema == 'object' && !Array.isArray(schema)) { + pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + for (var key in schema) { + var sch = schema[key]; + if (Array.isArray(sch)) { + if (key in traverse.arrayKeywords) { + for (var i=0; i schema.maxItems){ + addError("There must be a maximum of " + schema.maxItems + " in the array"); + } + }else if(schema.properties || schema.additionalProperties){ + errors.concat(checkObj(value, schema.properties, path, schema.additionalProperties)); + } + if(schema.pattern && typeof value == 'string' && !value.match(schema.pattern)){ + addError("does not match the regex pattern " + schema.pattern); + } + if(schema.maxLength && typeof value == 'string' && value.length > schema.maxLength){ + addError("may only be " + schema.maxLength + " characters long"); + } + if(schema.minLength && typeof value == 'string' && value.length < schema.minLength){ + addError("must be at least " + schema.minLength + " characters long"); + } + if(typeof schema.minimum !== 'undefined' && typeof value == typeof schema.minimum && + schema.minimum > value){ + addError("must have a minimum value of " + schema.minimum); + } + if(typeof schema.maximum !== 'undefined' && typeof value == typeof schema.maximum && + schema.maximum < value){ + addError("must have a maximum value of " + schema.maximum); + } + if(schema['enum']){ + var enumer = schema['enum']; + l = enumer.length; + var found; + for(var j = 0; j < l; j++){ + if(enumer[j]===value){ + found=1; + break; + } + } + if(!found){ + addError("does not have a value in the enumeration " + enumer.join(", ")); + } + } + if(typeof schema.maxDecimal == 'number' && + (value.toString().match(new RegExp("\\.[0-9]{" + (schema.maxDecimal + 1) + ",}")))){ + addError("may only have " + schema.maxDecimal + " digits of decimal places"); + } + } + } + return null; + } + // validate an object against a schema + function checkObj(instance,objTypeDef,path,additionalProp){ - if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { - isPair = true; - ch = state.input.charCodeAt(++state.position); - skipSeparationSpace(state, true, nodeIndent); - composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); - valueNode = state.result; - } + if(typeof objTypeDef =='object'){ + if(typeof instance != 'object' || instance instanceof Array){ + errors.push({property:path,message:"an object is required"}); + } + + for(var i in objTypeDef){ + if(objTypeDef.hasOwnProperty(i) && i != '__proto__' && i != 'constructor'){ + var value = instance.hasOwnProperty(i) ? instance[i] : undefined; + // skip _not_ specified properties + if (value === undefined && options.existingOnly) continue; + var propDef = objTypeDef[i]; + // set default + if(value === undefined && propDef["default"]){ + value = instance[i] = propDef["default"]; + } + if(options.coerce && i in instance){ + value = instance[i] = options.coerce(value, propDef); + } + checkProp(value,propDef,path,i); + } + } + } + for(i in instance){ + if(instance.hasOwnProperty(i) && !(i.charAt(0) == '_' && i.charAt(1) == '_') && objTypeDef && !objTypeDef[i] && additionalProp===false){ + if (options.filter) { + delete instance[i]; + continue; + } else { + errors.push({property:path,message:"The property " + i + + " is not defined in the schema and the schema does not allow additional properties"}); + } + } + var requires = objTypeDef && objTypeDef[i] && objTypeDef[i].requires; + if(requires && !(requires in instance)){ + errors.push({property:path,message:"the presence of the property " + i + " requires that " + requires + " also be present"}); + } + value = instance[i]; + if(additionalProp && (!(objTypeDef && typeof objTypeDef == 'object') || !(i in objTypeDef))){ + if(options.coerce){ + value = instance[i] = options.coerce(value, additionalProp); + } + checkProp(value,additionalProp,path,i); + } + if(!_changing && value && value.$schema){ + errors = errors.concat(checkProp(value,value.$schema,path,i)); + } + } + return errors; + } + if(schema){ + checkProp(instance,schema,'',_changing || ''); + } + if(!_changing && instance && instance.$schema){ + checkProp(instance,instance.$schema,'',''); + } + return {valid:!errors.length,errors:errors}; +}; +exports.mustBeValid = function(result){ + // summary: + // This checks to ensure that the result is valid and will throw an appropriate error message if it is not + // result: the result returned from checkPropertyChange or validate + if(!result.valid){ + throw new TypeError(result.errors.map(function(error){return "for property " + error.property + ': ' + error.message;}).join(", \n")); + } +} - if (isMapping) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); - } else if (isPair) { - _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); - } else { - _result.push(keyNode); - } +return exports; +})); - skipSeparationSpace(state, true, nodeIndent); - ch = state.input.charCodeAt(state.position); +/***/ }), - if (ch === 0x2C/* , */) { - readNext = true; - ch = state.input.charCodeAt(++state.position); - } else { - readNext = false; - } - } +/***/ 57073: +/***/ ((module, exports) => { - throwError(state, 'unexpected end of the stream within a flow collection'); +exports = module.exports = stringify +exports.getSerialize = serializer + +function stringify(obj, replacer, spaces, cycleReplacer) { + return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces) } -function readBlockScalar(state, nodeIndent) { - var captureStart, - folding, - chomping = CHOMPING_CLIP, - didReadContent = false, - detectedIndent = false, - textIndent = nodeIndent, - emptyLines = 0, - atMoreIndented = false, - tmp, - ch; +function serializer(replacer, cycleReplacer) { + var stack = [], keys = [] - ch = state.input.charCodeAt(state.position); + if (cycleReplacer == null) cycleReplacer = function(key, value) { + if (stack[0] === value) return "[Circular ~]" + return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]" + } - if (ch === 0x7C/* | */) { - folding = false; - } else if (ch === 0x3E/* > */) { - folding = true; - } else { - return false; + return function(key, value) { + if (stack.length > 0) { + var thisPos = stack.indexOf(this) + ~thisPos ? stack.splice(thisPos + 1) : stack.push(this) + ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key) + if (~stack.indexOf(value)) value = cycleReplacer.call(this, key, value) + } + else stack.push(value) + + return replacer == null ? value : replacer.call(this, key, value) } +} - state.kind = 'scalar'; - state.result = ''; - while (ch !== 0) { - ch = state.input.charCodeAt(++state.position); +/***/ }), - if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { - if (CHOMPING_CLIP === chomping) { - chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; - } else { - throwError(state, 'repeat of a chomping mode identifier'); - } +/***/ 63269: +/***/ (function(module, exports, __nccwpck_require__) { - } else if ((tmp = fromDecimalCode(ch)) >= 0) { - if (tmp === 0) { - throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); - } else if (!detectedIndent) { - textIndent = nodeIndent + tmp - 1; - detectedIndent = true; - } else { - throwError(state, 'repeat of an indentation width identifier'); - } +(function (global, factory) { + true ? factory(exports) : + 0; +}(this, function (exports) { 'use strict'; + function _typeof(obj) { + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof = function (obj) { + return typeof obj; + }; } else { - break; + _typeof = function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; } + + return _typeof(obj); } - if (is_WHITE_SPACE(ch)) { - do { ch = state.input.charCodeAt(++state.position); } - while (is_WHITE_SPACE(ch)); + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - if (ch === 0x23/* # */) { - do { ch = state.input.charCodeAt(++state.position); } - while (!is_EOL(ch) && (ch !== 0)); + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function"); } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true + } + }); + if (superClass) _setPrototypeOf(subClass, superClass); } - while (ch !== 0) { - readLineBreak(state); - state.lineIndent = 0; + function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + return _getPrototypeOf(o); + } - ch = state.input.charCodeAt(state.position); + function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; - while ((!detectedIndent || state.lineIndent < textIndent) && - (ch === 0x20/* Space */)) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); - } + return _setPrototypeOf(o, p); + } - if (!detectedIndent && state.lineIndent > textIndent) { - textIndent = state.lineIndent; + function isNativeReflectConstruct() { + if (typeof Reflect === "undefined" || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === "function") return true; + + try { + Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); + return true; + } catch (e) { + return false; } + } - if (is_EOL(ch)) { - emptyLines++; - continue; + function _construct(Parent, args, Class) { + if (isNativeReflectConstruct()) { + _construct = Reflect.construct; + } else { + _construct = function _construct(Parent, args, Class) { + var a = [null]; + a.push.apply(a, args); + var Constructor = Function.bind.apply(Parent, a); + var instance = new Constructor(); + if (Class) _setPrototypeOf(instance, Class.prototype); + return instance; + }; } - // End of the scalar. - if (state.lineIndent < textIndent) { + return _construct.apply(null, arguments); + } - // Perform the chomping. - if (chomping === CHOMPING_KEEP) { - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - } else if (chomping === CHOMPING_CLIP) { - if (didReadContent) { // i.e. only if the scalar is not empty. - state.result += '\n'; - } - } + function _isNativeFunction(fn) { + return Function.toString.call(fn).indexOf("[native code]") !== -1; + } - // Break this `while` cycle and go to the funciton's epilogue. - break; - } + function _wrapNativeSuper(Class) { + var _cache = typeof Map === "function" ? new Map() : undefined; - // Folded style: use fancy rules to handle line breaks. - if (folding) { + _wrapNativeSuper = function _wrapNativeSuper(Class) { + if (Class === null || !_isNativeFunction(Class)) return Class; - // Lines starting with white space characters (more-indented lines) are not folded. - if (is_WHITE_SPACE(ch)) { - atMoreIndented = true; - // except for the first content line (cf. Example 8.1) - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + if (typeof Class !== "function") { + throw new TypeError("Super expression must either be null or a function"); + } - // End of more-indented block. - } else if (atMoreIndented) { - atMoreIndented = false; - state.result += common.repeat('\n', emptyLines + 1); + if (typeof _cache !== "undefined") { + if (_cache.has(Class)) return _cache.get(Class); - // Just one line break - perceive as the same line. - } else if (emptyLines === 0) { - if (didReadContent) { // i.e. only if we have already read some scalar content. - state.result += ' '; - } + _cache.set(Class, Wrapper); + } - // Several line breaks - perceive as different lines. - } else { - state.result += common.repeat('\n', emptyLines); + function Wrapper() { + return _construct(Class, arguments, _getPrototypeOf(this).constructor); } - // Literal style: just add exact number of line breaks between content lines. - } else { - // Keep all line breaks except the header line break. - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - } + Wrapper.prototype = Object.create(Class.prototype, { + constructor: { + value: Wrapper, + enumerable: false, + writable: true, + configurable: true + } + }); + return _setPrototypeOf(Wrapper, Class); + }; - didReadContent = true; - detectedIndent = true; - emptyLines = 0; - captureStart = state.position; + return _wrapNativeSuper(Class); + } - while (!is_EOL(ch) && (ch !== 0)) { - ch = state.input.charCodeAt(++state.position); + function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } - captureSegment(state, captureStart, state.position, false); + return self; } - return true; -} - -function readBlockSequence(state, nodeIndent) { - var _line, - _tag = state.tag, - _anchor = state.anchor, - _result = [], - following, - detected = false, - ch; - - // there is a leading tab before this token, so it can't be a block sequence/mapping; - // it can still be flow sequence/mapping or a scalar - if (state.firstTabInLine !== -1) return false; + function _possibleConstructorReturn(self, call) { + if (call && (typeof call === "object" || typeof call === "function")) { + return call; + } - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; + return _assertThisInitialized(self); } - ch = state.input.charCodeAt(state.position); - - while (ch !== 0) { - if (state.firstTabInLine !== -1) { - state.position = state.firstTabInLine; - throwError(state, 'tab characters must not be used in indentation'); - } - - if (ch !== 0x2D/* - */) { - break; - } + /* eslint-disable no-eval */ + var globalEval = eval; // eslint-disable-next-line import/no-commonjs - following = state.input.charCodeAt(state.position + 1); + var supportsNodeVM = true && Boolean(module.exports) && !(typeof navigator !== 'undefined' && navigator.product === 'ReactNative'); + var allowedResultTypes = ['value', 'path', 'pointer', 'parent', 'parentProperty', 'all']; + var hasOwnProp = Object.prototype.hasOwnProperty; + /** + * Copy items out of one array into another. + * @param {Array} source Array with items to copy + * @param {Array} target Array to which to copy + * @param {Function} conditionCb Callback passed the current item; will move + * item if evaluates to `true` + * @returns {undefined} + */ - if (!is_WS_OR_EOL(following)) { - break; - } + var moveToAnotherArray = function moveToAnotherArray(source, target, conditionCb) { + var il = source.length; - detected = true; - state.position++; + for (var i = 0; i < il; i++) { + var item = source[i]; - if (skipSeparationSpace(state, true, -1)) { - if (state.lineIndent <= nodeIndent) { - _result.push(null); - ch = state.input.charCodeAt(state.position); - continue; + if (conditionCb(item)) { + target.push(source.splice(i--, 1)[0]); } } + }; - _line = state.line; - composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); - _result.push(state.result); - skipSeparationSpace(state, true, -1); + var vm = supportsNodeVM ? __nccwpck_require__(26144) : { + /** + * @param {string} expr Expression to evaluate + * @param {Object} context Object whose items will be added to evaluation + * @returns {*} Result of evaluated code + */ + runInNewContext: function runInNewContext(expr, context) { + var keys = Object.keys(context); + var funcs = []; + moveToAnotherArray(keys, funcs, function (key) { + return typeof context[key] === 'function'; + }); + var code = funcs.reduce(function (s, func) { + var fString = context[func].toString(); - ch = state.input.charCodeAt(state.position); + if (!/function/.exec(fString)) { + fString = 'function ' + fString; + } - if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { - throwError(state, 'bad indentation of a sequence entry'); - } else if (state.lineIndent < nodeIndent) { - break; + return 'var ' + func + '=' + fString + ';' + s; + }, '') + keys.reduce(function (s, vr) { + return 'var ' + vr + '=' + JSON.stringify(context[vr]).replace( // http://www.thespanner.co.uk/2011/07/25/the-json-specification-is-now-wrong/ + /\u2028|\u2029/g, function (m) { + return "\\u202" + (m === "\u2028" ? '8' : '9'); + }) + ';' + s; + }, expr); + return globalEval(code); } + }; + /** + * Copies array and then pushes item into it. + * @param {Array} arr Array to copy and into which to push + * @param {*} item Array item to add (to end) + * @returns {Array} Copy of the original array + */ + + function push(arr, item) { + arr = arr.slice(); + arr.push(item); + return arr; } + /** + * Copies array and then unshifts item into it. + * @param {*} item Array item to add (to beginning) + * @param {Array} arr Array to copy and into which to unshift + * @returns {Array} Copy of the original array + */ - if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = 'sequence'; - state.result = _result; - return true; + + function unshift(item, arr) { + arr = arr.slice(); + arr.unshift(item); + return arr; } - return false; -} + /** + * Caught when JSONPath is used without `new` but rethrown if with `new` + * @extends Error + */ -function readBlockMapping(state, nodeIndent, flowIndent) { - var following, - allowCompact, - _line, - _keyLine, - _keyLineStart, - _keyPos, - _tag = state.tag, - _anchor = state.anchor, - _result = {}, - overridableKeys = Object.create(null), - keyTag = null, - keyNode = null, - valueNode = null, - atExplicitKey = false, - detected = false, - ch; - // there is a leading tab before this token, so it can't be a block sequence/mapping; - // it can still be flow sequence/mapping or a scalar - if (state.firstTabInLine !== -1) return false; + var NewError = + /*#__PURE__*/ + function (_Error) { + _inherits(NewError, _Error); - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } + /** + * @param {*} value The evaluated scalar value + */ + function NewError(value) { + var _this; - ch = state.input.charCodeAt(state.position); + _classCallCheck(this, NewError); - while (ch !== 0) { - if (!atExplicitKey && state.firstTabInLine !== -1) { - state.position = state.firstTabInLine; - throwError(state, 'tab characters must not be used in indentation'); + _this = _possibleConstructorReturn(this, _getPrototypeOf(NewError).call(this, 'JSONPath should not be called with "new" (it prevents return of (unwrapped) scalar values)')); + _this.avoidNew = true; + _this.value = value; + _this.name = 'NewError'; + return _this; } - following = state.input.charCodeAt(state.position + 1); - _line = state.line; // Save the current line. + return NewError; + }(_wrapNativeSuper(Error)); + /** + * @param {Object} [opts] If present, must be an object + * @param {string} expr JSON path to evaluate + * @param {JSON} obj JSON object to evaluate against + * @param {Function} callback Passed 3 arguments: 1) desired payload per `resultType`, + * 2) `"value"|"property"`, 3) Full returned object with all payloads + * @param {Function} otherTypeCallback If `@other()` is at the end of one's query, this + * will be invoked with the value of the item, its path, its parent, and its parent's + * property name, and it should return a boolean indicating whether the supplied value + * belongs to the "other" type or not (or it may handle transformations and return `false`). + * @returns {JSONPath} + * @class + */ - // - // Explicit notation case. There are two separate blocks: - // first for the key (denoted by "?") and second for the value (denoted by ":") - // - if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { - if (ch === 0x3F/* ? */) { - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); - keyTag = keyNode = valueNode = null; + function JSONPath(opts, expr, obj, callback, otherTypeCallback) { + // eslint-disable-next-line no-restricted-syntax + if (!(this instanceof JSONPath)) { + try { + return new JSONPath(opts, expr, obj, callback, otherTypeCallback); + } catch (e) { + if (!e.avoidNew) { + throw e; } - detected = true; - atExplicitKey = true; - allowCompact = true; + return e.value; + } + } - } else if (atExplicitKey) { - // i.e. 0x3A/* : */ === character after the explicit key. - atExplicitKey = false; - allowCompact = true; + if (typeof opts === 'string') { + otherTypeCallback = callback; + callback = obj; + obj = expr; + expr = opts; + opts = {}; + } - } else { - throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); - } + opts = opts || {}; + var objArgs = hasOwnProp.call(opts, 'json') && hasOwnProp.call(opts, 'path'); + this.json = opts.json || obj; + this.path = opts.path || expr; + this.resultType = opts.resultType && opts.resultType.toLowerCase() || 'value'; + this.flatten = opts.flatten || false; + this.wrap = hasOwnProp.call(opts, 'wrap') ? opts.wrap : true; + this.sandbox = opts.sandbox || {}; + this.preventEval = opts.preventEval || false; + this.parent = opts.parent || null; + this.parentProperty = opts.parentProperty || null; + this.callback = opts.callback || callback || null; - state.position += 1; - ch = following; + this.otherTypeCallback = opts.otherTypeCallback || otherTypeCallback || function () { + throw new Error('You must supply an otherTypeCallback callback option with the @other() operator.'); + }; - // - // Implicit notation case. Flow-style node as the key first, then ":", and the value. - // - } else { - _keyLine = state.line; - _keyLineStart = state.lineStart; - _keyPos = state.position; + if (opts.autostart !== false) { + var ret = this.evaluate({ + path: objArgs ? opts.path : expr, + json: objArgs ? opts.json : obj + }); - if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { - // Neither implicit nor explicit notation. - // Reading is done. Go to the epilogue. - break; + if (!ret || _typeof(ret) !== 'object') { + throw new NewError(ret); } - if (state.line === _line) { - ch = state.input.charCodeAt(state.position); + return ret; + } + } // PUBLIC METHODS - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } - if (ch === 0x3A/* : */) { - ch = state.input.charCodeAt(++state.position); + JSONPath.prototype.evaluate = function (expr, json, callback, otherTypeCallback) { + var that = this; + var currParent = this.parent, + currParentProperty = this.parentProperty; + var flatten = this.flatten, + wrap = this.wrap; + this.currResultType = this.resultType; + this.currPreventEval = this.preventEval; + this.currSandbox = this.sandbox; + callback = callback || this.callback; + this.currOtherTypeCallback = otherTypeCallback || this.otherTypeCallback; + json = json || this.json; + expr = expr || this.path; - if (!is_WS_OR_EOL(ch)) { - throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); - } + if (expr && _typeof(expr) === 'object') { + if (!expr.path) { + throw new Error('You must supply a "path" property when providing an object argument to JSONPath.evaluate().'); + } - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); - keyTag = keyNode = valueNode = null; - } + json = hasOwnProp.call(expr, 'json') ? expr.json : json; + flatten = hasOwnProp.call(expr, 'flatten') ? expr.flatten : flatten; + this.currResultType = hasOwnProp.call(expr, 'resultType') ? expr.resultType : this.currResultType; + this.currSandbox = hasOwnProp.call(expr, 'sandbox') ? expr.sandbox : this.currSandbox; + wrap = hasOwnProp.call(expr, 'wrap') ? expr.wrap : wrap; + this.currPreventEval = hasOwnProp.call(expr, 'preventEval') ? expr.preventEval : this.currPreventEval; + callback = hasOwnProp.call(expr, 'callback') ? expr.callback : callback; + this.currOtherTypeCallback = hasOwnProp.call(expr, 'otherTypeCallback') ? expr.otherTypeCallback : this.currOtherTypeCallback; + currParent = hasOwnProp.call(expr, 'parent') ? expr.parent : currParent; + currParentProperty = hasOwnProp.call(expr, 'parentProperty') ? expr.parentProperty : currParentProperty; + expr = expr.path; + } - detected = true; - atExplicitKey = false; - allowCompact = false; - keyTag = state.tag; - keyNode = state.result; + currParent = currParent || null; + currParentProperty = currParentProperty || null; - } else if (detected) { - throwError(state, 'can not read an implicit mapping pair; a colon is missed'); + if (Array.isArray(expr)) { + expr = JSONPath.toPathString(expr); + } - } else { - state.tag = _tag; - state.anchor = _anchor; - return true; // Keep the result of `composeNode`. - } + if (!expr || !json || !allowedResultTypes.includes(this.currResultType)) { + return undefined; + } - } else if (detected) { - throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); + this._obj = json; + var exprList = JSONPath.toPathArray(expr); - } else { - state.tag = _tag; - state.anchor = _anchor; - return true; // Keep the result of `composeNode`. - } + if (exprList[0] === '$' && exprList.length > 1) { + exprList.shift(); } - // - // Common reading code for both explicit and implicit notations. - // - if (state.line === _line || state.lineIndent > nodeIndent) { - if (atExplicitKey) { - _keyLine = state.line; - _keyLineStart = state.lineStart; - _keyPos = state.position; - } - - if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { - if (atExplicitKey) { - keyNode = state.result; - } else { - valueNode = state.result; - } - } + this._hasParentSelector = null; - if (!atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); - keyTag = keyNode = valueNode = null; - } + var result = this._trace(exprList, json, ['$'], currParent, currParentProperty, callback).filter(function (ea) { + return ea && !ea.isParentSelector; + }); - skipSeparationSpace(state, true, -1); - ch = state.input.charCodeAt(state.position); + if (!result.length) { + return wrap ? [] : undefined; } - if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { - throwError(state, 'bad indentation of a mapping entry'); - } else if (state.lineIndent < nodeIndent) { - break; + if (result.length === 1 && !wrap && !Array.isArray(result[0].value)) { + return this._getPreferredOutput(result[0]); } - } - - // - // Epilogue. - // - - // Special case: last mapping's node contains only the key in explicit notation. - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); - } - - // Expose the resulting mapping. - if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = 'mapping'; - state.result = _result; - } - - return detected; -} - -function readTagProperty(state) { - var _position, - isVerbatim = false, - isNamed = false, - tagHandle, - tagName, - ch; - ch = state.input.charCodeAt(state.position); + return result.reduce(function (rslt, ea) { + var valOrPath = that._getPreferredOutput(ea); - if (ch !== 0x21/* ! */) return false; + if (flatten && Array.isArray(valOrPath)) { + rslt = rslt.concat(valOrPath); + } else { + rslt.push(valOrPath); + } - if (state.tag !== null) { - throwError(state, 'duplication of a tag property'); - } + return rslt; + }, []); + }; // PRIVATE METHODS - ch = state.input.charCodeAt(++state.position); - if (ch === 0x3C/* < */) { - isVerbatim = true; - ch = state.input.charCodeAt(++state.position); + JSONPath.prototype._getPreferredOutput = function (ea) { + var resultType = this.currResultType; - } else if (ch === 0x21/* ! */) { - isNamed = true; - tagHandle = '!!'; - ch = state.input.charCodeAt(++state.position); + switch (resultType) { + default: + throw new TypeError('Unknown result type'); - } else { - tagHandle = '!'; - } + case 'all': + ea.pointer = JSONPath.toPointer(ea.path); + ea.path = typeof ea.path === 'string' ? ea.path : JSONPath.toPathString(ea.path); + return ea; - _position = state.position; + case 'value': + case 'parent': + case 'parentProperty': + return ea[resultType]; - if (isVerbatim) { - do { ch = state.input.charCodeAt(++state.position); } - while (ch !== 0 && ch !== 0x3E/* > */); + case 'path': + return JSONPath.toPathString(ea[resultType]); - if (state.position < state.length) { - tagName = state.input.slice(_position, state.position); - ch = state.input.charCodeAt(++state.position); - } else { - throwError(state, 'unexpected end of the stream within a verbatim tag'); + case 'pointer': + return JSONPath.toPointer(ea.path); } - } else { - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - - if (ch === 0x21/* ! */) { - if (!isNamed) { - tagHandle = state.input.slice(_position - 1, state.position + 1); - - if (!PATTERN_TAG_HANDLE.test(tagHandle)) { - throwError(state, 'named tag handle cannot contain such characters'); - } - - isNamed = true; - _position = state.position + 1; - } else { - throwError(state, 'tag suffix cannot contain exclamation marks'); - } - } + }; - ch = state.input.charCodeAt(++state.position); - } + JSONPath.prototype._handleCallback = function (fullRetObj, callback, type) { + if (callback) { + var preferredOutput = this._getPreferredOutput(fullRetObj); - tagName = state.input.slice(_position, state.position); + fullRetObj.path = typeof fullRetObj.path === 'string' ? fullRetObj.path : JSONPath.toPathString(fullRetObj.path); // eslint-disable-next-line callback-return - if (PATTERN_FLOW_INDICATORS.test(tagName)) { - throwError(state, 'tag suffix cannot contain flow indicator characters'); + callback(preferredOutput, type, fullRetObj); } - } - - if (tagName && !PATTERN_TAG_URI.test(tagName)) { - throwError(state, 'tag name cannot contain such characters: ' + tagName); - } - - try { - tagName = decodeURIComponent(tagName); - } catch (err) { - throwError(state, 'tag name is malformed: ' + tagName); - } - - if (isVerbatim) { - state.tag = tagName; - - } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { - state.tag = state.tagMap[tagHandle] + tagName; + }; - } else if (tagHandle === '!') { - state.tag = '!' + tagName; + JSONPath.prototype._trace = function (expr, val, path, parent, parentPropName, callback, literalPriority) { + // No expr to follow? return path and value as the result of this trace branch + var retObj; + var that = this; - } else if (tagHandle === '!!') { - state.tag = 'tag:yaml.org,2002:' + tagName; + if (!expr.length) { + retObj = { + path: path, + value: val, + parent: parent, + parentProperty: parentPropName + }; - } else { - throwError(state, 'undeclared tag handle "' + tagHandle + '"'); - } + this._handleCallback(retObj, callback, 'value'); - return true; -} + return retObj; + } -function readAnchorProperty(state) { - var _position, - ch; + var loc = expr[0], + x = expr.slice(1); // We need to gather the return value of recursive trace calls in order to + // do the parent sel computation. - ch = state.input.charCodeAt(state.position); + var ret = []; - if (ch !== 0x26/* & */) return false; + function addRet(elems) { + if (Array.isArray(elems)) { + // This was causing excessive stack size in Node (with or without Babel) against our performance test: `ret.push(...elems);` + elems.forEach(function (t) { + ret.push(t); + }); + } else { + ret.push(elems); + } + } - if (state.anchor !== null) { - throwError(state, 'duplication of an anchor property'); - } + if ((typeof loc !== 'string' || literalPriority) && val && hasOwnProp.call(val, loc)) { + // simple case--directly follow property + addRet(this._trace(x, val[loc], push(path, loc), val, loc, callback)); + } else if (loc === '*') { + // all child properties + // eslint-disable-next-line no-shadow + this._walk(loc, x, val, path, parent, parentPropName, callback, function (m, l, x, v, p, par, pr, cb) { + addRet(that._trace(unshift(m, x), v, p, par, pr, cb, true)); + }); + } else if (loc === '..') { + // all descendent parent properties + addRet(this._trace(x, val, path, parent, parentPropName, callback)); // Check remaining expression with val's immediate children + // eslint-disable-next-line no-shadow - ch = state.input.charCodeAt(++state.position); - _position = state.position; + this._walk(loc, x, val, path, parent, parentPropName, callback, function (m, l, x, v, p, par, pr, cb) { + // We don't join m and x here because we only want parents, not scalar values + if (_typeof(v[m]) === 'object') { + // Keep going with recursive descent on val's object children + addRet(that._trace(unshift(l, x), v[m], push(p, m), v, m, cb)); + } + }); // The parent sel computation is handled in the frame above using the + // ancestor object of val - while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); - } + } else if (loc === '^') { + // This is not a final endpoint, so we do not invoke the callback here + this._hasParentSelector = true; + return path.length ? { + path: path.slice(0, -1), + expr: x, + isParentSelector: true + } : []; + } else if (loc === '~') { + // property name + retObj = { + path: push(path, loc), + value: parentPropName, + parent: parent, + parentProperty: null + }; - if (state.position === _position) { - throwError(state, 'name of an anchor node must contain at least one character'); - } + this._handleCallback(retObj, callback, 'property'); - state.anchor = state.input.slice(_position, state.position); - return true; -} + return retObj; + } else if (loc === '$') { + // root only + addRet(this._trace(x, val, path, null, null, callback)); + } else if (/^(-?\d*):(-?\d*):?(\d*)$/.test(loc)) { + // [start:end:step] Python slice syntax + addRet(this._slice(loc, x, val, path, parent, parentPropName, callback)); + } else if (loc.indexOf('?(') === 0) { + // [?(expr)] (filtering) + if (this.currPreventEval) { + throw new Error('Eval [?(expr)] prevented in JSONPath expression.'); + } // eslint-disable-next-line no-shadow -function readAlias(state) { - var _position, alias, - ch; - ch = state.input.charCodeAt(state.position); + this._walk(loc, x, val, path, parent, parentPropName, callback, function (m, l, x, v, p, par, pr, cb) { + if (that._eval(l.replace(/^\?\((.*?)\)$/, '$1'), v[m], m, p, par, pr)) { + addRet(that._trace(unshift(m, x), v, p, par, pr, cb)); + } + }); + } else if (loc[0] === '(') { + // [(expr)] (dynamic property/index) + if (this.currPreventEval) { + throw new Error('Eval [(expr)] prevented in JSONPath expression.'); + } // As this will resolve to a property name (but we don't know it yet), property and parent information is relative to the parent of the property to which this expression will resolve - if (ch !== 0x2A/* * */) return false; - ch = state.input.charCodeAt(++state.position); - _position = state.position; + addRet(this._trace(unshift(this._eval(loc, val, path[path.length - 1], path.slice(0, -1), parent, parentPropName), x), val, path, parent, parentPropName, callback)); + } else if (loc[0] === '@') { + // value type: @boolean(), etc. + var addType = false; + var valueType = loc.slice(1, -2); - while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); - } + switch (valueType) { + default: + throw new TypeError('Unknown value type ' + valueType); - if (state.position === _position) { - throwError(state, 'name of an alias node must contain at least one character'); - } + case 'scalar': + if (!val || !['object', 'function'].includes(_typeof(val))) { + addType = true; + } - alias = state.input.slice(_position, state.position); + break; - if (!_hasOwnProperty.call(state.anchorMap, alias)) { - throwError(state, 'unidentified alias "' + alias + '"'); - } + case 'boolean': + case 'string': + case 'undefined': + case 'function': + if (_typeof(val) === valueType) { + // eslint-disable-line valid-typeof + addType = true; + } - state.result = state.anchorMap[alias]; - skipSeparationSpace(state, true, -1); - return true; -} + break; -function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { - var allowBlockStyles, - allowBlockScalars, - allowBlockCollections, - indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; - } - } - } + break; - if (indentStatus === 1) { - while (readTagProperty(state) || readAnchorProperty(state)) { - if (skipSeparationSpace(state, true, -1)) { - atNewLine = true; - allowBlockCollections = allowBlockStyles; + case 'array': + if (Array.isArray(val)) { + addType = true; + } - if (state.lineIndent > parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; - } - } else { - allowBlockCollections = false; - } - } - } + break; - if (allowBlockCollections) { - allowBlockCollections = atNewLine || allowCompact; - } + case 'other': + addType = this.currOtherTypeCallback(val, path, parent, parentPropName); + break; - if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { - if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { - flowIndent = parentIndent; - } else { - flowIndent = parentIndent + 1; - } + case 'integer': + if (val === Number(val) && isFinite(val) && !(val % 1)) { + addType = true; + } - blockIndent = state.position - state.lineStart; + break; - if (indentStatus === 1) { - if (allowBlockCollections && - (readBlockSequence(state, blockIndent) || - readBlockMapping(state, blockIndent, flowIndent)) || - readFlowCollection(state, flowIndent)) { - hasContent = true; - } else { - if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || - readSingleQuotedScalar(state, flowIndent) || - readDoubleQuotedScalar(state, flowIndent)) { - hasContent = true; + case 'null': + if (val === null) { + addType = true; + } - } else if (readAlias(state)) { - hasContent = true; + break; + } - if (state.tag !== null || state.anchor !== null) { - throwError(state, 'alias node should not have any properties'); - } + if (addType) { + retObj = { + path: path, + value: val, + parent: parent, + parentProperty: parentPropName + }; - } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { - hasContent = true; + this._handleCallback(retObj, callback, 'value'); - if (state.tag === null) { - state.tag = '?'; - } - } + return retObj; + } + } else if (loc[0] === '`' && val && hasOwnProp.call(val, loc.slice(1))) { + // `-escaped property + var locProp = loc.slice(1); + addRet(this._trace(x, val[locProp], push(path, locProp), val, locProp, callback, true)); + } else if (loc.includes(',')) { + // [name1,name2,...] + var parts = loc.split(','); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; + try { + for (var _iterator = parts[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var part = _step.value; + addRet(this._trace(unshift(part, x), val, path, parent, parentPropName, callback)); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator["return"] != null) { + _iterator["return"](); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } } } - } else if (indentStatus === 0) { - // Special case: block sequences are allowed to have same indentation level as the parent. - // http://www.yaml.org/spec/1.2/spec.html#id2799784 - hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); - } - } + } else if (!literalPriority && val && hasOwnProp.call(val, loc)) { + // simple case--directly follow property + addRet(this._trace(x, val[loc], push(path, loc), val, loc, callback, true)); + } // We check the resulting values for parent selections. For parent + // selections we discard the value object and continue the trace with the + // current val object - if (state.tag === null) { - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - } else if (state.tag === '?') { - // Implicit resolving is not allowed for non-scalar types, and '?' - // non-specific tag is only automatically assigned to plain scalars. - // - // We only need to check kind conformity in case user explicitly assigns '?' - // tag, for example like this: "! [0]" - // - if (state.result !== null && state.kind !== 'scalar') { - throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); - } + if (this._hasParentSelector) { + // eslint-disable-next-line unicorn/no-for-loop + for (var t = 0; t < ret.length; t++) { + var rett = ret[t]; - for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { - type = state.implicitTypes[typeIndex]; + if (rett.isParentSelector) { + var tmp = that._trace(rett.expr, val, rett.path, parent, parentPropName, callback); - if (type.resolve(state.result)) { // `state.result` updated in resolver if matched - state.result = type.construct(state.result); - state.tag = type.tag; - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; + if (Array.isArray(tmp)) { + ret[t] = tmp[0]; + var tl = tmp.length; + + for (var tt = 1; tt < tl; tt++) { + t++; + ret.splice(t, 0, tmp[tt]); + } + } else { + ret[t] = tmp; + } } - break; } } - } else if (state.tag !== '!') { - if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { - type = state.typeMap[state.kind || 'fallback'][state.tag]; - } else { - // looking for multi type - type = null; - typeList = state.typeMap.multi[state.kind || 'fallback']; - for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) { - if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { - type = typeList[typeIndex]; - break; + return ret; + }; + + JSONPath.prototype._walk = function (loc, expr, val, path, parent, parentPropName, callback, f) { + if (Array.isArray(val)) { + var n = val.length; + + for (var i = 0; i < n; i++) { + f(i, loc, expr, val, path, parent, parentPropName, callback); + } + } else if (_typeof(val) === 'object') { + for (var m in val) { + if (hasOwnProp.call(val, m)) { + f(m, loc, expr, val, path, parent, parentPropName, callback); } } } + }; - if (!type) { - throwError(state, 'unknown tag !<' + state.tag + '>'); + JSONPath.prototype._slice = function (loc, expr, val, path, parent, parentPropName, callback) { + if (!Array.isArray(val)) { + return undefined; } - if (state.result !== null && type.kind !== state.kind) { - throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); - } + var len = val.length, + parts = loc.split(':'), + step = parts[2] && parseInt(parts[2]) || 1; + var start = parts[0] && parseInt(parts[0]) || 0, + end = parts[1] && parseInt(parts[1]) || len; + start = start < 0 ? Math.max(0, start + len) : Math.min(len, start); + end = end < 0 ? Math.max(0, end + len) : Math.min(len, end); + var ret = []; - if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched - throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); - } else { - state.result = type.construct(state.result, state.tag); - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; + for (var i = start; i < end; i += step) { + var tmp = this._trace(unshift(i, expr), val, path, parent, parentPropName, callback); + + if (Array.isArray(tmp)) { + // This was causing excessive stack size in Node (with or without Babel) against our performance test: `ret.push(...tmp);` + tmp.forEach(function (t) { + ret.push(t); + }); + } else { + ret.push(tmp); } } - } - - if (state.listener !== null) { - state.listener('close', state); - } - return state.tag !== null || state.anchor !== null || hasContent; -} - -function readDocument(state) { - var documentStart = state.position, - _position, - directiveName, - directiveArgs, - hasDirectives = false, - ch; - state.version = null; - state.checkLineBreaks = state.legacy; - state.tagMap = Object.create(null); - state.anchorMap = Object.create(null); - - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - skipSeparationSpace(state, true, -1); + return ret; + }; - ch = state.input.charCodeAt(state.position); + JSONPath.prototype._eval = function (code, _v, _vname, path, parent, parentPropName) { + if (!this._obj || !_v) { + return false; + } - if (state.lineIndent > 0 || ch !== 0x25/* % */) { - break; + if (code.includes('@parentProperty')) { + this.currSandbox._$_parentProperty = parentPropName; + code = code.replace(/@parentProperty/g, '_$_parentProperty'); } - hasDirectives = true; - ch = state.input.charCodeAt(++state.position); - _position = state.position; + if (code.includes('@parent')) { + this.currSandbox._$_parent = parent; + code = code.replace(/@parent/g, '_$_parent'); + } - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); + if (code.includes('@property')) { + this.currSandbox._$_property = _vname; + code = code.replace(/@property/g, '_$_property'); } - directiveName = state.input.slice(_position, state.position); - directiveArgs = []; + if (code.includes('@path')) { + this.currSandbox._$_path = JSONPath.toPathString(path.concat([_vname])); + code = code.replace(/@path/g, '_$_path'); + } - if (directiveName.length < 1) { - throwError(state, 'directive name must not be less than one character in length'); + if (code.match(/@([.\s)[])/)) { + this.currSandbox._$_v = _v; + code = code.replace(/@([.\s)[])/g, '_$_v$1'); } - while (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } + try { + return vm.runInNewContext(code, this.currSandbox); + } catch (e) { + // eslint-disable-next-line no-console + console.log(e); + throw new Error('jsonPath: ' + e.message + ': ' + code); + } + }; // PUBLIC CLASS PROPERTIES AND METHODS + // Could store the cache object itself - if (ch === 0x23/* # */) { - do { ch = state.input.charCodeAt(++state.position); } - while (ch !== 0 && !is_EOL(ch)); - break; - } - if (is_EOL(ch)) break; + JSONPath.cache = {}; + /** + * @param {string[]} pathArr Array to convert + * @returns {string} The path string + */ - _position = state.position; + JSONPath.toPathString = function (pathArr) { + var x = pathArr, + n = x.length; + var p = '$'; - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); + for (var i = 1; i < n; i++) { + if (!/^(~|\^|@.*?\(\))$/.test(x[i])) { + p += /^[0-9*]+$/.test(x[i]) ? '[' + x[i] + ']' : "['" + x[i] + "']"; } - - directiveArgs.push(state.input.slice(_position, state.position)); - } - - if (ch !== 0) readLineBreak(state); - - if (_hasOwnProperty.call(directiveHandlers, directiveName)) { - directiveHandlers[directiveName](state, directiveName, directiveArgs); - } else { - throwWarning(state, 'unknown document directive "' + directiveName + '"'); } - } - skipSeparationSpace(state, true, -1); + return p; + }; + /** + * @param {string} pointer JSON Path + * @returns {string} JSON Pointer + */ - if (state.lineIndent === 0 && - state.input.charCodeAt(state.position) === 0x2D/* - */ && - state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && - state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { - state.position += 3; - skipSeparationSpace(state, true, -1); - } else if (hasDirectives) { - throwError(state, 'directives end mark is expected'); - } + JSONPath.toPointer = function (pointer) { + var x = pointer, + n = x.length; + var p = ''; - composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); - skipSeparationSpace(state, true, -1); + for (var i = 1; i < n; i++) { + if (!/^(~|\^|@.*?\(\))$/.test(x[i])) { + p += '/' + x[i].toString().replace(/~/g, '~0').replace(/\//g, '~1'); + } + } - if (state.checkLineBreaks && - PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { - throwWarning(state, 'non-ASCII line breaks are interpreted as content'); - } + return p; + }; + /** + * @param {string} expr Expression to convert + * @returns {string[]} + */ - state.documents.push(state.result); - if (state.position === state.lineStart && testDocumentSeparator(state)) { + JSONPath.toPathArray = function (expr) { + var cache = JSONPath.cache; - if (state.input.charCodeAt(state.position) === 0x2E/* . */) { - state.position += 3; - skipSeparationSpace(state, true, -1); + if (cache[expr]) { + return cache[expr].concat(); } - return; - } - if (state.position < (state.length - 1)) { - throwError(state, 'end of the stream or a document separator is expected'); - } else { - return; - } -} + var subx = []; + var normalized = expr // Properties + .replace(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\(\)/g, ';$&;') // Parenthetical evaluations (filtering and otherwise), directly + // within brackets or single quotes + .replace(/[['](\??\(.*?\))[\]']/g, function ($0, $1) { + return '[#' + (subx.push($1) - 1) + ']'; + }) // Escape periods and tildes within properties + .replace(/\['([^'\]]*)'\]/g, function ($0, prop) { + return "['" + prop.replace(/\./g, '%@%').replace(/~/g, '%%@@%%') + "']"; + }) // Properties operator + .replace(/~/g, ';~;') // Split by property boundaries + .replace(/'?\.'?(?![^[]*\])|\['?/g, ';') // Reinsert periods within properties + .replace(/%@%/g, '.') // Reinsert tildes within properties + .replace(/%%@@%%/g, '~') // Parent + .replace(/(?:;)?(\^+)(?:;)?/g, function ($0, ups) { + return ';' + ups.split('').join(';') + ';'; + }) // Descendents + .replace(/;;;|;;/g, ';..;') // Remove trailing + .replace(/;$|'?\]|'$/g, ''); + var exprList = normalized.split(';').map(function (exp) { + var match = exp.match(/#(\d+)/); + return !match || !match[1] ? exp : subx[match[1]]; + }); + cache[expr] = exprList; + return cache[expr]; + }; + exports.JSONPath = JSONPath; -function loadDocuments(input, options) { - input = String(input); - options = options || {}; + Object.defineProperty(exports, '__esModule', { value: true }); - if (input.length !== 0) { +})); - // Add tailing `\n` if not exists - if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && - input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { - input += '\n'; - } - // Strip BOM - if (input.charCodeAt(0) === 0xFEFF) { - input = input.slice(1); - } - } +/***/ }), - var state = new State(input, options); +/***/ 6287: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var nullpos = input.indexOf('\0'); +/* + * lib/jsprim.js: utilities for primitive JavaScript types + */ - if (nullpos !== -1) { - state.position = nullpos; - throwError(state, 'null byte is not allowed in input'); - } +var mod_assert = __nccwpck_require__(66631); +var mod_util = __nccwpck_require__(73837); - // Use 0 as string terminator. That significantly simplifies bounds check. - state.input += '\0'; +var mod_extsprintf = __nccwpck_require__(87264); +var mod_verror = __nccwpck_require__(81692); +var mod_jsonschema = __nccwpck_require__(21328); - while (state.input.charCodeAt(state.position) === 0x20/* Space */) { - state.lineIndent += 1; - state.position += 1; - } +/* + * Public interface + */ +exports.deepCopy = deepCopy; +exports.deepEqual = deepEqual; +exports.isEmpty = isEmpty; +exports.hasKey = hasKey; +exports.forEachKey = forEachKey; +exports.pluck = pluck; +exports.flattenObject = flattenObject; +exports.flattenIter = flattenIter; +exports.validateJsonObject = validateJsonObjectJS; +exports.validateJsonObjectJS = validateJsonObjectJS; +exports.randElt = randElt; +exports.extraProperties = extraProperties; +exports.mergeObjects = mergeObjects; - while (state.position < (state.length - 1)) { - readDocument(state); - } +exports.startsWith = startsWith; +exports.endsWith = endsWith; - return state.documents; -} +exports.parseInteger = parseInteger; +exports.iso8601 = iso8601; +exports.rfc1123 = rfc1123; +exports.parseDateTime = parseDateTime; -function loadAll(input, iterator, options) { - if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { - options = iterator; - iterator = null; - } +exports.hrtimediff = hrtimeDiff; +exports.hrtimeDiff = hrtimeDiff; +exports.hrtimeAccum = hrtimeAccum; +exports.hrtimeAdd = hrtimeAdd; +exports.hrtimeNanosec = hrtimeNanosec; +exports.hrtimeMicrosec = hrtimeMicrosec; +exports.hrtimeMillisec = hrtimeMillisec; - var documents = loadDocuments(input, options); - if (typeof iterator !== 'function') { - return documents; - } +/* + * Deep copy an acyclic *basic* Javascript object. This only handles basic + * scalars (strings, numbers, booleans) and arbitrarily deep arrays and objects + * containing these. This does *not* handle instances of other classes. + */ +function deepCopy(obj) +{ + var ret, key; + var marker = '__deepCopy'; - for (var index = 0, length = documents.length; index < length; index += 1) { - iterator(documents[index]); - } -} + if (obj && obj[marker]) + throw (new Error('attempted deep copy of cyclic object')); + if (obj && obj.constructor == Object) { + ret = {}; + obj[marker] = true; -function load(input, options) { - var documents = loadDocuments(input, options); + for (key in obj) { + if (key == marker) + continue; - if (documents.length === 0) { - /*eslint-disable no-undefined*/ - return undefined; - } else if (documents.length === 1) { - return documents[0]; - } - throw new YAMLException('expected a single document in the stream, but found more'); -} + ret[key] = deepCopy(obj[key]); + } + delete (obj[marker]); + return (ret); + } -module.exports.loadAll = loadAll; -module.exports.load = load; + if (obj && obj.constructor == Array) { + ret = []; + obj[marker] = true; + for (key = 0; key < obj.length; key++) + ret.push(deepCopy(obj[key])); -/***/ }), + delete (obj[marker]); + return (ret); + } -/***/ 21082: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /* + * It must be a primitive type -- just return it. + */ + return (obj); +} -"use strict"; +function deepEqual(obj1, obj2) +{ + if (typeof (obj1) != typeof (obj2)) + return (false); + if (obj1 === null || obj2 === null || typeof (obj1) != 'object') + return (obj1 === obj2); -/*eslint-disable max-len*/ + if (obj1.constructor != obj2.constructor) + return (false); -var YAMLException = __nccwpck_require__(68179); -var Type = __nccwpck_require__(6073); + var k; + for (k in obj1) { + if (!obj2.hasOwnProperty(k)) + return (false); + if (!deepEqual(obj1[k], obj2[k])) + return (false); + } -function compileList(schema, name) { - var result = []; + for (k in obj2) { + if (!obj1.hasOwnProperty(k)) + return (false); + } - schema[name].forEach(function (currentType) { - var newIndex = result.length; + return (true); +} - result.forEach(function (previousType, previousIndex) { - if (previousType.tag === currentType.tag && - previousType.kind === currentType.kind && - previousType.multi === currentType.multi) { +function isEmpty(obj) +{ + var key; + for (key in obj) + return (false); + return (true); +} - newIndex = previousIndex; - } - }); +function hasKey(obj, key) +{ + mod_assert.equal(typeof (key), 'string'); + return (Object.prototype.hasOwnProperty.call(obj, key)); +} - result[newIndex] = currentType; - }); +function forEachKey(obj, callback) +{ + for (var key in obj) { + if (hasKey(obj, key)) { + callback(key, obj[key]); + } + } +} - return result; +function pluck(obj, key) +{ + mod_assert.equal(typeof (key), 'string'); + return (pluckv(obj, key)); } +function pluckv(obj, key) +{ + if (obj === null || typeof (obj) !== 'object') + return (undefined); -function compileMap(/* lists... */) { - var result = { - scalar: {}, - sequence: {}, - mapping: {}, - fallback: {}, - multi: { - scalar: [], - sequence: [], - mapping: [], - fallback: [] - } - }, index, length; + if (obj.hasOwnProperty(key)) + return (obj[key]); - function collectType(type) { - if (type.multi) { - result.multi[type.kind].push(type); - result.multi['fallback'].push(type); - } else { - result[type.kind][type.tag] = result['fallback'][type.tag] = type; - } - } + var i = key.indexOf('.'); + if (i == -1) + return (undefined); - for (index = 0, length = arguments.length; index < length; index += 1) { - arguments[index].forEach(collectType); - } - return result; -} + var key1 = key.substr(0, i); + if (!obj.hasOwnProperty(key1)) + return (undefined); + return (pluckv(obj[key1], key.substr(i + 1))); +} -function Schema(definition) { - return this.extend(definition); +/* + * Invoke callback(row) for each entry in the array that would be returned by + * flattenObject(data, depth). This is just like flattenObject(data, + * depth).forEach(callback), except that the intermediate array is never + * created. + */ +function flattenIter(data, depth, callback) +{ + doFlattenIter(data, depth, [], callback); } +function doFlattenIter(data, depth, accum, callback) +{ + var each; + var key; -Schema.prototype.extend = function extend(definition) { - var implicit = []; - var explicit = []; + if (depth === 0) { + each = accum.slice(0); + each.push(data); + callback(each); + return; + } - if (definition instanceof Type) { - // Schema.extend(type) - explicit.push(definition); + mod_assert.ok(data !== null); + mod_assert.equal(typeof (data), 'object'); + mod_assert.equal(typeof (depth), 'number'); + mod_assert.ok(depth >= 0); - } else if (Array.isArray(definition)) { - // Schema.extend([ type1, type2, ... ]) - explicit = explicit.concat(definition); + for (key in data) { + each = accum.slice(0); + each.push(key); + doFlattenIter(data[key], depth - 1, each, callback); + } +} - } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { - // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] }) - if (definition.implicit) implicit = implicit.concat(definition.implicit); - if (definition.explicit) explicit = explicit.concat(definition.explicit); +function flattenObject(data, depth) +{ + if (depth === 0) + return ([ data ]); - } else { - throw new YAMLException('Schema.extend argument should be a Type, [ Type ], ' + - 'or a schema definition ({ implicit: [...], explicit: [...] })'); - } + mod_assert.ok(data !== null); + mod_assert.equal(typeof (data), 'object'); + mod_assert.equal(typeof (depth), 'number'); + mod_assert.ok(depth >= 0); - implicit.forEach(function (type) { - if (!(type instanceof Type)) { - throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); - } + var rv = []; + var key; - if (type.loadKind && type.loadKind !== 'scalar') { - throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); - } + for (key in data) { + flattenObject(data[key], depth - 1).forEach(function (p) { + rv.push([ key ].concat(p)); + }); + } - if (type.multi) { - throw new YAMLException('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.'); - } - }); + return (rv); +} - explicit.forEach(function (type) { - if (!(type instanceof Type)) { - throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); - } - }); +function startsWith(str, prefix) +{ + return (str.substr(0, prefix.length) == prefix); +} - var result = Object.create(Schema.prototype); +function endsWith(str, suffix) +{ + return (str.substr( + str.length - suffix.length, suffix.length) == suffix); +} - result.implicit = (this.implicit || []).concat(implicit); - result.explicit = (this.explicit || []).concat(explicit); +function iso8601(d) +{ + if (typeof (d) == 'number') + d = new Date(d); + mod_assert.ok(d.constructor === Date); + return (mod_extsprintf.sprintf('%4d-%02d-%02dT%02d:%02d:%02d.%03dZ', + d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate(), + d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), + d.getUTCMilliseconds())); +} - result.compiledImplicit = compileList(result, 'implicit'); - result.compiledExplicit = compileList(result, 'explicit'); - result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); +var RFC1123_MONTHS = [ + 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', + 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; +var RFC1123_DAYS = [ + 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; - return result; -}; +function rfc1123(date) { + return (mod_extsprintf.sprintf('%s, %02d %s %04d %02d:%02d:%02d GMT', + RFC1123_DAYS[date.getUTCDay()], date.getUTCDate(), + RFC1123_MONTHS[date.getUTCMonth()], date.getUTCFullYear(), + date.getUTCHours(), date.getUTCMinutes(), + date.getUTCSeconds())); +} +/* + * Parses a date expressed as a string, as either a number of milliseconds since + * the epoch or any string format that Date accepts, giving preference to the + * former where these two sets overlap (e.g., small numbers). + */ +function parseDateTime(str) +{ + /* + * This is irritatingly implicit, but significantly more concise than + * alternatives. The "+str" will convert a string containing only a + * number directly to a Number, or NaN for other strings. Thus, if the + * conversion succeeds, we use it (this is the milliseconds-since-epoch + * case). Otherwise, we pass the string directly to the Date + * constructor to parse. + */ + var numeric = +str; + if (!isNaN(numeric)) { + return (new Date(numeric)); + } else { + return (new Date(str)); + } +} -module.exports = Schema; +/* + * Number.*_SAFE_INTEGER isn't present before node v0.12, so we hardcode + * the ES6 definitions here, while allowing for them to someday be higher. + */ +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; +var MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991; -/***/ }), -/***/ 12011: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/* + * Default options for parseInteger(). + */ +var PI_DEFAULTS = { + base: 10, + allowSign: true, + allowPrefix: false, + allowTrailing: false, + allowImprecise: false, + trimWhitespace: false, + leadingZeroIsOctal: false +}; -"use strict"; -// Standard YAML's Core schema. -// http://www.yaml.org/spec/1.2/spec.html#id2804923 -// -// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. -// So, Core schema has no distinctions from JSON schema is JS-YAML. +var CP_0 = 0x30; +var CP_9 = 0x39; +var CP_A = 0x41; +var CP_B = 0x42; +var CP_O = 0x4f; +var CP_T = 0x54; +var CP_X = 0x58; +var CP_Z = 0x5a; +var CP_a = 0x61; +var CP_b = 0x62; +var CP_o = 0x6f; +var CP_t = 0x74; +var CP_x = 0x78; +var CP_z = 0x7a; +var PI_CONV_DEC = 0x30; +var PI_CONV_UC = 0x37; +var PI_CONV_LC = 0x57; -module.exports = __nccwpck_require__(1035); +/* + * A stricter version of parseInt() that provides options for changing what + * is an acceptable string (for example, disallowing trailing characters). + */ +function parseInteger(str, uopts) +{ + mod_assert.string(str, 'str'); + mod_assert.optionalObject(uopts, 'options'); + var baseOverride = false; + var options = PI_DEFAULTS; -/***/ }), + if (uopts) { + baseOverride = hasKey(uopts, 'base'); + options = mergeObjects(options, uopts); + mod_assert.number(options.base, 'options.base'); + mod_assert.ok(options.base >= 2, 'options.base >= 2'); + mod_assert.ok(options.base <= 36, 'options.base <= 36'); + mod_assert.bool(options.allowSign, 'options.allowSign'); + mod_assert.bool(options.allowPrefix, 'options.allowPrefix'); + mod_assert.bool(options.allowTrailing, + 'options.allowTrailing'); + mod_assert.bool(options.allowImprecise, + 'options.allowImprecise'); + mod_assert.bool(options.trimWhitespace, + 'options.trimWhitespace'); + mod_assert.bool(options.leadingZeroIsOctal, + 'options.leadingZeroIsOctal'); -/***/ 18759: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (options.leadingZeroIsOctal) { + mod_assert.ok(!baseOverride, + '"base" and "leadingZeroIsOctal" are ' + + 'mutually exclusive'); + } + } -"use strict"; -// JS-YAML's default schema for `safeLoad` function. -// It is not described in the YAML specification. -// -// This schema is based on standard YAML's Core schema and includes most of -// extra types described at YAML tag repository. (http://yaml.org/type/) + var c; + var pbase = -1; + var base = options.base; + var start; + var mult = 1; + var value = 0; + var idx = 0; + var len = str.length; + /* Trim any whitespace on the left side. */ + if (options.trimWhitespace) { + while (idx < len && isSpace(str.charCodeAt(idx))) { + ++idx; + } + } + /* Check the number for a leading sign. */ + if (options.allowSign) { + if (str[idx] === '-') { + idx += 1; + mult = -1; + } else if (str[idx] === '+') { + idx += 1; + } + } + /* Parse the base-indicating prefix if there is one. */ + if (str[idx] === '0') { + if (options.allowPrefix) { + pbase = prefixToBase(str.charCodeAt(idx + 1)); + if (pbase !== -1 && (!baseOverride || pbase === base)) { + base = pbase; + idx += 2; + } + } + if (pbase === -1 && options.leadingZeroIsOctal) { + base = 8; + } + } -module.exports = (__nccwpck_require__(12011).extend)({ - implicit: [ - __nccwpck_require__(99212), - __nccwpck_require__(86104) - ], - explicit: [ - __nccwpck_require__(77900), - __nccwpck_require__(19046), - __nccwpck_require__(96860), - __nccwpck_require__(79548) - ] -}); + /* Parse the actual digits. */ + for (start = idx; idx < len; ++idx) { + c = translateDigit(str.charCodeAt(idx)); + if (c !== -1 && c < base) { + value *= base; + value += c; + } else { + break; + } + } + /* If we didn't parse any digits, we have an invalid number. */ + if (start === idx) { + return (new Error('invalid number: ' + JSON.stringify(str))); + } -/***/ }), + /* Trim any whitespace on the right side. */ + if (options.trimWhitespace) { + while (idx < len && isSpace(str.charCodeAt(idx))) { + ++idx; + } + } -/***/ 28562: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /* Check for trailing characters. */ + if (idx < len && !options.allowTrailing) { + return (new Error('trailing characters after number: ' + + JSON.stringify(str.slice(idx)))); + } -"use strict"; -// Standard YAML's Failsafe schema. -// http://www.yaml.org/spec/1.2/spec.html#id2802346 + /* If our value is 0, we return now, to avoid returning -0. */ + if (value === 0) { + return (0); + } + /* Calculate our final value. */ + var result = value * mult; + /* + * If the string represents a value that cannot be precisely represented + * by JavaScript, then we want to check that: + * + * - We never increased the value past MAX_SAFE_INTEGER + * - We don't make the result negative and below MIN_SAFE_INTEGER + * + * Because we only ever increment the value during parsing, there's no + * chance of moving past MAX_SAFE_INTEGER and then dropping below it + * again, losing precision in the process. This means that we only need + * to do our checks here, at the end. + */ + if (!options.allowImprecise && + (value > MAX_SAFE_INTEGER || result < MIN_SAFE_INTEGER)) { + return (new Error('number is outside of the supported range: ' + + JSON.stringify(str.slice(start, idx)))); + } + return (result); +} -var Schema = __nccwpck_require__(21082); +/* + * Interpret a character code as a base-36 digit. + */ +function translateDigit(d) +{ + if (d >= CP_0 && d <= CP_9) { + /* '0' to '9' -> 0 to 9 */ + return (d - PI_CONV_DEC); + } else if (d >= CP_A && d <= CP_Z) { + /* 'A' - 'Z' -> 10 to 35 */ + return (d - PI_CONV_UC); + } else if (d >= CP_a && d <= CP_z) { + /* 'a' - 'z' -> 10 to 35 */ + return (d - PI_CONV_LC); + } else { + /* Invalid character code */ + return (-1); + } +} -module.exports = new Schema({ - explicit: [ - __nccwpck_require__(23619), - __nccwpck_require__(67283), - __nccwpck_require__(86150) - ] -}); +/* + * Test if a value matches the ECMAScript definition of trimmable whitespace. + */ +function isSpace(c) +{ + return (c === 0x20) || + (c >= 0x0009 && c <= 0x000d) || + (c === 0x00a0) || + (c === 0x1680) || + (c === 0x180e) || + (c >= 0x2000 && c <= 0x200a) || + (c === 0x2028) || + (c === 0x2029) || + (c === 0x202f) || + (c === 0x205f) || + (c === 0x3000) || + (c === 0xfeff); +} -/***/ }), +/* + * Determine which base a character indicates (e.g., 'x' indicates hex). + */ +function prefixToBase(c) +{ + if (c === CP_b || c === CP_B) { + /* 0b/0B (binary) */ + return (2); + } else if (c === CP_o || c === CP_O) { + /* 0o/0O (octal) */ + return (8); + } else if (c === CP_t || c === CP_T) { + /* 0t/0T (decimal) */ + return (10); + } else if (c === CP_x || c === CP_X) { + /* 0x/0X (hexadecimal) */ + return (16); + } else { + /* Not a meaningful character */ + return (-1); + } +} -/***/ 1035: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; -// Standard YAML's JSON schema. -// http://www.yaml.org/spec/1.2/spec.html#id2803231 -// -// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. -// So, this schema is not such strict as defined in the YAML specification. -// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. +function validateJsonObjectJS(schema, input) +{ + var report = mod_jsonschema.validate(input, schema); + if (report.errors.length === 0) + return (null); + /* Currently, we only do anything useful with the first error. */ + var error = report.errors[0]; + /* The failed property is given by a URI with an irrelevant prefix. */ + var propname = error['property']; + var reason = error['message'].toLowerCase(); + var i, j; + /* + * There's at least one case where the property error message is + * confusing at best. We work around this here. + */ + if ((i = reason.indexOf('the property ')) != -1 && + (j = reason.indexOf(' is not defined in the schema and the ' + + 'schema does not allow additional properties')) != -1) { + i += 'the property '.length; + if (propname === '') + propname = reason.substr(i, j - i); + else + propname = propname + '.' + reason.substr(i, j - i); -module.exports = (__nccwpck_require__(28562).extend)({ - implicit: [ - __nccwpck_require__(20721), - __nccwpck_require__(64993), - __nccwpck_require__(11615), - __nccwpck_require__(42705) - ] -}); + reason = 'unsupported property'; + } + var rv = new mod_verror.VError('property "%s": %s', propname, reason); + rv.jsv_details = error; + return (rv); +} -/***/ }), +function randElt(arr) +{ + mod_assert.ok(Array.isArray(arr) && arr.length > 0, + 'randElt argument must be a non-empty array'); -/***/ 96975: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return (arr[Math.floor(Math.random() * arr.length)]); +} -"use strict"; +function assertHrtime(a) +{ + mod_assert.ok(a[0] >= 0 && a[1] >= 0, + 'negative numbers not allowed in hrtimes'); + mod_assert.ok(a[1] < 1e9, 'nanoseconds column overflow'); +} +/* + * Compute the time elapsed between hrtime readings A and B, where A is later + * than B. hrtime readings come from Node's process.hrtime(). There is no + * defined way to represent negative deltas, so it's illegal to diff B from A + * where the time denoted by B is later than the time denoted by A. If this + * becomes valuable, we can define a representation and extend the + * implementation to support it. + */ +function hrtimeDiff(a, b) +{ + assertHrtime(a); + assertHrtime(b); + mod_assert.ok(a[0] > b[0] || (a[0] == b[0] && a[1] >= b[1]), + 'negative differences not allowed'); + var rv = [ a[0] - b[0], 0 ]; -var common = __nccwpck_require__(26829); + if (a[1] >= b[1]) { + rv[1] = a[1] - b[1]; + } else { + rv[0]--; + rv[1] = 1e9 - (b[1] - a[1]); + } + return (rv); +} -// get snippet for a single line, respecting maxLength -function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { - var head = ''; - var tail = ''; - var maxHalfLength = Math.floor(maxLineLength / 2) - 1; +/* + * Convert a hrtime reading from the array format returned by Node's + * process.hrtime() into a scalar number of nanoseconds. + */ +function hrtimeNanosec(a) +{ + assertHrtime(a); - if (position - lineStart > maxHalfLength) { - head = ' ... '; - lineStart = position - maxHalfLength + head.length; - } + return (Math.floor(a[0] * 1e9 + a[1])); +} - if (lineEnd - position > maxHalfLength) { - tail = ' ...'; - lineEnd = position + maxHalfLength - tail.length; - } +/* + * Convert a hrtime reading from the array format returned by Node's + * process.hrtime() into a scalar number of microseconds. + */ +function hrtimeMicrosec(a) +{ + assertHrtime(a); - return { - str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail, - pos: position - lineStart + head.length // relative position - }; + return (Math.floor(a[0] * 1e6 + a[1] / 1e3)); } +/* + * Convert a hrtime reading from the array format returned by Node's + * process.hrtime() into a scalar number of milliseconds. + */ +function hrtimeMillisec(a) +{ + assertHrtime(a); -function padStart(string, max) { - return common.repeat(' ', max - string.length) + string; + return (Math.floor(a[0] * 1e3 + a[1] / 1e6)); } +/* + * Add two hrtime readings A and B, overwriting A with the result of the + * addition. This function is useful for accumulating several hrtime intervals + * into a counter. Returns A. + */ +function hrtimeAccum(a, b) +{ + assertHrtime(a); + assertHrtime(b); -function makeSnippet(mark, options) { - options = Object.create(options || null); + /* + * Accumulate the nanosecond component. + */ + a[1] += b[1]; + if (a[1] >= 1e9) { + /* + * The nanosecond component overflowed, so carry to the seconds + * field. + */ + a[0]++; + a[1] -= 1e9; + } - if (!mark.buffer) return null; + /* + * Accumulate the seconds component. + */ + a[0] += b[0]; - if (!options.maxLength) options.maxLength = 79; - if (typeof options.indent !== 'number') options.indent = 1; - if (typeof options.linesBefore !== 'number') options.linesBefore = 3; - if (typeof options.linesAfter !== 'number') options.linesAfter = 2; + return (a); +} - var re = /\r?\n|\r|\0/g; - var lineStarts = [ 0 ]; - var lineEnds = []; - var match; - var foundLineNo = -1; +/* + * Add two hrtime readings A and B, returning the result as a new hrtime array. + * Does not modify either input argument. + */ +function hrtimeAdd(a, b) +{ + assertHrtime(a); - while ((match = re.exec(mark.buffer))) { - lineEnds.push(match.index); - lineStarts.push(match.index + match[0].length); + var rv = [ a[0], a[1] ]; - if (mark.position <= match.index && foundLineNo < 0) { - foundLineNo = lineStarts.length - 2; - } - } + return (hrtimeAccum(rv, b)); +} - if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; - var result = '', i, line; - var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; - var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); +/* + * Check an object for unexpected properties. Accepts the object to check, and + * an array of allowed property names (strings). Returns an array of key names + * that were found on the object, but did not appear in the list of allowed + * properties. If no properties were found, the returned array will be of + * zero length. + */ +function extraProperties(obj, allowed) +{ + mod_assert.ok(typeof (obj) === 'object' && obj !== null, + 'obj argument must be a non-null object'); + mod_assert.ok(Array.isArray(allowed), + 'allowed argument must be an array of strings'); + for (var i = 0; i < allowed.length; i++) { + mod_assert.ok(typeof (allowed[i]) === 'string', + 'allowed argument must be an array of strings'); + } - for (i = 1; i <= options.linesBefore; i++) { - if (foundLineNo - i < 0) break; - line = getLine( - mark.buffer, - lineStarts[foundLineNo - i], - lineEnds[foundLineNo - i], - mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), - maxLineLength - ); - result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + - ' | ' + line.str + '\n' + result; - } + return (Object.keys(obj).filter(function (key) { + return (allowed.indexOf(key) === -1); + })); +} - line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); - result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + - ' | ' + line.str + '\n'; - result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n'; +/* + * Given three sets of properties "provided" (may be undefined), "overrides" + * (required), and "defaults" (may be undefined), construct an object containing + * the union of these sets with "overrides" overriding "provided", and + * "provided" overriding "defaults". None of the input objects are modified. + */ +function mergeObjects(provided, overrides, defaults) +{ + var rv, k; - for (i = 1; i <= options.linesAfter; i++) { - if (foundLineNo + i >= lineEnds.length) break; - line = getLine( - mark.buffer, - lineStarts[foundLineNo + i], - lineEnds[foundLineNo + i], - mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), - maxLineLength - ); - result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + - ' | ' + line.str + '\n'; - } + rv = {}; + if (defaults) { + for (k in defaults) + rv[k] = defaults[k]; + } - return result.replace(/\n$/, ''); -} + if (provided) { + for (k in provided) + rv[k] = provided[k]; + } + if (overrides) { + for (k in overrides) + rv[k] = overrides[k]; + } -module.exports = makeSnippet; + return (rv); +} /***/ }), -/***/ 6073: +/***/ 51531: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var YAMLException = __nccwpck_require__(68179); - -var TYPE_CONSTRUCTOR_OPTIONS = [ - 'kind', - 'multi', - 'resolve', - 'construct', - 'instanceOf', - 'predicate', - 'represent', - 'representName', - 'defaultStyle', - 'styleAliases' -]; - -var YAML_NODE_KINDS = [ - 'scalar', - 'sequence', - 'mapping' -]; - -function compileStyleAliases(map) { - var result = {}; +const EventEmitter = __nccwpck_require__(82361); +const JSONB = __nccwpck_require__(22820); - if (map !== null) { - Object.keys(map).forEach(function (style) { - map[style].forEach(function (alias) { - result[String(alias)] = style; - }); - }); - } +const loadStore = options => { + const adapters = { + redis: '@keyv/redis', + rediss: '@keyv/redis', + mongodb: '@keyv/mongo', + mongo: '@keyv/mongo', + sqlite: '@keyv/sqlite', + postgresql: '@keyv/postgres', + postgres: '@keyv/postgres', + mysql: '@keyv/mysql', + etcd: '@keyv/etcd', + offline: '@keyv/offline', + tiered: '@keyv/tiered', + }; + if (options.adapter || options.uri) { + const adapter = options.adapter || /^[^:+]*/.exec(options.uri)[0]; + return new (require(adapters[adapter]))(options); + } - return result; -} + return new Map(); +}; -function Type(tag, options) { - options = options || {}; +const iterableAdapters = [ + 'sqlite', + 'postgres', + 'mysql', + 'mongo', + 'redis', + 'tiered', +]; - Object.keys(options).forEach(function (name) { - if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { - throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); - } - }); +class Keyv extends EventEmitter { + constructor(uri, {emitErrors = true, ...options} = {}) { + super(); + this.opts = { + namespace: 'keyv', + serialize: JSONB.stringify, + deserialize: JSONB.parse, + ...((typeof uri === 'string') ? {uri} : uri), + ...options, + }; - // TODO: Add tag format check. - this.options = options; // keep original options in case user wants to extend this type later - this.tag = tag; - this.kind = options['kind'] || null; - this.resolve = options['resolve'] || function () { return true; }; - this.construct = options['construct'] || function (data) { return data; }; - this.instanceOf = options['instanceOf'] || null; - this.predicate = options['predicate'] || null; - this.represent = options['represent'] || null; - this.representName = options['representName'] || null; - this.defaultStyle = options['defaultStyle'] || null; - this.multi = options['multi'] || false; - this.styleAliases = compileStyleAliases(options['styleAliases'] || null); + if (!this.opts.store) { + const adapterOptions = {...this.opts}; + this.opts.store = loadStore(adapterOptions); + } - if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { - throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); - } -} + if (this.opts.compression) { + const compression = this.opts.compression; + this.opts.serialize = compression.serialize.bind(compression); + this.opts.deserialize = compression.deserialize.bind(compression); + } -module.exports = Type; + if (typeof this.opts.store.on === 'function' && emitErrors) { + this.opts.store.on('error', error => this.emit('error', error)); + } + this.opts.store.namespace = this.opts.namespace; -/***/ }), + const generateIterator = iterator => async function * () { + for await (const [key, raw] of typeof iterator === 'function' + ? iterator(this.opts.store.namespace) + : iterator) { + const data = await this.opts.deserialize(raw); + if (this.opts.store.namespace && !key.includes(this.opts.store.namespace)) { + continue; + } -/***/ 77900: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (typeof data.expires === 'number' && Date.now() > data.expires) { + this.delete(key); + continue; + } -"use strict"; + yield [this._getKeyUnprefix(key), data.value]; + } + }; + // Attach iterators + if (typeof this.opts.store[Symbol.iterator] === 'function' && this.opts.store instanceof Map) { + this.iterator = generateIterator(this.opts.store); + } else if (typeof this.opts.store.iterator === 'function' && this.opts.store.opts + && this._checkIterableAdaptar()) { + this.iterator = generateIterator(this.opts.store.iterator.bind(this.opts.store)); + } + } -/*eslint-disable no-bitwise*/ + _checkIterableAdaptar() { + return iterableAdapters.includes(this.opts.store.opts.dialect) + || iterableAdapters.findIndex(element => this.opts.store.opts.url.includes(element)) >= 0; + } + _getKeyPrefix(key) { + return `${this.opts.namespace}:${key}`; + } -var Type = __nccwpck_require__(6073); + _getKeyPrefixArray(keys) { + return keys.map(key => `${this.opts.namespace}:${key}`); + } + _getKeyUnprefix(key) { + return key + .split(':') + .splice(1) + .join(':'); + } -// [ 64, 65, 66 ] -> [ padding, CR, LF ] -var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; + get(key, options) { + const {store} = this.opts; + const isArray = Array.isArray(key); + const keyPrefixed = isArray ? this._getKeyPrefixArray(key) : this._getKeyPrefix(key); + if (isArray && store.getMany === undefined) { + const promises = []; + for (const key of keyPrefixed) { + promises.push(Promise.resolve() + .then(() => store.get(key)) + .then(data => (typeof data === 'string') ? this.opts.deserialize(data) : (this.opts.compression ? this.opts.deserialize(data) : data)) + .then(data => { + if (data === undefined || data === null) { + return undefined; + } + if (typeof data.expires === 'number' && Date.now() > data.expires) { + return this.delete(key).then(() => undefined); + } -function resolveYamlBinary(data) { - if (data === null) return false; + return (options && options.raw) ? data : data.value; + }), + ); + } - var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; + return Promise.allSettled(promises) + .then(values => { + const data = []; + for (const value of values) { + data.push(value.value); + } - // Convert one by one. - for (idx = 0; idx < max; idx++) { - code = map.indexOf(data.charAt(idx)); + return data; + }); + } - // Skip CR/LF - if (code > 64) continue; + return Promise.resolve() + .then(() => isArray ? store.getMany(keyPrefixed) : store.get(keyPrefixed)) + .then(data => (typeof data === 'string') ? this.opts.deserialize(data) : (this.opts.compression ? this.opts.deserialize(data) : data)) + .then(data => { + if (data === undefined || data === null) { + return undefined; + } - // Fail on illegal characters - if (code < 0) return false; + if (isArray) { + const result = []; - bitlen += 6; - } + for (let row of data) { + if ((typeof row === 'string')) { + row = this.opts.deserialize(row); + } - // If there are any bits left, source was corrupted - return (bitlen % 8) === 0; -} + if (row === undefined || row === null) { + result.push(undefined); + continue; + } -function constructYamlBinary(data) { - var idx, tailbits, - input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan - max = input.length, - map = BASE64_MAP, - bits = 0, - result = []; + if (typeof row.expires === 'number' && Date.now() > row.expires) { + this.delete(key).then(() => undefined); + result.push(undefined); + } else { + result.push((options && options.raw) ? row : row.value); + } + } - // Collect by 6*4 bits (3 bytes) + return result; + } - for (idx = 0; idx < max; idx++) { - if ((idx % 4 === 0) && idx) { - result.push((bits >> 16) & 0xFF); - result.push((bits >> 8) & 0xFF); - result.push(bits & 0xFF); - } + if (typeof data.expires === 'number' && Date.now() > data.expires) { + return this.delete(key).then(() => undefined); + } - bits = (bits << 6) | map.indexOf(input.charAt(idx)); - } + return (options && options.raw) ? data : data.value; + }); + } - // Dump tail + set(key, value, ttl) { + const keyPrefixed = this._getKeyPrefix(key); + if (typeof ttl === 'undefined') { + ttl = this.opts.ttl; + } - tailbits = (max % 4) * 6; + if (ttl === 0) { + ttl = undefined; + } - if (tailbits === 0) { - result.push((bits >> 16) & 0xFF); - result.push((bits >> 8) & 0xFF); - result.push(bits & 0xFF); - } else if (tailbits === 18) { - result.push((bits >> 10) & 0xFF); - result.push((bits >> 2) & 0xFF); - } else if (tailbits === 12) { - result.push((bits >> 4) & 0xFF); - } + const {store} = this.opts; - return new Uint8Array(result); -} + return Promise.resolve() + .then(() => { + const expires = (typeof ttl === 'number') ? (Date.now() + ttl) : null; + if (typeof value === 'symbol') { + this.emit('error', 'symbol cannot be serialized'); + } -function representYamlBinary(object /*, style*/) { - var result = '', bits = 0, idx, tail, - max = object.length, - map = BASE64_MAP; + value = {value, expires}; + return this.opts.serialize(value); + }) + .then(value => store.set(keyPrefixed, value, ttl)) + .then(() => true); + } - // Convert every three bytes to 4 ASCII characters. + delete(key) { + const {store} = this.opts; + if (Array.isArray(key)) { + const keyPrefixed = this._getKeyPrefixArray(key); + if (store.deleteMany === undefined) { + const promises = []; + for (const key of keyPrefixed) { + promises.push(store.delete(key)); + } - for (idx = 0; idx < max; idx++) { - if ((idx % 3 === 0) && idx) { - result += map[(bits >> 18) & 0x3F]; - result += map[(bits >> 12) & 0x3F]; - result += map[(bits >> 6) & 0x3F]; - result += map[bits & 0x3F]; - } + return Promise.allSettled(promises) + .then(values => values.every(x => x.value === true)); + } - bits = (bits << 8) + object[idx]; - } + return Promise.resolve() + .then(() => store.deleteMany(keyPrefixed)); + } - // Dump tail + const keyPrefixed = this._getKeyPrefix(key); + return Promise.resolve() + .then(() => store.delete(keyPrefixed)); + } - tail = max % 3; + clear() { + const {store} = this.opts; + return Promise.resolve() + .then(() => store.clear()); + } - if (tail === 0) { - result += map[(bits >> 18) & 0x3F]; - result += map[(bits >> 12) & 0x3F]; - result += map[(bits >> 6) & 0x3F]; - result += map[bits & 0x3F]; - } else if (tail === 2) { - result += map[(bits >> 10) & 0x3F]; - result += map[(bits >> 4) & 0x3F]; - result += map[(bits << 2) & 0x3F]; - result += map[64]; - } else if (tail === 1) { - result += map[(bits >> 2) & 0x3F]; - result += map[(bits << 4) & 0x3F]; - result += map[64]; - result += map[64]; - } + has(key) { + const keyPrefixed = this._getKeyPrefix(key); + const {store} = this.opts; + return Promise.resolve() + .then(async () => { + if (typeof store.has === 'function') { + return store.has(keyPrefixed); + } - return result; -} + const value = await store.get(keyPrefixed); + return value !== undefined; + }); + } -function isBinary(obj) { - return Object.prototype.toString.call(obj) === '[object Uint8Array]'; + disconnect() { + const {store} = this.opts; + if (typeof store.disconnect === 'function') { + return store.disconnect(); + } + } } -module.exports = new Type('tag:yaml.org,2002:binary', { - kind: 'scalar', - resolve: resolveYamlBinary, - construct: constructYamlBinary, - predicate: isBinary, - represent: representYamlBinary -}); +module.exports = Keyv; /***/ }), -/***/ 64993: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 9662: +/***/ ((module) => { "use strict"; +module.exports = object => { + const result = {}; -var Type = __nccwpck_require__(6073); - -function resolveYamlBoolean(data) { - if (data === null) return false; - - var max = data.length; - - return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || - (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); -} - -function constructYamlBoolean(data) { - return data === 'true' || - data === 'True' || - data === 'TRUE'; -} - -function isBoolean(object) { - return Object.prototype.toString.call(object) === '[object Boolean]'; -} + for (const [key, value] of Object.entries(object)) { + result[key.toLowerCase()] = value; + } -module.exports = new Type('tag:yaml.org,2002:bool', { - kind: 'scalar', - resolve: resolveYamlBoolean, - construct: constructYamlBoolean, - predicate: isBoolean, - represent: { - lowercase: function (object) { return object ? 'true' : 'false'; }, - uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, - camelcase: function (object) { return object ? 'True' : 'False'; } - }, - defaultStyle: 'lowercase' -}); + return result; +}; /***/ }), -/***/ 42705: +/***/ 7129: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var common = __nccwpck_require__(26829); -var Type = __nccwpck_require__(6073); - -var YAML_FLOAT_PATTERN = new RegExp( - // 2.5e4, 2.5 and integers - '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + - // .2e4, .2 - // special case, seems not from spec - '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + - // .inf - '|[-+]?\\.(?:inf|Inf|INF)' + - // .nan - '|\\.(?:nan|NaN|NAN))$'); +// A linked list to keep track of recently-used-ness +const Yallist = __nccwpck_require__(40665) -function resolveYamlFloat(data) { - if (data === null) return false; +const MAX = Symbol('max') +const LENGTH = Symbol('length') +const LENGTH_CALCULATOR = Symbol('lengthCalculator') +const ALLOW_STALE = Symbol('allowStale') +const MAX_AGE = Symbol('maxAge') +const DISPOSE = Symbol('dispose') +const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') +const LRU_LIST = Symbol('lruList') +const CACHE = Symbol('cache') +const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') - if (!YAML_FLOAT_PATTERN.test(data) || - // Quick hack to not allow integers end with `_` - // Probably should update regexp & check speed - data[data.length - 1] === '_') { - return false; - } +const naiveLength = () => 1 - return true; -} +// lruList is a yallist where the head is the youngest +// item, and the tail is the oldest. the list contains the Hit +// objects as the entries. +// Each Hit object has a reference to its Yallist.Node. This +// never changes. +// +// cache is a Map (or PseudoMap) that matches the keys to +// the Yallist.Node object. +class LRUCache { + constructor (options) { + if (typeof options === 'number') + options = { max: options } -function constructYamlFloat(data) { - var value, sign; + if (!options) + options = {} - value = data.replace(/_/g, '').toLowerCase(); - sign = value[0] === '-' ? -1 : 1; + if (options.max && (typeof options.max !== 'number' || options.max < 0)) + throw new TypeError('max must be a non-negative number') + // Kind of weird to have a default max of Infinity, but oh well. + const max = this[MAX] = options.max || Infinity - if ('+-'.indexOf(value[0]) >= 0) { - value = value.slice(1); + const lc = options.length || naiveLength + this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc + this[ALLOW_STALE] = options.stale || false + if (options.maxAge && typeof options.maxAge !== 'number') + throw new TypeError('maxAge must be a number') + this[MAX_AGE] = options.maxAge || 0 + this[DISPOSE] = options.dispose + this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false + this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false + this.reset() } - if (value === '.inf') { - return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; + // resize the cache when the max changes. + set max (mL) { + if (typeof mL !== 'number' || mL < 0) + throw new TypeError('max must be a non-negative number') - } else if (value === '.nan') { - return NaN; + this[MAX] = mL || Infinity + trim(this) + } + get max () { + return this[MAX] } - return sign * parseFloat(value, 10); -} + set allowStale (allowStale) { + this[ALLOW_STALE] = !!allowStale + } + get allowStale () { + return this[ALLOW_STALE] + } -var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; + set maxAge (mA) { + if (typeof mA !== 'number') + throw new TypeError('maxAge must be a non-negative number') -function representYamlFloat(object, style) { - var res; + this[MAX_AGE] = mA + trim(this) + } + get maxAge () { + return this[MAX_AGE] + } - if (isNaN(object)) { - switch (style) { - case 'lowercase': return '.nan'; - case 'uppercase': return '.NAN'; - case 'camelcase': return '.NaN'; - } - } else if (Number.POSITIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '.inf'; - case 'uppercase': return '.INF'; - case 'camelcase': return '.Inf'; - } - } else if (Number.NEGATIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '-.inf'; - case 'uppercase': return '-.INF'; - case 'camelcase': return '-.Inf'; + // resize the cache when the lengthCalculator changes. + set lengthCalculator (lC) { + if (typeof lC !== 'function') + lC = naiveLength + + if (lC !== this[LENGTH_CALCULATOR]) { + this[LENGTH_CALCULATOR] = lC + this[LENGTH] = 0 + this[LRU_LIST].forEach(hit => { + hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) + this[LENGTH] += hit.length + }) } - } else if (common.isNegativeZero(object)) { - return '-0.0'; + trim(this) } + get lengthCalculator () { return this[LENGTH_CALCULATOR] } - res = object.toString(10); - - // JS stringifier can build scientific format without dots: 5e-100, - // while YAML requres dot: 5.e-100. Fix it with simple hack + get length () { return this[LENGTH] } + get itemCount () { return this[LRU_LIST].length } - return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; -} + rforEach (fn, thisp) { + thisp = thisp || this + for (let walker = this[LRU_LIST].tail; walker !== null;) { + const prev = walker.prev + forEachStep(this, fn, walker, thisp) + walker = prev + } + } -function isFloat(object) { - return (Object.prototype.toString.call(object) === '[object Number]') && - (object % 1 !== 0 || common.isNegativeZero(object)); -} + forEach (fn, thisp) { + thisp = thisp || this + for (let walker = this[LRU_LIST].head; walker !== null;) { + const next = walker.next + forEachStep(this, fn, walker, thisp) + walker = next + } + } -module.exports = new Type('tag:yaml.org,2002:float', { - kind: 'scalar', - resolve: resolveYamlFloat, - construct: constructYamlFloat, - predicate: isFloat, - represent: representYamlFloat, - defaultStyle: 'lowercase' -}); + keys () { + return this[LRU_LIST].toArray().map(k => k.key) + } + values () { + return this[LRU_LIST].toArray().map(k => k.value) + } -/***/ }), + reset () { + if (this[DISPOSE] && + this[LRU_LIST] && + this[LRU_LIST].length) { + this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) + } -/***/ 11615: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this[CACHE] = new Map() // hash of items by key + this[LRU_LIST] = new Yallist() // list of items in order of use recency + this[LENGTH] = 0 // length of items in the list + } -"use strict"; + dump () { + return this[LRU_LIST].map(hit => + isStale(this, hit) ? false : { + k: hit.key, + v: hit.value, + e: hit.now + (hit.maxAge || 0) + }).toArray().filter(h => h) + } + dumpLru () { + return this[LRU_LIST] + } -var common = __nccwpck_require__(26829); -var Type = __nccwpck_require__(6073); + set (key, value, maxAge) { + maxAge = maxAge || this[MAX_AGE] -function isHexCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || - ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || - ((0x61/* a */ <= c) && (c <= 0x66/* f */)); -} + if (maxAge && typeof maxAge !== 'number') + throw new TypeError('maxAge must be a number') -function isOctCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); -} + const now = maxAge ? Date.now() : 0 + const len = this[LENGTH_CALCULATOR](value, key) -function isDecCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); -} + if (this[CACHE].has(key)) { + if (len > this[MAX]) { + del(this, this[CACHE].get(key)) + return false + } -function resolveYamlInteger(data) { - if (data === null) return false; + const node = this[CACHE].get(key) + const item = node.value - var max = data.length, - index = 0, - hasDigits = false, - ch; + // dispose of the old one before overwriting + // split out into 2 ifs for better coverage tracking + if (this[DISPOSE]) { + if (!this[NO_DISPOSE_ON_SET]) + this[DISPOSE](key, item.value) + } - if (!max) return false; + item.now = now + item.maxAge = maxAge + item.value = value + this[LENGTH] += len - item.length + item.length = len + this.get(key) + trim(this) + return true + } - ch = data[index]; + const hit = new Entry(key, value, len, now, maxAge) - // sign - if (ch === '-' || ch === '+') { - ch = data[++index]; - } + // oversized objects fall out of cache automatically. + if (hit.length > this[MAX]) { + if (this[DISPOSE]) + this[DISPOSE](key, value) - if (ch === '0') { - // 0 - if (index + 1 === max) return true; - ch = data[++index]; + return false + } - // base 2, base 8, base 16 + this[LENGTH] += hit.length + this[LRU_LIST].unshift(hit) + this[CACHE].set(key, this[LRU_LIST].head) + trim(this) + return true + } - if (ch === 'b') { - // base 2 - index++; + has (key) { + if (!this[CACHE].has(key)) return false + const hit = this[CACHE].get(key).value + return !isStale(this, hit) + } - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (ch !== '0' && ch !== '1') return false; - hasDigits = true; - } - return hasDigits && ch !== '_'; - } + get (key) { + return get(this, key, true) + } + peek (key) { + return get(this, key, false) + } - if (ch === 'x') { - // base 16 - index++; + pop () { + const node = this[LRU_LIST].tail + if (!node) + return null - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isHexCode(data.charCodeAt(index))) return false; - hasDigits = true; - } - return hasDigits && ch !== '_'; - } + del(this, node) + return node.value + } + del (key) { + del(this, this[CACHE].get(key)) + } - if (ch === 'o') { - // base 8 - index++; + load (arr) { + // reset the cache + this.reset() - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isOctCode(data.charCodeAt(index))) return false; - hasDigits = true; + const now = Date.now() + // A previous serialized cache has the most recent items first + for (let l = arr.length - 1; l >= 0; l--) { + const hit = arr[l] + const expiresAt = hit.e || 0 + if (expiresAt === 0) + // the item was created without expiration in a non aged cache + this.set(hit.k, hit.v) + else { + const maxAge = expiresAt - now + // dont add already expired items + if (maxAge > 0) { + this.set(hit.k, hit.v, maxAge) + } } - return hasDigits && ch !== '_'; } } - // base 10 (except 0) - - // value should not start with `_`; - if (ch === '_') return false; + prune () { + this[CACHE].forEach((value, key) => get(this, key, false)) + } +} - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isDecCode(data.charCodeAt(index))) { - return false; +const get = (self, key, doUse) => { + const node = self[CACHE].get(key) + if (node) { + const hit = node.value + if (isStale(self, hit)) { + del(self, node) + if (!self[ALLOW_STALE]) + return undefined + } else { + if (doUse) { + if (self[UPDATE_AGE_ON_GET]) + node.value.now = Date.now() + self[LRU_LIST].unshiftNode(node) + } } - hasDigits = true; + return hit.value } +} - // Should have digits and should not end with `_` - if (!hasDigits || ch === '_') return false; +const isStale = (self, hit) => { + if (!hit || (!hit.maxAge && !self[MAX_AGE])) + return false - return true; + const diff = Date.now() - hit.now + return hit.maxAge ? diff > hit.maxAge + : self[MAX_AGE] && (diff > self[MAX_AGE]) } -function constructYamlInteger(data) { - var value = data, sign = 1, ch; - - if (value.indexOf('_') !== -1) { - value = value.replace(/_/g, ''); +const trim = self => { + if (self[LENGTH] > self[MAX]) { + for (let walker = self[LRU_LIST].tail; + self[LENGTH] > self[MAX] && walker !== null;) { + // We know that we're about to delete this one, and also + // what the next least recently used key will be, so just + // go ahead and set it now. + const prev = walker.prev + del(self, walker) + walker = prev + } } +} - ch = value[0]; +const del = (self, node) => { + if (node) { + const hit = node.value + if (self[DISPOSE]) + self[DISPOSE](hit.key, hit.value) - if (ch === '-' || ch === '+') { - if (ch === '-') sign = -1; - value = value.slice(1); - ch = value[0]; + self[LENGTH] -= hit.length + self[CACHE].delete(hit.key) + self[LRU_LIST].removeNode(node) } +} - if (value === '0') return 0; - - if (ch === '0') { - if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); - if (value[1] === 'x') return sign * parseInt(value.slice(2), 16); - if (value[1] === 'o') return sign * parseInt(value.slice(2), 8); +class Entry { + constructor (key, value, length, now, maxAge) { + this.key = key + this.value = value + this.length = length + this.now = now + this.maxAge = maxAge || 0 } - - return sign * parseInt(value, 10); } -function isInteger(object) { - return (Object.prototype.toString.call(object)) === '[object Number]' && - (object % 1 === 0 && !common.isNegativeZero(object)); +const forEachStep = (self, fn, node, thisp) => { + let hit = node.value + if (isStale(self, hit)) { + del(self, node) + if (!self[ALLOW_STALE]) + hit = undefined + } + if (hit) + fn.call(thisp, hit.value, hit.key, self) } -module.exports = new Type('tag:yaml.org,2002:int', { - kind: 'scalar', - resolve: resolveYamlInteger, - construct: constructYamlInteger, - predicate: isInteger, - represent: { - binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, - octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); }, - decimal: function (obj) { return obj.toString(10); }, - /* eslint-disable max-len */ - hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } - }, - defaultStyle: 'decimal', - styleAliases: { - binary: [ 2, 'bin' ], - octal: [ 8, 'oct' ], - decimal: [ 10, 'dec' ], - hexadecimal: [ 16, 'hex' ] - } -}); +module.exports = LRUCache /***/ }), -/***/ 86150: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 21381: +/***/ ((module, exports) => { "use strict"; +// ISC @ Julien Fontanet -var Type = __nccwpck_require__(6073); - -module.exports = new Type('tag:yaml.org,2002:map', { - kind: 'mapping', - construct: function (data) { return data !== null ? data : {}; } -}); +// =================================================================== -/***/ }), +var construct = typeof Reflect !== "undefined" ? Reflect.construct : undefined; +var defineProperty = Object.defineProperty; -/***/ 86104: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// ------------------------------------------------------------------- -"use strict"; +var captureStackTrace = Error.captureStackTrace; +if (captureStackTrace === undefined) { + captureStackTrace = function captureStackTrace(error) { + var container = new Error(); + defineProperty(error, "stack", { + configurable: true, + get: function getStack() { + var stack = container.stack; -var Type = __nccwpck_require__(6073); + // Replace property with value for faster future accesses. + defineProperty(this, "stack", { + configurable: true, + value: stack, + writable: true, + }); -function resolveYamlMerge(data) { - return data === '<<' || data === null; + return stack; + }, + set: function setStack(stack) { + defineProperty(error, "stack", { + configurable: true, + value: stack, + writable: true, + }); + }, + }); + }; } -module.exports = new Type('tag:yaml.org,2002:merge', { - kind: 'scalar', - resolve: resolveYamlMerge -}); - - -/***/ }), - -/***/ 20721: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var Type = __nccwpck_require__(6073); - -function resolveYamlNull(data) { - if (data === null) return true; - - var max = data.length; +// ------------------------------------------------------------------- - return (max === 1 && data === '~') || - (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); -} +function BaseError(message) { + if (message !== undefined) { + defineProperty(this, "message", { + configurable: true, + value: message, + writable: true, + }); + } -function constructYamlNull() { - return null; -} + var cname = this.constructor.name; + if (cname !== undefined && cname !== this.name) { + defineProperty(this, "name", { + configurable: true, + value: cname, + writable: true, + }); + } -function isNull(object) { - return object === null; + captureStackTrace(this, this.constructor); } -module.exports = new Type('tag:yaml.org,2002:null', { - kind: 'scalar', - resolve: resolveYamlNull, - construct: constructYamlNull, - predicate: isNull, - represent: { - canonical: function () { return '~'; }, - lowercase: function () { return 'null'; }, - uppercase: function () { return 'NULL'; }, - camelcase: function () { return 'Null'; }, - empty: function () { return ''; } +BaseError.prototype = Object.create(Error.prototype, { + // See: https://github.com/JsCommunity/make-error/issues/4 + constructor: { + configurable: true, + value: BaseError, + writable: true, }, - defaultStyle: 'lowercase' }); +// ------------------------------------------------------------------- -/***/ }), - -/***/ 19046: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var Type = __nccwpck_require__(6073); - -var _hasOwnProperty = Object.prototype.hasOwnProperty; -var _toString = Object.prototype.toString; - -function resolveYamlOmap(data) { - if (data === null) return true; +// Sets the name of a function if possible (depends of the JS engine). +var setFunctionName = (function() { + function setFunctionName(fn, name) { + return defineProperty(fn, "name", { + configurable: true, + value: name, + }); + } + try { + var f = function() {}; + setFunctionName(f, "foo"); + if (f.name === "foo") { + return setFunctionName; + } + } catch (_) {} +})(); - var objectKeys = [], index, length, pair, pairKey, pairHasKey, - object = data; +// ------------------------------------------------------------------- - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - pairHasKey = false; +function makeError(constructor, super_) { + if (super_ == null || super_ === Error) { + super_ = BaseError; + } else if (typeof super_ !== "function") { + throw new TypeError("super_ should be a function"); + } - if (_toString.call(pair) !== '[object Object]') return false; + var name; + if (typeof constructor === "string") { + name = constructor; + constructor = + construct !== undefined + ? function() { + return construct(super_, arguments, this.constructor); + } + : function() { + super_.apply(this, arguments); + }; - for (pairKey in pair) { - if (_hasOwnProperty.call(pair, pairKey)) { - if (!pairHasKey) pairHasKey = true; - else return false; - } + // If the name can be set, do it once and for all. + if (setFunctionName !== undefined) { + setFunctionName(constructor, name); + name = undefined; } + } else if (typeof constructor !== "function") { + throw new TypeError("constructor should be either a string or a function"); + } - if (!pairHasKey) return false; + // Also register the super constructor also as `constructor.super_` just + // like Node's `util.inherits()`. + // + // eslint-disable-next-line dot-notation + constructor.super_ = constructor["super"] = super_; - if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); - else return false; - } + var properties = { + constructor: { + configurable: true, + value: constructor, + writable: true, + }, + }; - return true; -} + // If the name could not be set on the constructor, set it on the + // prototype. + if (name !== undefined) { + properties.name = { + configurable: true, + value: name, + writable: true, + }; + } + constructor.prototype = Object.create(super_.prototype, properties); -function constructYamlOmap(data) { - return data !== null ? data : []; + return constructor; } - -module.exports = new Type('tag:yaml.org,2002:omap', { - kind: 'sequence', - resolve: resolveYamlOmap, - construct: constructYamlOmap -}); +exports = module.exports = makeError; +exports.BaseError = BaseError; /***/ }), -/***/ 96860: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 19775: +/***/ ((module) => { "use strict"; -var Type = __nccwpck_require__(6073); +/** @type {import('./abs')} */ +module.exports = Math.abs; -var _toString = Object.prototype.toString; -function resolveYamlPairs(data) { - if (data === null) return true; +/***/ }), - var index, length, pair, keys, result, - object = data; +/***/ 60924: +/***/ ((module) => { - result = new Array(object.length); +"use strict"; - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - if (_toString.call(pair) !== '[object Object]') return false; +/** @type {import('./floor')} */ +module.exports = Math.floor; - keys = Object.keys(pair); - if (keys.length !== 1) return false; +/***/ }), - result[index] = [ keys[0], pair[keys[0]] ]; - } +/***/ 57661: +/***/ ((module) => { - return true; -} +"use strict"; -function constructYamlPairs(data) { - if (data === null) return []; - var index, length, pair, keys, result, - object = data; +/** @type {import('./isNaN')} */ +module.exports = Number.isNaN || function isNaN(a) { + return a !== a; +}; - result = new Array(object.length); - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; +/***/ }), - keys = Object.keys(pair); +/***/ 52419: +/***/ ((module) => { - result[index] = [ keys[0], pair[keys[0]] ]; - } +"use strict"; - return result; -} -module.exports = new Type('tag:yaml.org,2002:pairs', { - kind: 'sequence', - resolve: resolveYamlPairs, - construct: constructYamlPairs -}); +/** @type {import('./max')} */ +module.exports = Math.max; /***/ }), -/***/ 67283: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 73373: +/***/ ((module) => { "use strict"; -var Type = __nccwpck_require__(6073); - -module.exports = new Type('tag:yaml.org,2002:seq', { - kind: 'sequence', - construct: function (data) { return data !== null ? data : []; } -}); +/** @type {import('./min')} */ +module.exports = Math.min; /***/ }), -/***/ 79548: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 78029: +/***/ ((module) => { "use strict"; -var Type = __nccwpck_require__(6073); - -var _hasOwnProperty = Object.prototype.hasOwnProperty; +/** @type {import('./pow')} */ +module.exports = Math.pow; -function resolveYamlSet(data) { - if (data === null) return true; - var key, object = data; +/***/ }), - for (key in object) { - if (_hasOwnProperty.call(object, key)) { - if (object[key] !== null) return false; - } - } +/***/ 59396: +/***/ ((module) => { - return true; -} +"use strict"; -function constructYamlSet(data) { - return data !== null ? data : {}; -} -module.exports = new Type('tag:yaml.org,2002:set', { - kind: 'mapping', - resolve: resolveYamlSet, - construct: constructYamlSet -}); +/** @type {import('./round')} */ +module.exports = Math.round; /***/ }), -/***/ 23619: +/***/ 39091: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var Type = __nccwpck_require__(6073); +var $isNaN = __nccwpck_require__(57661); -module.exports = new Type('tag:yaml.org,2002:str', { - kind: 'scalar', - construct: function (data) { return data !== null ? data : ''; } -}); +/** @type {import('./sign')} */ +module.exports = function sign(number) { + if ($isNaN(number) || number === 0) { + return number; + } + return number < 0 ? -1 : +1; +}; /***/ }), -/***/ 99212: +/***/ 2621: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var Type = __nccwpck_require__(6073); - -var YAML_DATE_REGEXP = new RegExp( - '^([0-9][0-9][0-9][0-9])' + // [1] year - '-([0-9][0-9])' + // [2] month - '-([0-9][0-9])$'); // [3] day +const { PassThrough } = __nccwpck_require__(12781); -var YAML_TIMESTAMP_REGEXP = new RegExp( - '^([0-9][0-9][0-9][0-9])' + // [1] year - '-([0-9][0-9]?)' + // [2] month - '-([0-9][0-9]?)' + // [3] day - '(?:[Tt]|[ \\t]+)' + // ... - '([0-9][0-9]?)' + // [4] hour - ':([0-9][0-9])' + // [5] minute - ':([0-9][0-9])' + // [6] second - '(?:\\.([0-9]*))?' + // [7] fraction - '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour - '(?::([0-9][0-9]))?))?$'); // [11] tz_minute +module.exports = function (/*streams...*/) { + var sources = [] + var output = new PassThrough({objectMode: true}) -function resolveYamlTimestamp(data) { - if (data === null) return false; - if (YAML_DATE_REGEXP.exec(data) !== null) return true; - if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; - return false; -} + output.setMaxListeners(0) -function constructYamlTimestamp(data) { - var match, year, month, day, hour, minute, second, fraction = 0, - delta = null, tz_hour, tz_minute, date; + output.add = add + output.isEmpty = isEmpty - match = YAML_DATE_REGEXP.exec(data); - if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); + output.on('unpipe', remove) - if (match === null) throw new Error('Date resolve error'); + Array.prototype.slice.call(arguments).forEach(add) - // match: [1] year [2] month [3] day + return output - year = +(match[1]); - month = +(match[2]) - 1; // JS month starts with 0 - day = +(match[3]); + function add (source) { + if (Array.isArray(source)) { + source.forEach(add) + return this + } - if (!match[4]) { // no hour - return new Date(Date.UTC(year, month, day)); + sources.push(source); + source.once('end', remove.bind(null, source)) + source.once('error', output.emit.bind(output, 'error')) + source.pipe(output, {end: false}) + return this } - // match: [4] hour [5] minute [6] second [7] fraction - - hour = +(match[4]); - minute = +(match[5]); - second = +(match[6]); - - if (match[7]) { - fraction = match[7].slice(0, 3); - while (fraction.length < 3) { // milli-seconds - fraction += '0'; - } - fraction = +fraction; + function isEmpty () { + return sources.length == 0; } - // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute - - if (match[9]) { - tz_hour = +(match[10]); - tz_minute = +(match[11] || 0); - delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds - if (match[9] === '-') delta = -delta; + function remove (source) { + sources = sources.filter(function (it) { return it !== source }) + if (!sources.length && output.readable) { output.end() } } - - date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); - - if (delta) date.setTime(date.getTime() - delta); - - return date; -} - -function representYamlTimestamp(object /*, style*/) { - return object.toISOString(); } -module.exports = new Type('tag:yaml.org,2002:timestamp', { - kind: 'scalar', - resolve: resolveYamlTimestamp, - construct: constructYamlTimestamp, - instanceOf: Date, - represent: representYamlTimestamp -}); - /***/ }), -/***/ 85587: -/***/ (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; - } - - BigInteger.prototype.DB = dbits; - BigInteger.prototype.DM = ((1<= 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; } +/***/ 47426: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // (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; - } +/** + * Module exports. + */ - // (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"; - } +module.exports = __nccwpck_require__(53765) - // (public) -this - function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } - // (public) |this| - function bnAbs() { return (this.s<0)?this.negate():this; } +/***/ }), - // (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; - } +/***/ 43583: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // 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; - } +"use strict"; +/*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ - // (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)); - } - // (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; - } - // (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; - } +/** + * Module dependencies. + * @private + */ - // (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(); - } +var db = __nccwpck_require__(47426) +var extname = (__nccwpck_require__(71017).extname) - // (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(); - } +var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ +var TEXT_TYPE_REGEXP = /^text\//i - // (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); - } +/** + * Module exports. + * @public + */ - // (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(); - } +exports.charset = charset +exports.charsets = { lookup: charset } +exports.contentType = contentType +exports.extension = extension +exports.extensions = Object.create(null) +exports.lookup = lookup +exports.types = Object.create(null) - // (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); - } +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) - // (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; - } +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ - // 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); } +function charset (type) { + if (!type || typeof type !== 'string') { + return false + } - Classic.prototype.convert = cConvert; - Classic.prototype.revert = cRevert; - Classic.prototype.reduce = cReduce; - Classic.prototype.mulTo = cMulTo; - Classic.prototype.sqrTo = cSqrTo; + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + var mime = match && db[match[1].toLowerCase()] - // (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; - } + if (mime && mime.charset) { + return mime.charset + } - // 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; - } + // default text/* to utf-8 + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return 'UTF-8' + } - // 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; - } + return false +} - // x/R mod m - function montRevert(x) { - var r = nbi(); - x.copyTo(r); - this.reduce(r); - return r; - } +/** + * Create a full Content-Type header given a MIME type or extension. + * + * @param {string} str + * @return {boolean|string} + */ - // 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); - } +function contentType (str) { + // TODO: should this even be in this module? + if (!str || typeof str !== 'string') { + return false + } - // r = "x^2/R mod m"; x != r - function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); } + var mime = str.indexOf('/') === -1 + ? exports.lookup(str) + : str - // r = "xy/R mod m"; x,y != r - function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } + if (!mime) { + return false + } - Montgomery.prototype.convert = montConvert; - Montgomery.prototype.revert = montRevert; - Montgomery.prototype.reduce = montReduce; - Montgomery.prototype.mulTo = montMulTo; - Montgomery.prototype.sqrTo = montSqrTo; + // TODO: use content-type or other module + if (mime.indexOf('charset') === -1) { + var charset = exports.charset(mime) + if (charset) mime += '; charset=' + charset.toLowerCase() + } - // (protected) true iff this is even - function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; } + return mime +} - // (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); - } +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ - // (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); - } +function extension (type) { + if (!type || typeof type !== 'string') { + return false + } - // 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; + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) - // 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; + // get extensions + var exts = match && exports.extensions[match[1].toLowerCase()] - // "constants" - BigInteger.ZERO = nbv(0); - BigInteger.ONE = nbv(1); + if (!exts || !exts.length) { + return false + } - // Copyright (c) 2005-2009 Tom Wu - // All Rights Reserved. - // See "LICENSE" for details. + return exts[0] +} - // Extended JavaScript BN functions, required for RSA private ops. +/** + * Lookup the MIME type for a file path/extension. + * + * @param {string} path + * @return {boolean|string} + */ - // Version 1.1: new BigInteger("0", 10) returns "proper" zero - // Version 1.2: square() API, isProbablePrime fix +function lookup (path) { + if (!path || typeof path !== 'string') { + return false + } - // (public) - function bnClone() { var r = nbi(); this.copyTo(r); return r; } + // get the extension ("ext" or ".ext" or full path) + var extension = extname('x.' + path) + .toLowerCase() + .substr(1) - // (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; } + return exports.types[extension] || false +} - // (public) return value as short (assumes DB>=16) - function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; } +/** + * Populate the extensions and types maps. + * @private + */ - // (protected) return x s.t. r^x < DV - function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); } +function populateMaps (extensions, types) { + // source preference (least -> most) + var preference = ['nginx', 'apache', undefined, 'iana'] - // (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; - } + Object.keys(db).forEach(function forEachMimeType (type) { + var mime = db[type] + var exts = mime.extensions - // (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 (!exts || !exts.length) { + return } - // (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); - } + // mime -> extensions + extensions[type] = exts - // (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< mime + for (var i = 0; i < exts.length; i++) { + var extension = exts[i] - // (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; + if (types[extension]) { + var from = preference.indexOf(db[types[extension]].source) + var to = preference.indexOf(mime.source) + + if (types[extension] !== 'application/octet-stream' && + (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { + // skip the remapping + continue } } - return r; + + // set the extension -> mime + types[extension] = type } + }) +} - 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(); - } +/***/ }), - // (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; } +/***/ 76047: +/***/ ((module) => { - // (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; } +"use strict"; - // (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; } +const mimicFn = (to, from) => { + for (const prop of Reflect.ownKeys(from)) { + Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop)); + } - // (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; - } + return to; +}; - // (public) this << n - function bnShiftLeft(n) { - var r = nbi(); - if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); - return r; - } +module.exports = mimicFn; +// TODO: Remove this for the next major release +module.exports["default"] = mimicFn; - // (public) this >> n - function bnShiftRight(n) { - var r = nbi(); - if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); - return r; - } - // 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; - } +/***/ }), - // (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; - } +/***/ 42610: +/***/ ((module) => { - // return number of 1 bits in x - function cbit(x) { - var r = 0; - while(x != 0) { x &= x-1; ++r; } - return r; - } +"use strict"; - // (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; - } - // (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); - } +// We define these manually to ensure they're always copied +// even if they would move up the prototype chain +// https://nodejs.org/api/http.html#http_class_http_incomingmessage +const knownProperties = [ + 'aborted', + 'complete', + 'headers', + 'httpVersion', + 'httpVersionMinor', + 'httpVersionMajor', + 'method', + 'rawHeaders', + 'rawTrailers', + 'setTimeout', + 'socket', + 'statusCode', + 'statusMessage', + 'trailers', + 'url' +]; - // (protected) this op (1< { + if (toStream._readableState.autoDestroy) { + throw new Error('The second stream must have the `autoDestroy` option set to `false`'); + } - // (public) this | (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(); - } + properties[property] = { + get() { + const value = fromStream[property]; + const isFunction = typeof value === 'function'; - // (public) this + a - function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } + return isFunction ? value.bind(fromStream) : value; + }, + set(value) { + fromStream[property] = value; + }, + enumerable: true, + configurable: false + }; + } - // (public) this - a - function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } + Object.defineProperties(toStream, properties); - // (public) this * a - function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } + fromStream.once('aborted', () => { + toStream.destroy(); - // (public) this^2 - function bnSquare() { var r = nbi(); this.squareTo(r); return r; } + toStream.emit('aborted'); + }); - // (public) this / a - function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } + fromStream.once('close', () => { + if (fromStream.complete) { + if (toStream.readable) { + toStream.once('end', () => { + toStream.emit('close'); + }); + } else { + toStream.emit('close'); + } + } else { + toStream.emit('close'); + } + }); - // (public) this % a - function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } + return toStream; +}; - // (public) [this/a,this%a] - function bnDivideAndRemainder(a) { - var q = nbi(), r = nbi(); - this.divRemTo(a,q,r); - return new Array(q,r); - } - // (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]; - } - } +/***/ 83973: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 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); } +module.exports = minimatch +minimatch.Minimatch = Minimatch - NullExp.prototype.convert = nNop; - NullExp.prototype.revert = nNop; - NullExp.prototype.mulTo = nMulTo; - NullExp.prototype.sqrTo = nSqrTo; +var path = (function () { try { return __nccwpck_require__(71017) } catch (e) {}}()) || { + sep: '/' +} +minimatch.sep = path.sep - // (public) this^e - function bnPow(e) { return this.exp(e,new NullExp()); } +var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} +var expand = __nccwpck_require__(33717) - // (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(); - } +var plTypes = { + '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, + '?': { open: '(?:', close: ')?' }, + '+': { open: '(?:', close: ')+' }, + '*': { open: '(?:', close: ')*' }, + '@': { open: '(?:', close: ')' } +} - // (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); - } +// any single thing other than / +// don't need to escape / when using new RegExp() +var qmark = '[^/]' - // 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; - } +// * => any number of characters +var star = qmark + '*?' - 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; } - } +// ** 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})($|\\\/)).)*?' - function barrettRevert(x) { return x; } +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' - // 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); - } +// characters that need to be escaped in RegExp. +var reSpecials = charSet('().*{}+?[]^$\\!') - // r = x^2 mod m; x != r - function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } +// "abc" -> { a:true, b:true, c:true } +function charSet (s) { + return s.split('').reduce(function (set, c) { + set[c] = true + return set + }, {}) +} - // r = x*y mod m; x,y != r - function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } +// normalizes slashes. +var slashSplit = /\/+/ - Barrett.prototype.convert = barrettConvert; - Barrett.prototype.revert = barrettRevert; - Barrett.prototype.reduce = barrettReduce; - Barrett.prototype.mulTo = barrettMulTo; - Barrett.prototype.sqrTo = barrettSqrTo; +minimatch.filter = filter +function filter (pattern, options) { + options = options || {} + return function (p, i, list) { + return minimatch(p, pattern, options) + } +} - // (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); +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 +} - // 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; - } - } +minimatch.defaults = function (def) { + if (!def || typeof def !== 'object' || !Object.keys(def).length) { + return minimatch + } - 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); - } + var orig = minimatch - 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); - } + var m = function minimatch (p, pattern, options) { + return orig(p, pattern, ext(def, options)) + } - 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; - } + m.filter = function filter (pattern, options) { + return orig.filter(pattern, ext(def, options)) + } - // (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; - } + m.defaults = function defaults (options) { + return orig.defaults(ext(def, options)) + } - // (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(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; - } + m.makeRe = function makeRe (pattern, options) { + return orig.makeRe(pattern, ext(def, 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]; + m.braceExpand = function braceExpand (pattern, options) { + return orig.braceExpand(pattern, ext(def, options)) + } - // (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); - } + m.match = function (list, pattern, options) { + return orig.match(list, pattern, ext(def, options)) + } - // (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; - } + return m +} - // 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; +Minimatch.defaults = function (def) { + return minimatch.defaults(def).Minimatch +} - // 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; +function minimatch (p, pattern, options) { + assertValidPattern(pattern) - // JSBN-specific extension - BigInteger.prototype.square = bnSquare; + if (!options) options = {} - // Expose the Barrett function - BigInteger.prototype.Barrett = Barrett + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false + } - // BigInteger interfaces not implemented in jsbn: + return new Minimatch(pattern, options).match(p) +} - // BigInteger(int signum, byte[] magnitude) - // double doubleValue() - // float floatValue() - // int hashCode() - // long longValue() - // static BigInteger valueOf(long val) +function Minimatch (pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options) + } - // Random number generator - requires a PRNG backend, e.g. prng4.js + assertValidPattern(pattern) - // For best results, put code like - // - // in your main HTML document. + if (!options) options = {} - var rng_state; - var rng_pool; - var rng_pptr; + pattern = pattern.trim() - // 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; - } + // windows support: need to use /, not \ + if (!options.allowWindowsEscape && path.sep !== '/') { + pattern = pattern.split(path.sep).join('/') + } - // Mix in the current time (w/milliseconds) into the pool - function rng_seed_time() { - rng_seed_int(new Date().getTime()); - } + this.options = options + this.maxGlobstarRecursion = options.maxGlobstarRecursion !== undefined + ? options.maxGlobstarRecursion : 200 + this.set = [] + this.pattern = pattern + this.regexp = null + this.negate = false + this.comment = false + this.empty = false + this.partial = !!options.partial - // 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); - } + // make the set of regexps etc. + this.make() +} - 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(); - } +Minimatch.prototype.debug = function () {} - function rng_get_bytes(ba) { - var i; - for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte(); - } +Minimatch.prototype.make = make +function make () { + var pattern = this.pattern + var options = this.options - function SecureRandom() {} + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true + return + } + if (!pattern) { + this.empty = true + return + } - SecureRandom.prototype.nextBytes = rng_get_bytes; + // step 1: figure out negation, etc. + this.parseNegate() - // prng4.js - uses Arcfour as a PRNG + // step 2: expand braces + var set = this.globSet = this.braceExpand() - function Arcfour() { - this.i = 0; - this.j = 0; - this.S = new Array(); - } + if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) } - // 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; - } + this.debug(this.pattern, set) - 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]; - } + // 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) + }) - Arcfour.prototype.init = ARC4init; - Arcfour.prototype.next = ARC4next; + this.debug(this.pattern, set) - // Plug in your RNG constructor here - function prng_newstate() { - return new Arcfour(); - } + // glob --> regexps + set = set.map(function (s, si, set) { + return s.map(this.parse, this) + }, this) - // 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; + this.debug(this.pattern, set) - BigInteger.SecureRandom = SecureRandom; - BigInteger.BigInteger = BigInteger; - if (true) { - exports = module.exports = BigInteger; - } else {} + // filter out everything that didn't compile properly. + set = set.filter(function (s) { + return s.indexOf(false) === -1 + }) -}).call(this); + this.debug(this.pattern, set) + this.set = set +} -/***/ }), +Minimatch.prototype.parseNegate = parseNegate +function parseNegate () { + var pattern = this.pattern + var negate = false + var options = this.options + var negateOffset = 0 -/***/ 52533: -/***/ ((module) => { + if (options.nonegate) return -"use strict"; + 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 +} -var traverse = module.exports = function (schema, opts, cb) { - // Legacy support for v0.3.1 and earlier. - if (typeof opts == 'function') { - cb = opts; - opts = {}; +// 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 = {} + } } - cb = opts.cb || cb; - var pre = (typeof cb == 'function') ? cb : cb.pre || function() {}; - var post = cb.post || function() {}; + pattern = typeof pattern === 'undefined' + ? this.pattern : pattern - _traverse(opts, pre, post, schema, '', schema); -}; + 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] + } -traverse.keywords = { - additionalItems: true, - items: true, - contains: true, - additionalProperties: true, - propertyNames: true, - not: true -}; + return expand(pattern) +} -traverse.arrayKeywords = { - items: true, - allOf: true, - anyOf: true, - oneOf: true -}; +var MAX_PATTERN_LENGTH = 1024 * 64 +var assertValidPattern = function (pattern) { + if (typeof pattern !== 'string') { + throw new TypeError('invalid pattern') + } -traverse.propsKeywords = { - definitions: true, - properties: true, - patternProperties: true, - dependencies: true -}; + if (pattern.length > MAX_PATTERN_LENGTH) { + throw new TypeError('pattern is too long') + } +} -traverse.skipKeywords = { - default: true, - enum: true, - const: true, - required: true, - maximum: true, - minimum: true, - exclusiveMaximum: true, - exclusiveMinimum: true, - multipleOf: true, - maxLength: true, - minLength: true, - pattern: true, - format: true, - maxItems: true, - minItems: true, - uniqueItems: true, - maxProperties: true, - minProperties: true -}; +// 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 -function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { - if (schema && typeof schema == 'object' && !Array.isArray(schema)) { - pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); - for (var key in schema) { - var sch = schema[key]; - if (Array.isArray(sch)) { - if (key in traverse.arrayKeywords) { - for (var i=0; i 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 } + self.debug('clearStateChar %j %j', stateChar, re) + stateChar = false } - post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); } -} + 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) -function escapeJsonPtr(str) { - return str.replace(/~/g, '~0').replace(/\//g, '~1'); -} + // 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 -/***/ 21328: -/***/ (function(module) { + // 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) -/** - * JSONSchema Validator - Validates JavaScript objects using JSON Schemas - * (http://www.json.com/json-schema-proposal/) - * Licensed under AFL-2.1 OR BSD-3-Clause -To use the validator call the validate function with an instance object and an optional schema object. -If a schema is provided, it will be used to validate. If the instance object refers to a schema (self-validating), -that schema will be used to validate and the schema parameter is not necessary (if both exist, -both validations will occur). -The validate method will return an array of validation errors. If there are no errors, then an -empty list will be returned. A validation error will have two properties: -"property" which indicates which property had the error -"message" which indicates what the error was - */ -(function (root, factory) { - if (typeof define === 'function' && define.amd) { - // AMD. Register as an anonymous module. - define([], function () { - return factory(); - }); - } else if ( true && module.exports) { - // Node. Does not work with strict CommonJS, but - // only CommonJS-like environments that support module.exports, - // like Node. - module.exports = factory(); - } else { - // Browser globals - root.jsonSchema = factory(); - } -}(this, function () {// setup primitive classes to be JSON Schema types -var exports = validate -exports.Integer = {type:"integer"}; -var primitiveConstructors = { - String: String, - Boolean: Boolean, - Number: Number, - Object: Object, - Array: Array, - Date: Date -} -exports.validate = validate; -function validate(/*Any*/instance,/*Object*/schema) { - // Summary: - // To use the validator call JSONSchema.validate with an instance object and an optional schema object. - // If a schema is provided, it will be used to validate. If the instance object refers to a schema (self-validating), - // that schema will be used to validate and the schema parameter is not necessary (if both exist, - // both validations will occur). - // The validate method will return an object with two properties: - // valid: A boolean indicating if the instance is valid by the schema - // errors: An array of validation errors. If there are no errors, then an - // empty list will be returned. A validation error will have two properties: - // property: which indicates which property had the error - // message: which indicates what the error was - // - return validate(instance, schema, {changing: false});//, coerce: false, existingOnly: false}); - }; -exports.checkPropertyChange = function(/*Any*/value,/*Object*/schema, /*String*/property) { - // Summary: - // The checkPropertyChange method will check to see if an value can legally be in property with the given schema - // This is slightly different than the validate method in that it will fail if the schema is readonly and it will - // not check for self-validation, it is assumed that the passed in value is already internally valid. - // The checkPropertyChange method will return the same object type as validate, see JSONSchema.validate for - // information. - // - return validate(value, schema, {changing: property || "property"}); - }; -var validate = exports._validate = function(/*Any*/instance,/*Object*/schema,/*Object*/options) { + // 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 (!options) options = {}; - var _changing = options.changing; + // coalesce consecutive non-globstar * characters + if (c === '*' && stateChar === '*') continue - function getType(schema){ - return schema.type || (primitiveConstructors[schema.name] == schema && schema.name.toLowerCase()); - } - var errors = []; - // validate a value against a property definition - function checkProp(value, schema, path,i){ + // 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 - var l; - path += path ? typeof i == 'number' ? '[' + i + ']' : typeof i == 'undefined' ? '' : '.' + i : i; - function addError(message){ - errors.push({property:path,message:message}); - } + case '(': + if (inClass) { + re += '(' + continue + } - if((typeof schema != 'object' || schema instanceof Array) && (path || typeof schema != 'function') && !(schema && getType(schema))){ - if(typeof schema == 'function'){ - if(!(value instanceof schema)){ - addError("is not an instance of the class/constructor " + schema.name); - } - }else if(schema){ - addError("Invalid schema/property definition " + schema); - } - return null; - } - if(_changing && schema.readonly){ - addError("is a readonly field, it can not be changed"); - } - if(schema['extends']){ // if it extends another schema, it must pass that schema as well - checkProp(value,schema['extends'],path,i); - } - // validate a value against a type definition - function checkType(type,value){ - if(type){ - if(typeof type == 'string' && type != 'any' && - (type == 'null' ? value !== null : typeof value != type) && - !(value instanceof Array && type == 'array') && - !(value instanceof Date && type == 'date') && - !(type == 'integer' && value%1===0)){ - return [{property:path,message:value + " - " + (typeof value) + " value found, but a " + type + " is required"}]; - } - if(type instanceof Array){ - var unionErrors=[]; - for(var j = 0; j < type.length; j++){ // a union type - if(!(unionErrors=checkType(type[j],value)).length){ - break; - } - } - if(unionErrors.length){ - return unionErrors; - } - }else if(typeof type == 'object'){ - var priorErrors = errors; - errors = []; - checkProp(value,type,path); - var theseErrors = errors; - errors = priorErrors; - return theseErrors; - } - } - return []; - } - if(value === undefined){ - if(schema.required){ - addError("is missing and it is required"); - } - }else{ - errors = errors.concat(checkType(getType(schema),value)); - if(schema.disallow && !checkType(schema.disallow,value).length){ - addError(" disallowed value was matched"); - } - if(value !== null){ - if(value instanceof Array){ - if(schema.items){ - var itemsIsArray = schema.items instanceof Array; - var propDef = schema.items; - for (i = 0, l = value.length; i < l; i += 1) { - if (itemsIsArray) - propDef = schema.items[i]; - if (options.coerce) - value[i] = options.coerce(value[i], propDef); - errors.concat(checkProp(value[i],propDef,path,i)); - } - } - if(schema.minItems && value.length < schema.minItems){ - addError("There must be a minimum of " + schema.minItems + " in the array"); - } - if(schema.maxItems && value.length > schema.maxItems){ - addError("There must be a maximum of " + schema.maxItems + " in the array"); - } - }else if(schema.properties || schema.additionalProperties){ - errors.concat(checkObj(value, schema.properties, path, schema.additionalProperties)); - } - if(schema.pattern && typeof value == 'string' && !value.match(schema.pattern)){ - addError("does not match the regex pattern " + schema.pattern); - } - if(schema.maxLength && typeof value == 'string' && value.length > schema.maxLength){ - addError("may only be " + schema.maxLength + " characters long"); - } - if(schema.minLength && typeof value == 'string' && value.length < schema.minLength){ - addError("must be at least " + schema.minLength + " characters long"); - } - if(typeof schema.minimum !== 'undefined' && typeof value == typeof schema.minimum && - schema.minimum > value){ - addError("must have a minimum value of " + schema.minimum); - } - if(typeof schema.maximum !== 'undefined' && typeof value == typeof schema.maximum && - schema.maximum < value){ - addError("must have a maximum value of " + schema.maximum); - } - if(schema['enum']){ - var enumer = schema['enum']; - l = enumer.length; - var found; - for(var j = 0; j < l; j++){ - if(enumer[j]===value){ - found=1; - break; - } - } - if(!found){ - addError("does not have a value in the enumeration " + enumer.join(", ")); - } - } - if(typeof schema.maxDecimal == 'number' && - (value.toString().match(new RegExp("\\.[0-9]{" + (schema.maxDecimal + 1) + ",}")))){ - addError("may only have " + schema.maxDecimal + " digits of decimal places"); - } - } - } - return null; - } - // validate an object against a schema - function checkObj(instance,objTypeDef,path,additionalProp){ + if (!stateChar) { + re += '\\(' + continue + } - if(typeof objTypeDef =='object'){ - if(typeof instance != 'object' || instance instanceof Array){ - errors.push({property:path,message:"an object is required"}); - } - - for(var i in objTypeDef){ - if(objTypeDef.hasOwnProperty(i) && i != '__proto__' && i != 'constructor'){ - var value = instance.hasOwnProperty(i) ? instance[i] : undefined; - // skip _not_ specified properties - if (value === undefined && options.existingOnly) continue; - var propDef = objTypeDef[i]; - // set default - if(value === undefined && propDef["default"]){ - value = instance[i] = propDef["default"]; - } - if(options.coerce && i in instance){ - value = instance[i] = options.coerce(value, propDef); - } - checkProp(value,propDef,path,i); - } - } - } - for(i in instance){ - if(instance.hasOwnProperty(i) && !(i.charAt(0) == '_' && i.charAt(1) == '_') && objTypeDef && !objTypeDef[i] && additionalProp===false){ - if (options.filter) { - delete instance[i]; - continue; - } else { - errors.push({property:path,message:"The property " + i + - " is not defined in the schema and the schema does not allow additional properties"}); - } - } - var requires = objTypeDef && objTypeDef[i] && objTypeDef[i].requires; - if(requires && !(requires in instance)){ - errors.push({property:path,message:"the presence of the property " + i + " requires that " + requires + " also be present"}); - } - value = instance[i]; - if(additionalProp && (!(objTypeDef && typeof objTypeDef == 'object') || !(i in objTypeDef))){ - if(options.coerce){ - value = instance[i] = options.coerce(value, additionalProp); - } - checkProp(value,additionalProp,path,i); - } - if(!_changing && value && value.$schema){ - errors = errors.concat(checkProp(value,value.$schema,path,i)); - } - } - return errors; - } - if(schema){ - checkProp(instance,schema,'',_changing || ''); - } - if(!_changing && instance && instance.$schema){ - checkProp(instance,instance.$schema,'',''); - } - return {valid:!errors.length,errors:errors}; -}; -exports.mustBeValid = function(result){ - // summary: - // This checks to ensure that the result is valid and will throw an appropriate error message if it is not - // result: the result returned from checkPropertyChange or validate - if(!result.valid){ - throw new TypeError(result.errors.map(function(error){return "for property " + error.property + ': ' + error.message;}).join(", \n")); - } -} + 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 -return exports; -})); + case ')': + if (inClass || !patternListStack.length) { + re += '\\)' + continue + } + 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 -/***/ }), + case '|': + if (inClass || !patternListStack.length || escaping) { + re += '\\|' + escaping = false + continue + } -/***/ 57073: -/***/ ((module, exports) => { + clearStateChar() + re += '|' + continue -exports = module.exports = stringify -exports.getSerialize = serializer + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar() -function stringify(obj, replacer, spaces, cycleReplacer) { - return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces) -} + if (inClass) { + re += '\\' + c + continue + } -function serializer(replacer, cycleReplacer) { - var stack = [], keys = [] + inClass = true + classStart = i + reClassStart = re.length + re += c + continue - if (cycleReplacer == null) cycleReplacer = function(key, value) { - if (stack[0] === value) return "[Circular ~]" - return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]" - } + 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 + } - return function(key, value) { - if (stack.length > 0) { - var thisPos = stack.indexOf(this) - ~thisPos ? stack.splice(thisPos + 1) : stack.push(this) - ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key) - if (~stack.indexOf(value)) value = cycleReplacer.call(this, key, value) - } - else stack.push(value) + // 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 + } - return replacer == null ? value : replacer.call(this, key, value) - } -} + // 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 += '\\' + } -/***/ 63269: -/***/ (function(module, exports, __nccwpck_require__) { + re += c -(function (global, factory) { - true ? factory(exports) : - 0; -}(this, function (exports) { 'use strict'; + } // switch + } // for - function _typeof(obj) { - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof = function (obj) { - return typeof obj; - }; - } else { - _typeof = function (obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }; - } + // 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 _typeof(obj); + // 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 + + hasMagic = true + re = re.slice(0, pl.reStart) + t + '\\(' + tail } - function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += '\\\\' } - function _inherits(subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError("Super expression must either be null or a function"); + // 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) + + 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 - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - writable: true, - configurable: true - } - }); - if (superClass) _setPrototypeOf(subClass, superClass); + var dollar = '' + if (nlAfter === '' && isSub !== SUBPARSE) { + dollar = '$' + } + var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast + re = newRe } - function _getPrototypeOf(o) { - _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { - return o.__proto__ || Object.getPrototypeOf(o); - }; - return _getPrototypeOf(o); + // 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 } - function _setPrototypeOf(o, p) { - _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { - o.__proto__ = p; - return o; - }; + if (addPatternStart) { + re = patternStart + re + } - return _setPrototypeOf(o, p); + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] } - function isNativeReflectConstruct() { - if (typeof Reflect === "undefined" || !Reflect.construct) return false; - if (Reflect.construct.sham) return false; - if (typeof Proxy === "function") return true; + // 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) + } - try { - Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); - return true; - } catch (e) { - return false; - } + 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('$.') } - function _construct(Parent, args, Class) { - if (isNativeReflectConstruct()) { - _construct = Reflect.construct; - } else { - _construct = function _construct(Parent, args, Class) { - var a = [null]; - a.push.apply(a, args); - var Constructor = Function.bind.apply(Parent, a); - var instance = new Constructor(); - if (Class) _setPrototypeOf(instance, Class.prototype); - return instance; - }; - } + regExp._glob = pattern + regExp._src = re - return _construct.apply(null, arguments); - } + return regExp +} - function _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; - } +minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe() +} - function _wrapNativeSuper(Class) { - var _cache = typeof Map === "function" ? new Map() : undefined; +Minimatch.prototype.makeRe = makeRe +function makeRe () { + if (this.regexp || this.regexp === false) return this.regexp - _wrapNativeSuper = function _wrapNativeSuper(Class) { - if (Class === null || !_isNativeFunction(Class)) return Class; + // 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 (typeof Class !== "function") { - throw new TypeError("Super expression must either be null or a function"); - } + if (!set.length) { + this.regexp = false + return this.regexp + } + var options = this.options - if (typeof _cache !== "undefined") { - if (_cache.has(Class)) return _cache.get(Class); + var twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + var flags = options.nocase ? 'i' : '' - _cache.set(Class, Wrapper); - } + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return (p === GLOBSTAR) ? twoStar + : (typeof p === 'string') ? regExpEscape(p) + : p._src + }).join('\\\/') + }).join('|') - function Wrapper() { - return _construct(Class, arguments, _getPrototypeOf(this).constructor); - } + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$' - Wrapper.prototype = Object.create(Class.prototype, { - constructor: { - value: Wrapper, - enumerable: false, - writable: true, - configurable: true - } - }); - return _setPrototypeOf(Wrapper, Class); - }; + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$' - return _wrapNativeSuper(Class); + try { + this.regexp = new RegExp(re, flags) + } catch (ex) /* istanbul ignore next - should be impossible */ { + this.regexp = false } + return this.regexp +} - function _assertThisInitialized(self) { - if (self === void 0) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - } +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 +} + +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 === '' - return self; - } + if (f === '/' && partial) return true - function _possibleConstructorReturn(self, call) { - if (call && (typeof call === "object" || typeof call === "function")) { - return call; - } + var options = this.options - return _assertThisInitialized(self); + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/') } - /* eslint-disable no-eval */ - var globalEval = eval; // eslint-disable-next-line import/no-commonjs + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, 'split', f) - var supportsNodeVM = true && Boolean(module.exports) && !(typeof navigator !== 'undefined' && navigator.product === 'ReactNative'); - var allowedResultTypes = ['value', 'path', 'pointer', 'parent', 'parentProperty', 'all']; - var hasOwnProp = Object.prototype.hasOwnProperty; - /** - * Copy items out of one array into another. - * @param {Array} source Array with items to copy - * @param {Array} target Array to which to copy - * @param {Function} conditionCb Callback passed the current item; will move - * item if evaluates to `true` - * @returns {undefined} - */ + // 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 moveToAnotherArray = function moveToAnotherArray(source, target, conditionCb) { - var il = source.length; + var set = this.set + this.debug(this.pattern, 'set', set) - for (var i = 0; i < il; i++) { - var item = source[i]; + // 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 + } - if (conditionCb(item)) { - target.push(source.splice(i--, 1)[0]); - } + for (i = 0; i < set.length; i++) { + var pattern = set[i] + var file = f + if (options.matchBase && pattern.length === 1) { + file = [filename] } - }; - - var vm = supportsNodeVM ? __nccwpck_require__(26144) : { - /** - * @param {string} expr Expression to evaluate - * @param {Object} context Object whose items will be added to evaluation - * @returns {*} Result of evaluated code - */ - runInNewContext: function runInNewContext(expr, context) { - var keys = Object.keys(context); - var funcs = []; - moveToAnotherArray(keys, funcs, function (key) { - return typeof context[key] === 'function'; - }); - var code = funcs.reduce(function (s, func) { - var fString = context[func].toString(); - - if (!/function/.exec(fString)) { - fString = 'function ' + fString; - } - - return 'var ' + func + '=' + fString + ';' + s; - }, '') + keys.reduce(function (s, vr) { - return 'var ' + vr + '=' + JSON.stringify(context[vr]).replace( // http://www.thespanner.co.uk/2011/07/25/the-json-specification-is-now-wrong/ - /\u2028|\u2029/g, function (m) { - return "\\u202" + (m === "\u2028" ? '8' : '9'); - }) + ';' + s; - }, expr); - return globalEval(code); + var hit = this.matchOne(file, pattern, partial) + if (hit) { + if (options.flipNegate) return true + return !this.negate } - }; - /** - * Copies array and then pushes item into it. - * @param {Array} arr Array to copy and into which to push - * @param {*} item Array item to add (to end) - * @returns {Array} Copy of the original array - */ - - function push(arr, item) { - arr = arr.slice(); - arr.push(item); - return arr; } - /** - * Copies array and then unshifts item into it. - * @param {*} item Array item to add (to beginning) - * @param {Array} arr Array to copy and into which to unshift - * @returns {Array} Copy of the original array - */ + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate +} - function unshift(item, arr) { - arr = arr.slice(); - arr.unshift(item); - return arr; +// 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) { + if (pattern.indexOf(GLOBSTAR) !== -1) { + return this._matchGlobstar(file, pattern, partial, 0, 0) } - /** - * Caught when JSONPath is used without `new` but rethrown if with `new` - * @extends Error - */ + return this._matchOne(file, pattern, partial, 0, 0) +} +Minimatch.prototype._matchGlobstar = function (file, pattern, partial, fileIndex, patternIndex) { + var i - var NewError = - /*#__PURE__*/ - function (_Error) { - _inherits(NewError, _Error); + // find first globstar from patternIndex + var firstgs = -1 + for (i = patternIndex; i < pattern.length; i++) { + if (pattern[i] === GLOBSTAR) { firstgs = i; break } + } - /** - * @param {*} value The evaluated scalar value - */ - function NewError(value) { - var _this; + // find last globstar + var lastgs = -1 + for (i = pattern.length - 1; i >= 0; i--) { + if (pattern[i] === GLOBSTAR) { lastgs = i; break } + } - _classCallCheck(this, NewError); + var head = pattern.slice(patternIndex, firstgs) + var body = partial ? pattern.slice(firstgs + 1) : pattern.slice(firstgs + 1, lastgs) + var tail = partial ? [] : pattern.slice(lastgs + 1) - _this = _possibleConstructorReturn(this, _getPrototypeOf(NewError).call(this, 'JSONPath should not be called with "new" (it prevents return of (unwrapped) scalar values)')); - _this.avoidNew = true; - _this.value = value; - _this.name = 'NewError'; - return _this; + // check the head + if (head.length) { + var fileHead = file.slice(fileIndex, fileIndex + head.length) + if (!this._matchOne(fileHead, head, partial, 0, 0)) { + return false } + fileIndex += head.length + } - return NewError; - }(_wrapNativeSuper(Error)); - /** - * @param {Object} [opts] If present, must be an object - * @param {string} expr JSON path to evaluate - * @param {JSON} obj JSON object to evaluate against - * @param {Function} callback Passed 3 arguments: 1) desired payload per `resultType`, - * 2) `"value"|"property"`, 3) Full returned object with all payloads - * @param {Function} otherTypeCallback If `@other()` is at the end of one's query, this - * will be invoked with the value of the item, its path, its parent, and its parent's - * property name, and it should return a boolean indicating whether the supplied value - * belongs to the "other" type or not (or it may handle transformations and return `false`). - * @returns {JSONPath} - * @class - */ - - - function JSONPath(opts, expr, obj, callback, otherTypeCallback) { - // eslint-disable-next-line no-restricted-syntax - if (!(this instanceof JSONPath)) { - try { - return new JSONPath(opts, expr, obj, callback, otherTypeCallback); - } catch (e) { - if (!e.avoidNew) { - throw e; - } + // check the tail + var fileTailMatch = 0 + if (tail.length) { + if (tail.length + fileIndex > file.length) return false - return e.value; + var tailStart = file.length - tail.length + if (this._matchOne(file, tail, partial, tailStart, 0)) { + fileTailMatch = tail.length + } else { + // affordance for stuff like a/**/* matching a/b/ + if (file[file.length - 1] !== '' || + fileIndex + tail.length === file.length) { + return false + } + tailStart-- + if (!this._matchOne(file, tail, partial, tailStart, 0)) { + return false } + fileTailMatch = tail.length + 1 } + } - if (typeof opts === 'string') { - otherTypeCallback = callback; - callback = obj; - obj = expr; - expr = opts; - opts = {}; + // if body is empty (single ** between head and tail) + if (!body.length) { + var sawSome = !!fileTailMatch + for (i = fileIndex; i < file.length - fileTailMatch; i++) { + var f = String(file[i]) + sawSome = true + if (f === '.' || f === '..' || + (!this.options.dot && f.charAt(0) === '.')) { + return false + } } + return partial || sawSome + } - opts = opts || {}; - var objArgs = hasOwnProp.call(opts, 'json') && hasOwnProp.call(opts, 'path'); - this.json = opts.json || obj; - this.path = opts.path || expr; - this.resultType = opts.resultType && opts.resultType.toLowerCase() || 'value'; - this.flatten = opts.flatten || false; - this.wrap = hasOwnProp.call(opts, 'wrap') ? opts.wrap : true; - this.sandbox = opts.sandbox || {}; - this.preventEval = opts.preventEval || false; - this.parent = opts.parent || null; - this.parentProperty = opts.parentProperty || null; - this.callback = opts.callback || callback || null; + // split body into segments at each GLOBSTAR + var bodySegments = [[[], 0]] + var currentBody = bodySegments[0] + var nonGsParts = 0 + var nonGsPartsSums = [0] + for (var bi = 0; bi < body.length; bi++) { + var b = body[bi] + if (b === GLOBSTAR) { + nonGsPartsSums.push(nonGsParts) + currentBody = [[], 0] + bodySegments.push(currentBody) + } else { + currentBody[0].push(b) + nonGsParts++ + } + } - this.otherTypeCallback = opts.otherTypeCallback || otherTypeCallback || function () { - throw new Error('You must supply an otherTypeCallback callback option with the @other() operator.'); - }; + var idx = bodySegments.length - 1 + var fileLength = file.length - fileTailMatch + for (var si = 0; si < bodySegments.length; si++) { + bodySegments[si][1] = fileLength - + (nonGsPartsSums[idx--] + bodySegments[si][0].length) + } - if (opts.autostart !== false) { - var ret = this.evaluate({ - path: objArgs ? opts.path : expr, - json: objArgs ? opts.json : obj - }); + return !!this._matchGlobStarBodySections( + file, bodySegments, fileIndex, 0, partial, 0, !!fileTailMatch + ) +} - if (!ret || _typeof(ret) !== 'object') { - throw new NewError(ret); +// return false for "nope, not matching" +// return null for "not matching, cannot keep trying" +Minimatch.prototype._matchGlobStarBodySections = function ( + file, bodySegments, fileIndex, bodyIndex, partial, globStarDepth, sawTail +) { + var bs = bodySegments[bodyIndex] + if (!bs) { + // just make sure there are no bad dots + for (var i = fileIndex; i < file.length; i++) { + sawTail = true + var f = file[i] + if (f === '.' || f === '..' || + (!this.options.dot && f.charAt(0) === '.')) { + return false } + } + return sawTail + } - return ret; + var body = bs[0] + var after = bs[1] + while (fileIndex <= after) { + var m = this._matchOne( + file.slice(0, fileIndex + body.length), + body, + partial, + fileIndex, + 0 + ) + // if limit exceeded, no match. intentional false negative, + // acceptable break in correctness for security. + if (m && globStarDepth < this.maxGlobstarRecursion) { + var sub = this._matchGlobStarBodySections( + file, bodySegments, + fileIndex + body.length, bodyIndex + 1, + partial, globStarDepth + 1, sawTail + ) + if (sub !== false) { + return sub + } } - } // PUBLIC METHODS + var f = file[fileIndex] + if (f === '.' || f === '..' || + (!this.options.dot && f.charAt(0) === '.')) { + return false + } + fileIndex++ + } + return partial || null +} +Minimatch.prototype._matchOne = function (file, pattern, partial, fileIndex, patternIndex) { + var fi, pi, fl, pl + for ( + fi = fileIndex, pi = patternIndex, fl = file.length, pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++ + ) { + this.debug('matchOne loop') + var p = pattern[pi] + var f = file[fi] - JSONPath.prototype.evaluate = function (expr, json, callback, otherTypeCallback) { - var that = this; - var currParent = this.parent, - currParentProperty = this.parentProperty; - var flatten = this.flatten, - wrap = this.wrap; - this.currResultType = this.resultType; - this.currPreventEval = this.preventEval; - this.currSandbox = this.sandbox; - callback = callback || this.callback; - this.currOtherTypeCallback = otherTypeCallback || this.otherTypeCallback; - json = json || this.json; - expr = expr || this.path; + this.debug(pattern, p, f) - if (expr && _typeof(expr) === 'object') { - if (!expr.path) { - throw new Error('You must supply a "path" property when providing an object argument to JSONPath.evaluate().'); - } + // should be impossible. + // some invalid regexp stuff in the set. + /* istanbul ignore if */ + if (p === false || p === GLOBSTAR) return false - json = hasOwnProp.call(expr, 'json') ? expr.json : json; - flatten = hasOwnProp.call(expr, 'flatten') ? expr.flatten : flatten; - this.currResultType = hasOwnProp.call(expr, 'resultType') ? expr.resultType : this.currResultType; - this.currSandbox = hasOwnProp.call(expr, 'sandbox') ? expr.sandbox : this.currSandbox; - wrap = hasOwnProp.call(expr, 'wrap') ? expr.wrap : wrap; - this.currPreventEval = hasOwnProp.call(expr, 'preventEval') ? expr.preventEval : this.currPreventEval; - callback = hasOwnProp.call(expr, 'callback') ? expr.callback : callback; - this.currOtherTypeCallback = hasOwnProp.call(expr, 'otherTypeCallback') ? expr.otherTypeCallback : this.currOtherTypeCallback; - currParent = hasOwnProp.call(expr, 'parent') ? expr.parent : currParent; - currParentProperty = hasOwnProp.call(expr, 'parentProperty') ? expr.parentProperty : currParentProperty; - expr = expr.path; + // 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) } - currParent = currParent || null; - currParentProperty = currParentProperty || null; + if (!hit) return false + } - if (Array.isArray(expr)) { - expr = JSONPath.toPathString(expr); - } + // 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] === '') + } - if (!expr || !json || !allowedResultTypes.includes(this.currResultType)) { - return undefined; - } + // should be unreachable. + /* istanbul ignore next */ + throw new Error('wtf?') +} - this._obj = json; - var exprList = JSONPath.toPathArray(expr); +// replace stuff like \* with * +function globUnescape (s) { + return s.replace(/\\(.)/g, '$1') +} - if (exprList[0] === '$' && exprList.length > 1) { - exprList.shift(); - } +function regExpEscape (s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +} - this._hasParentSelector = null; - var result = this._trace(exprList, json, ['$'], currParent, currParentProperty, callback).filter(function (ea) { - return ea && !ea.isParentSelector; - }); +/***/ }), - if (!result.length) { - return wrap ? [] : undefined; - } +/***/ 41077: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (result.length === 1 && !wrap && !Array.isArray(result[0].value)) { - return this._getPreferredOutput(result[0]); - } +"use strict"; - return result.reduce(function (rslt, ea) { - var valOrPath = that._getPreferredOutput(ea); +const proc = typeof process === 'object' && process ? process : { + stdout: null, + stderr: null, +} +const EE = __nccwpck_require__(82361) +const Stream = __nccwpck_require__(12781) +const SD = (__nccwpck_require__(71576).StringDecoder) - if (flatten && Array.isArray(valOrPath)) { - rslt = rslt.concat(valOrPath); - } else { - rslt.push(valOrPath); - } +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') - return rslt; - }, []); - }; // PRIVATE METHODS +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') - JSONPath.prototype._getPreferredOutput = function (ea) { - var resultType = this.currResultType; +// 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' - switch (resultType) { - default: - throw new TypeError('Unknown result type'); +const isArrayBuffer = b => b instanceof ArrayBuffer || + typeof b === 'object' && + b.constructor && + b.constructor.name === 'ArrayBuffer' && + b.byteLength >= 0 - case 'all': - ea.pointer = JSONPath.toPointer(ea.path); - ea.path = typeof ea.path === 'string' ? ea.path : JSONPath.toPathString(ea.path); - return ea; +const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) - case 'value': - case 'parent': - case 'parentProperty': - return ea[resultType]; +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() + } +} - case 'path': - return JSONPath.toPathString(ea[resultType]); +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) + } +} - case 'pointer': - return JSONPath.toPointer(ea.path); - } - }; +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 + } - JSONPath.prototype._handleCallback = function (fullRetObj, callback, type) { - if (callback) { - var preferredOutput = this._getPreferredOutput(fullRetObj); + get bufferLength () { return this[BUFFERLENGTH] } - fullRetObj.path = typeof fullRetObj.path === 'string' ? fullRetObj.path : JSONPath.toPathString(fullRetObj.path); // eslint-disable-next-line callback-return + get encoding () { return this[ENCODING] } + set encoding (enc) { + if (this[OBJECTMODE]) + throw new Error('cannot set encoding in objectMode') - callback(preferredOutput, type, fullRetObj); + 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)) } - }; - JSONPath.prototype._trace = function (expr, val, path, parent, parentPropName, callback, literalPriority) { - // No expr to follow? return path and value as the result of this trace branch - var retObj; - var that = this; + this[ENCODING] = enc + } - if (!expr.length) { - retObj = { - path: path, - value: val, - parent: parent, - parentProperty: parentPropName - }; + setEncoding (enc) { + this.encoding = enc + } - this._handleCallback(retObj, callback, 'value'); + get objectMode () { return this[OBJECTMODE] } + set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om } - return retObj; + 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 } - var loc = expr[0], - x = expr.slice(1); // We need to gather the return value of recursive trace calls in order to - // do the parent sel computation. + if (typeof encoding === 'function') + cb = encoding, encoding = 'utf8' - var ret = []; + if (!encoding) + encoding = 'utf8' - function addRet(elems) { - if (Array.isArray(elems)) { - // This was causing excessive stack size in Node (with or without Babel) against our performance test: `ret.push(...elems);` - elems.forEach(function (t) { - ret.push(t); - }); - } else { - ret.push(elems); - } + 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 } - if ((typeof loc !== 'string' || literalPriority) && val && hasOwnProp.call(val, loc)) { - // simple case--directly follow property - addRet(this._trace(x, val[loc], push(path, loc), val, loc, callback)); - } else if (loc === '*') { - // all child properties - // eslint-disable-next-line no-shadow - this._walk(loc, x, val, path, parent, parentPropName, callback, function (m, l, x, v, p, par, pr, cb) { - addRet(that._trace(unshift(m, x), v, p, par, pr, cb, true)); - }); - } else if (loc === '..') { - // all descendent parent properties - addRet(this._trace(x, val, path, parent, parentPropName, callback)); // Check remaining expression with val's immediate children - // eslint-disable-next-line no-shadow + // 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._walk(loc, x, val, path, parent, parentPropName, callback, function (m, l, x, v, p, par, pr, cb) { - // We don't join m and x here because we only want parents, not scalar values - if (_typeof(v[m]) === 'object') { - // Keep going with recursive descent on val's object children - addRet(that._trace(unshift(l, x), v[m], push(p, m), v, m, cb)); - } - }); // The parent sel computation is handled in the frame above using the - // ancestor object of val + if (this.flowing) + this.emit('data', chunk) + else + this[BUFFERPUSH](chunk) - } else if (loc === '^') { - // This is not a final endpoint, so we do not invoke the callback here - this._hasParentSelector = true; - return path.length ? { - path: path.slice(0, -1), - expr: x, - isParentSelector: true - } : []; - } else if (loc === '~') { - // property name - retObj = { - path: push(path, loc), - value: parentPropName, - parent: parent, - parentProperty: null - }; + if (this[BUFFERLENGTH] !== 0) + this.emit('readable') - this._handleCallback(retObj, callback, 'property'); + if (cb) + fn(cb) - return retObj; - } else if (loc === '$') { - // root only - addRet(this._trace(x, val, path, null, null, callback)); - } else if (/^(-?\d*):(-?\d*):?(\d*)$/.test(loc)) { - // [start:end:step] Python slice syntax - addRet(this._slice(loc, x, val, path, parent, parentPropName, callback)); - } else if (loc.indexOf('?(') === 0) { - // [?(expr)] (filtering) - if (this.currPreventEval) { - throw new Error('Eval [?(expr)] prevented in JSONPath expression.'); - } // eslint-disable-next-line no-shadow + return this.flowing + } + // 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 + } - this._walk(loc, x, val, path, parent, parentPropName, callback, function (m, l, x, v, p, par, pr, cb) { - if (that._eval(l.replace(/^\?\((.*?)\)$/, '$1'), v[m], m, p, par, pr)) { - addRet(that._trace(unshift(m, x), v, p, par, pr, cb)); - } - }); - } else if (loc[0] === '(') { - // [(expr)] (dynamic property/index) - if (this.currPreventEval) { - throw new Error('Eval [(expr)] prevented in JSONPath expression.'); - } // As this will resolve to a property name (but we don't know it yet), property and parent information is relative to the parent of the property to which this expression will resolve + // 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) - addRet(this._trace(unshift(this._eval(loc, val, path[path.length - 1], path.slice(0, -1), parent, parentPropName), x), val, path, parent, parentPropName, callback)); - } else if (loc[0] === '@') { - // value type: @boolean(), etc. - var addType = false; - var valueType = loc.slice(1, -2); + // Note: flushing CAN potentially switch us into not-flowing mode + if (this.flowing && this[BUFFERLENGTH] !== 0) + this[FLUSH](true) - switch (valueType) { - default: - throw new TypeError('Unknown value type ' + valueType); + if (this.flowing) + this.emit('data', chunk) + else + this[BUFFERPUSH](chunk) - case 'scalar': - if (!val || !['object', 'function'].includes(_typeof(val))) { - addType = true; - } + if (this[BUFFERLENGTH] !== 0) + this.emit('readable') - break; + if (cb) + fn(cb) - case 'boolean': - case 'string': - case 'undefined': - case 'function': - if (_typeof(val) === valueType) { - // eslint-disable-line valid-typeof - addType = true; - } + return this.flowing + } - break; + read (n) { + if (this[DESTROYED]) + return null - case 'number': - if (_typeof(val) === valueType && isFinite(val)) { - // eslint-disable-line valid-typeof - addType = true; - } + if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) { + this[MAYBE_EMIT_END]() + return null + } - break; + if (this[OBJECTMODE]) + n = null - case 'nonFinite': - if (typeof val === 'number' && !isFinite(val)) { - addType = 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])] + } - break; + const ret = this[READ](n || null, this.buffer[0]) + this[MAYBE_EMIT_END]() + return ret + } - case 'object': - if (val && _typeof(val) === valueType) { - // eslint-disable-line valid-typeof - addType = 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 + } - break; + this.emit('data', chunk) - case 'array': - if (Array.isArray(val)) { - addType = true; - } + if (!this.buffer.length && !this[EOF]) + this.emit('drain') - break; + return chunk + } - case 'other': - addType = this.currOtherTypeCallback(val, path, parent, parentPropName); - break; + 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 - case 'integer': - if (val === Number(val) && isFinite(val) && !(val % 1)) { - addType = 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 + } - break; + // don't let the internal resume be overwritten + [RESUME] () { + if (this[DESTROYED]) + return - case 'null': - if (val === null) { - addType = true; - } + 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') + } - break; - } + resume () { + return this[RESUME]() + } - if (addType) { - retObj = { - path: path, - value: val, - parent: parent, - parentProperty: parentPropName - }; + pause () { + this[FLOWING] = false + this[PAUSED] = true + } - this._handleCallback(retObj, callback, 'value'); + get destroyed () { + return this[DESTROYED] + } - return retObj; - } - } else if (loc[0] === '`' && val && hasOwnProp.call(val, loc.slice(1))) { - // `-escaped property - var locProp = loc.slice(1); - addRet(this._trace(x, val[locProp], push(path, locProp), val, locProp, callback, true)); - } else if (loc.includes(',')) { - // [name1,name2,...] - var parts = loc.split(','); - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; + get flowing () { + return this[FLOWING] + } - try { - for (var _iterator = parts[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var part = _step.value; - addRet(this._trace(unshift(part, x), val, path, parent, parentPropName, callback)); - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator["return"] != null) { - _iterator["return"](); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - } else if (!literalPriority && val && hasOwnProp.call(val, loc)) { - // simple case--directly follow property - addRet(this._trace(x, val[loc], push(path, loc), val, loc, callback, true)); - } // We check the resulting values for parent selections. For parent - // selections we discard the value object and continue the trace with the - // current val object + get paused () { + return this[PAUSED] + } + [BUFFERPUSH] (chunk) { + if (this[OBJECTMODE]) + this[BUFFERLENGTH] += 1 + else + this[BUFFERLENGTH] += chunk.length + this.buffer.push(chunk) + } - if (this._hasParentSelector) { - // eslint-disable-next-line unicorn/no-for-loop - for (var t = 0; t < ret.length; t++) { - var rett = ret[t]; + [BUFFERSHIFT] () { + if (this.buffer.length) { + if (this[OBJECTMODE]) + this[BUFFERLENGTH] -= 1 + else + this[BUFFERLENGTH] -= this.buffer[0].length + } + return this.buffer.shift() + } - if (rett.isParentSelector) { - var tmp = that._trace(rett.expr, val, rett.path, parent, parentPropName, callback); + [FLUSH] (noDrain) { + do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]())) - if (Array.isArray(tmp)) { - ret[t] = tmp[0]; - var tl = tmp.length; + if (!noDrain && !this.buffer.length && !this[EOF]) + this.emit('drain') + } - for (var tt = 1; tt < tl; tt++) { - t++; - ret.splice(t, 0, tmp[tt]); - } - } else { - ret[t] = tmp; - } - } - } - } + [FLUSHCHUNK] (chunk) { + return chunk ? (this.emit('data', chunk), this.flowing) : false + } - return ret; - }; + pipe (dest, opts) { + if (this[DESTROYED]) + return - JSONPath.prototype._walk = function (loc, expr, val, path, parent, parentPropName, callback, f) { - if (Array.isArray(val)) { - var n = val.length; + 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 - for (var i = 0; i < n; i++) { - f(i, loc, expr, val, path, parent, parentPropName, callback); - } - } else if (_typeof(val) === 'object') { - for (var m in val) { - if (hasOwnProp.call(val, m)) { - f(m, loc, expr, val, path, parent, parentPropName, callback); - } - } + // 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]() } - }; - JSONPath.prototype._slice = function (loc, expr, val, path, parent, parentPropName, callback) { - if (!Array.isArray(val)) { - return undefined; - } + return dest + } - var len = val.length, - parts = loc.split(':'), - step = parts[2] && parseInt(parts[2]) || 1; - var start = parts[0] && parseInt(parts[0]) || 0, - end = parts[1] && parseInt(parts[1]) || len; - start = start < 0 ? Math.max(0, start + len) : Math.min(len, start); - end = end < 0 ? Math.max(0, end + len) : Math.min(len, end); - var ret = []; + unpipe (dest) { + const p = this.pipes.find(p => p.dest === dest) + if (p) { + this.pipes.splice(this.pipes.indexOf(p), 1) + p.unpipe() + } + } - for (var i = start; i < end; i += step) { - var tmp = this._trace(unshift(i, expr), val, path, parent, parentPropName, callback); + addListener (ev, fn) { + return this.on(ev, fn) + } - if (Array.isArray(tmp)) { - // This was causing excessive stack size in Node (with or without Babel) against our performance test: `ret.push(...tmp);` - tmp.forEach(function (t) { - ret.push(t); - }); - } else { - ret.push(tmp); - } + 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 + } - return ret; - }; + get emittedEnd () { + return this[EMITTED_END] + } - JSONPath.prototype._eval = function (code, _v, _vname, path, parent, parentPropName) { - if (!this._obj || !_v) { - return 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 + } + } + + 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 (code.includes('@parentProperty')) { - this.currSandbox._$_parentProperty = parentPropName; - code = code.replace(/@parentProperty/g, '_$_parentProperty'); - } + // Some other unknown event + const ret = super.emit(ev, data, ...extra) + this[MAYBE_EMIT_END]() + return ret + } - if (code.includes('@parent')) { - this.currSandbox._$_parent = parent; - code = code.replace(/@parent/g, '_$_parent'); + [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 (code.includes('@property')) { - this.currSandbox._$_property = _vname; - code = code.replace(/@property/g, '_$_property'); - } + [EMITEND] () { + if (this[EMITTED_END]) + return - if (code.includes('@path')) { - this.currSandbox._$_path = JSONPath.toPathString(path.concat([_vname])); - code = code.replace(/@path/g, '_$_path'); - } + this[EMITTED_END] = true + this.readable = false + if (this[ASYNC]) + defer(() => this[EMITEND2]()) + else + this[EMITEND2]() + } - if (code.match(/@([.\s)[])/)) { - this.currSandbox._$_v = _v; - code = code.replace(/@([.\s)[])/g, '_$_v$1'); + [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) + } } - try { - return vm.runInNewContext(code, this.currSandbox); - } catch (e) { - // eslint-disable-next-line no-console - console.log(e); - throw new Error('jsonPath: ' + e.message + ': ' + code); + for (const p of this.pipes) { + p.end() } - }; // PUBLIC CLASS PROPERTIES AND METHODS - // Could store the cache object itself - - - JSONPath.cache = {}; - /** - * @param {string[]} pathArr Array to convert - * @returns {string} The path string - */ + const ret = super.emit('end') + this.removeAllListeners('end') + return ret + } - JSONPath.toPathString = function (pathArr) { - var x = pathArr, - n = x.length; - var p = '$'; + // 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 i = 1; i < n; i++) { - if (!/^(~|\^|@.*?\(\))$/.test(x[i])) { - p += /^[0-9*]+$/.test(x[i]) ? '[' + x[i] + ']' : "['" + x[i] + "']"; - } - } + // 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)) + } - return p; - }; - /** - * @param {string} pointer JSON Path - * @returns {string} JSON Pointer - */ + // 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 }) - JSONPath.toPointer = function (pointer) { - var x = pointer, - n = x.length; - var p = ''; + if (this[EOF]) + return Promise.resolve({ done: true }) - for (var i = 1; i < n; i++) { - if (!/^(~|\^|@.*?\(\))$/.test(x[i])) { - p += '/' + x[i].toString().replace(/~/g, '~0').replace(/\//g, '~1'); + 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 p; - }; - /** - * @param {string} expr Expression to convert - * @returns {string[]} - */ - - - JSONPath.toPathArray = function (expr) { - var cache = JSONPath.cache; + return { next } + } - if (cache[expr]) { - return cache[expr].concat(); + // for (let chunk of stream) + [ITERATOR] () { + const next = () => { + const value = this.read() + const done = value === null + return { value, done } } + return { next } + } - var subx = []; - var normalized = expr // Properties - .replace(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\(\)/g, ';$&;') // Parenthetical evaluations (filtering and otherwise), directly - // within brackets or single quotes - .replace(/[['](\??\(.*?\))[\]']/g, function ($0, $1) { - return '[#' + (subx.push($1) - 1) + ']'; - }) // Escape periods and tildes within properties - .replace(/\['([^'\]]*)'\]/g, function ($0, prop) { - return "['" + prop.replace(/\./g, '%@%').replace(/~/g, '%%@@%%') + "']"; - }) // Properties operator - .replace(/~/g, ';~;') // Split by property boundaries - .replace(/'?\.'?(?![^[]*\])|\['?/g, ';') // Reinsert periods within properties - .replace(/%@%/g, '.') // Reinsert tildes within properties - .replace(/%%@@%%/g, '~') // Parent - .replace(/(?:;)?(\^+)(?:;)?/g, function ($0, ups) { - return ';' + ups.split('').join(';') + ';'; - }) // Descendents - .replace(/;;;|;;/g, ';..;') // Remove trailing - .replace(/;$|'?\]|'$/g, ''); - var exprList = normalized.split(';').map(function (exp) { - var match = exp.match(/#(\d+)/); - return !match || !match[1] ? exp : subx[match[1]]; - }); - cache[expr] = exprList; - return cache[expr]; - }; + destroy (er) { + if (this[DESTROYED]) { + if (er) + this.emit('error', er) + else + this.emit(DESTROYED) + return this + } - exports.JSONPath = JSONPath; + this[DESTROYED] = true - Object.defineProperty(exports, '__esModule', { value: true }); + // throw away all buffered data, it's never coming out + this.buffer.length = 0 + this[BUFFERLENGTH] = 0 -})); + if (typeof this.close === 'function' && !this[CLOSED]) + this.close() + if (er) + this.emit('error', er) + else // if no error to emit, still reject pending promises + this.emit(DESTROYED) -/***/ }), + return this + } -/***/ 6287: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + 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 + )) + } +} -/* - * lib/jsprim.js: utilities for primitive JavaScript types - */ -var mod_assert = __nccwpck_require__(66631); -var mod_util = __nccwpck_require__(73837); +/***/ }), -var mod_extsprintf = __nccwpck_require__(87264); -var mod_verror = __nccwpck_require__(81692); -var mod_jsonschema = __nccwpck_require__(21328); +/***/ 6769: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/* - * Public interface - */ -exports.deepCopy = deepCopy; -exports.deepEqual = deepEqual; -exports.isEmpty = isEmpty; -exports.hasKey = hasKey; -exports.forEachKey = forEachKey; -exports.pluck = pluck; -exports.flattenObject = flattenObject; -exports.flattenIter = flattenIter; -exports.validateJsonObject = validateJsonObjectJS; -exports.validateJsonObjectJS = validateJsonObjectJS; -exports.randElt = randElt; -exports.extraProperties = extraProperties; -exports.mergeObjects = mergeObjects; +// Update with any zlib constants that are added or changed in the future. +// Node v6 didn't export this, so we just hard code the version and rely +// on all the other hard-coded values from zlib v4736. When node v6 +// support drops, we can just export the realZlibConstants object. +const realZlibConstants = (__nccwpck_require__(59796).constants) || + /* istanbul ignore next */ { ZLIB_VERNUM: 4736 } -exports.startsWith = startsWith; -exports.endsWith = endsWith; +module.exports = Object.freeze(Object.assign(Object.create(null), { + Z_NO_FLUSH: 0, + Z_PARTIAL_FLUSH: 1, + Z_SYNC_FLUSH: 2, + Z_FULL_FLUSH: 3, + Z_FINISH: 4, + Z_BLOCK: 5, + Z_OK: 0, + Z_STREAM_END: 1, + Z_NEED_DICT: 2, + Z_ERRNO: -1, + Z_STREAM_ERROR: -2, + Z_DATA_ERROR: -3, + Z_MEM_ERROR: -4, + Z_BUF_ERROR: -5, + Z_VERSION_ERROR: -6, + Z_NO_COMPRESSION: 0, + Z_BEST_SPEED: 1, + Z_BEST_COMPRESSION: 9, + Z_DEFAULT_COMPRESSION: -1, + Z_FILTERED: 1, + Z_HUFFMAN_ONLY: 2, + Z_RLE: 3, + Z_FIXED: 4, + Z_DEFAULT_STRATEGY: 0, + DEFLATE: 1, + INFLATE: 2, + GZIP: 3, + GUNZIP: 4, + DEFLATERAW: 5, + INFLATERAW: 6, + UNZIP: 7, + BROTLI_DECODE: 8, + BROTLI_ENCODE: 9, + Z_MIN_WINDOWBITS: 8, + Z_MAX_WINDOWBITS: 15, + Z_DEFAULT_WINDOWBITS: 15, + Z_MIN_CHUNK: 64, + Z_MAX_CHUNK: Infinity, + Z_DEFAULT_CHUNK: 16384, + Z_MIN_MEMLEVEL: 1, + Z_MAX_MEMLEVEL: 9, + Z_DEFAULT_MEMLEVEL: 8, + Z_MIN_LEVEL: -1, + Z_MAX_LEVEL: 9, + Z_DEFAULT_LEVEL: -1, + BROTLI_OPERATION_PROCESS: 0, + BROTLI_OPERATION_FLUSH: 1, + BROTLI_OPERATION_FINISH: 2, + BROTLI_OPERATION_EMIT_METADATA: 3, + BROTLI_MODE_GENERIC: 0, + BROTLI_MODE_TEXT: 1, + BROTLI_MODE_FONT: 2, + BROTLI_DEFAULT_MODE: 0, + BROTLI_MIN_QUALITY: 0, + BROTLI_MAX_QUALITY: 11, + BROTLI_DEFAULT_QUALITY: 11, + BROTLI_MIN_WINDOW_BITS: 10, + BROTLI_MAX_WINDOW_BITS: 24, + BROTLI_LARGE_MAX_WINDOW_BITS: 30, + BROTLI_DEFAULT_WINDOW: 22, + BROTLI_MIN_INPUT_BLOCK_BITS: 16, + BROTLI_MAX_INPUT_BLOCK_BITS: 24, + BROTLI_PARAM_MODE: 0, + BROTLI_PARAM_QUALITY: 1, + BROTLI_PARAM_LGWIN: 2, + BROTLI_PARAM_LGBLOCK: 3, + BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4, + BROTLI_PARAM_SIZE_HINT: 5, + BROTLI_PARAM_LARGE_WINDOW: 6, + BROTLI_PARAM_NPOSTFIX: 7, + BROTLI_PARAM_NDIRECT: 8, + BROTLI_DECODER_RESULT_ERROR: 0, + BROTLI_DECODER_RESULT_SUCCESS: 1, + BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2, + BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3, + BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0, + BROTLI_DECODER_PARAM_LARGE_WINDOW: 1, + BROTLI_DECODER_NO_ERROR: 0, + BROTLI_DECODER_SUCCESS: 1, + BROTLI_DECODER_NEEDS_MORE_INPUT: 2, + BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3, + BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1, + BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2, + BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3, + BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4, + BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5, + BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6, + BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7, + BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8, + BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9, + BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10, + BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11, + BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12, + BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13, + BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14, + BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15, + BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16, + BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19, + BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20, + BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21, + BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22, + BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25, + BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26, + BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27, + BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30, + BROTLI_DECODER_ERROR_UNREACHABLE: -31, +}, realZlibConstants)) -exports.parseInteger = parseInteger; -exports.iso8601 = iso8601; -exports.rfc1123 = rfc1123; -exports.parseDateTime = parseDateTime; +/***/ }), -exports.hrtimediff = hrtimeDiff; -exports.hrtimeDiff = hrtimeDiff; -exports.hrtimeAccum = hrtimeAccum; -exports.hrtimeAdd = hrtimeAdd; -exports.hrtimeNanosec = hrtimeNanosec; -exports.hrtimeMicrosec = hrtimeMicrosec; -exports.hrtimeMillisec = hrtimeMillisec; +/***/ 33486: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; -/* - * Deep copy an acyclic *basic* Javascript object. This only handles basic - * scalars (strings, numbers, booleans) and arbitrarily deep arrays and objects - * containing these. This does *not* handle instances of other classes. - */ -function deepCopy(obj) -{ - var ret, key; - var marker = '__deepCopy'; - if (obj && obj[marker]) - throw (new Error('attempted deep copy of cyclic object')); +const assert = __nccwpck_require__(39491) +const Buffer = (__nccwpck_require__(14300).Buffer) +const realZlib = __nccwpck_require__(59796) - if (obj && obj.constructor == Object) { - ret = {}; - obj[marker] = true; +const constants = exports.constants = __nccwpck_require__(6769) +const Minipass = __nccwpck_require__(41077) - for (key in obj) { - if (key == marker) - continue; +const OriginalBufferConcat = Buffer.concat - ret[key] = deepCopy(obj[key]); - } +const _superWrite = Symbol('_superWrite') +class ZlibError extends Error { + constructor (err) { + super('zlib: ' + err.message) + this.code = err.code + this.errno = err.errno + /* istanbul ignore if */ + if (!this.code) + this.code = 'ZLIB_ERROR' - delete (obj[marker]); - return (ret); - } + this.message = 'zlib: ' + err.message + Error.captureStackTrace(this, this.constructor) + } - if (obj && obj.constructor == Array) { - ret = []; - obj[marker] = true; + get name () { + return 'ZlibError' + } +} - for (key = 0; key < obj.length; key++) - ret.push(deepCopy(obj[key])); +// the Zlib class they all inherit from +// This thing manages the queue of requests, and returns +// true or false if there is anything in the queue when +// you call the .write() method. +const _opts = Symbol('opts') +const _flushFlag = Symbol('flushFlag') +const _finishFlushFlag = Symbol('finishFlushFlag') +const _fullFlushFlag = Symbol('fullFlushFlag') +const _handle = Symbol('handle') +const _onError = Symbol('onError') +const _sawError = Symbol('sawError') +const _level = Symbol('level') +const _strategy = Symbol('strategy') +const _ended = Symbol('ended') +const _defaultFullFlush = Symbol('_defaultFullFlush') - delete (obj[marker]); - return (ret); - } +class ZlibBase extends Minipass { + constructor (opts, mode) { + if (!opts || typeof opts !== 'object') + throw new TypeError('invalid options for ZlibBase constructor') - /* - * It must be a primitive type -- just return it. - */ - return (obj); -} + super(opts) + this[_sawError] = false + this[_ended] = false + this[_opts] = opts -function deepEqual(obj1, obj2) -{ - if (typeof (obj1) != typeof (obj2)) - return (false); + this[_flushFlag] = opts.flush + this[_finishFlushFlag] = opts.finishFlush + // this will throw if any options are invalid for the class selected + try { + this[_handle] = new realZlib[mode](opts) + } catch (er) { + // make sure that all errors get decorated properly + throw new ZlibError(er) + } - if (obj1 === null || obj2 === null || typeof (obj1) != 'object') - return (obj1 === obj2); + this[_onError] = (err) => { + // no sense raising multiple errors, since we abort on the first one. + if (this[_sawError]) + return - if (obj1.constructor != obj2.constructor) - return (false); + this[_sawError] = true - var k; - for (k in obj1) { - if (!obj2.hasOwnProperty(k)) - return (false); + // there is no way to cleanly recover. + // continuing only obscures problems. + this.close() + this.emit('error', err) + } - if (!deepEqual(obj1[k], obj2[k])) - return (false); - } + this[_handle].on('error', er => this[_onError](new ZlibError(er))) + this.once('end', () => this.close) + } - for (k in obj2) { - if (!obj1.hasOwnProperty(k)) - return (false); - } + close () { + if (this[_handle]) { + this[_handle].close() + this[_handle] = null + this.emit('close') + } + } - return (true); -} + reset () { + if (!this[_sawError]) { + assert(this[_handle], 'zlib binding closed') + return this[_handle].reset() + } + } -function isEmpty(obj) -{ - var key; - for (key in obj) - return (false); - return (true); -} + flush (flushFlag) { + if (this.ended) + return -function hasKey(obj, key) -{ - mod_assert.equal(typeof (key), 'string'); - return (Object.prototype.hasOwnProperty.call(obj, key)); -} + if (typeof flushFlag !== 'number') + flushFlag = this[_fullFlushFlag] + this.write(Object.assign(Buffer.alloc(0), { [_flushFlag]: flushFlag })) + } -function forEachKey(obj, callback) -{ - for (var key in obj) { - if (hasKey(obj, key)) { - callback(key, obj[key]); - } - } -} + end (chunk, encoding, cb) { + if (chunk) + this.write(chunk, encoding) + this.flush(this[_finishFlushFlag]) + this[_ended] = true + return super.end(null, null, cb) + } -function pluck(obj, key) -{ - mod_assert.equal(typeof (key), 'string'); - return (pluckv(obj, key)); -} + get ended () { + return this[_ended] + } -function pluckv(obj, key) -{ - if (obj === null || typeof (obj) !== 'object') - return (undefined); + write (chunk, encoding, cb) { + // process the chunk using the sync process + // then super.write() all the outputted chunks + if (typeof encoding === 'function') + cb = encoding, encoding = 'utf8' - if (obj.hasOwnProperty(key)) - return (obj[key]); + if (typeof chunk === 'string') + chunk = Buffer.from(chunk, encoding) - var i = key.indexOf('.'); - if (i == -1) - return (undefined); + if (this[_sawError]) + return + assert(this[_handle], 'zlib binding closed') - var key1 = key.substr(0, i); - if (!obj.hasOwnProperty(key1)) - return (undefined); + // _processChunk tries to .close() the native handle after it's done, so we + // intercept that by temporarily making it a no-op. + const nativeHandle = this[_handle]._handle + const originalNativeClose = nativeHandle.close + nativeHandle.close = () => {} + const originalClose = this[_handle].close + this[_handle].close = () => {} + // It also calls `Buffer.concat()` at the end, which may be convenient + // for some, but which we are not interested in as it slows us down. + Buffer.concat = (args) => args + let result + try { + const flushFlag = typeof chunk[_flushFlag] === 'number' + ? chunk[_flushFlag] : this[_flushFlag] + result = this[_handle]._processChunk(chunk, flushFlag) + // if we don't throw, reset it back how it was + Buffer.concat = OriginalBufferConcat + } catch (err) { + // or if we do, put Buffer.concat() back before we emit error + // Error events call into user code, which may call Buffer.concat() + Buffer.concat = OriginalBufferConcat + this[_onError](new ZlibError(err)) + } finally { + if (this[_handle]) { + // Core zlib resets `_handle` to null after attempting to close the + // native handle. Our no-op handler prevented actual closure, but we + // need to restore the `._handle` property. + this[_handle]._handle = nativeHandle + nativeHandle.close = originalNativeClose + this[_handle].close = originalClose + // `_processChunk()` adds an 'error' listener. If we don't remove it + // after each call, these handlers start piling up. + this[_handle].removeAllListeners('error') + // make sure OUR error listener is still attached tho + } + } - return (pluckv(obj[key1], key.substr(i + 1))); -} + if (this[_handle]) + this[_handle].on('error', er => this[_onError](new ZlibError(er))) -/* - * Invoke callback(row) for each entry in the array that would be returned by - * flattenObject(data, depth). This is just like flattenObject(data, - * depth).forEach(callback), except that the intermediate array is never - * created. - */ -function flattenIter(data, depth, callback) -{ - doFlattenIter(data, depth, [], callback); -} + let writeReturn + if (result) { + if (Array.isArray(result) && result.length > 0) { + // The first buffer is always `handle._outBuffer`, which would be + // re-used for later invocations; so, we always have to copy that one. + writeReturn = this[_superWrite](Buffer.from(result[0])) + for (let i = 1; i < result.length; i++) { + writeReturn = this[_superWrite](result[i]) + } + } else { + writeReturn = this[_superWrite](Buffer.from(result)) + } + } -function doFlattenIter(data, depth, accum, callback) -{ - var each; - var key; + if (cb) + cb() + return writeReturn + } - if (depth === 0) { - each = accum.slice(0); - each.push(data); - callback(each); - return; - } + [_superWrite] (data) { + return super.write(data) + } +} - mod_assert.ok(data !== null); - mod_assert.equal(typeof (data), 'object'); - mod_assert.equal(typeof (depth), 'number'); - mod_assert.ok(depth >= 0); +class Zlib extends ZlibBase { + constructor (opts, mode) { + opts = opts || {} - for (key in data) { - each = accum.slice(0); - each.push(key); - doFlattenIter(data[key], depth - 1, each, callback); - } -} + opts.flush = opts.flush || constants.Z_NO_FLUSH + opts.finishFlush = opts.finishFlush || constants.Z_FINISH + super(opts, mode) -function flattenObject(data, depth) -{ - if (depth === 0) - return ([ data ]); + this[_fullFlushFlag] = constants.Z_FULL_FLUSH + this[_level] = opts.level + this[_strategy] = opts.strategy + } - mod_assert.ok(data !== null); - mod_assert.equal(typeof (data), 'object'); - mod_assert.equal(typeof (depth), 'number'); - mod_assert.ok(depth >= 0); + params (level, strategy) { + if (this[_sawError]) + return - var rv = []; - var key; + if (!this[_handle]) + throw new Error('cannot switch params when binding is closed') - for (key in data) { - flattenObject(data[key], depth - 1).forEach(function (p) { - rv.push([ key ].concat(p)); - }); - } + // no way to test this without also not supporting params at all + /* istanbul ignore if */ + if (!this[_handle].params) + throw new Error('not supported in this implementation') - return (rv); + if (this[_level] !== level || this[_strategy] !== strategy) { + this.flush(constants.Z_SYNC_FLUSH) + assert(this[_handle], 'zlib binding closed') + // .params() calls .flush(), but the latter is always async in the + // core zlib. We override .flush() temporarily to intercept that and + // flush synchronously. + const origFlush = this[_handle].flush + this[_handle].flush = (flushFlag, cb) => { + this.flush(flushFlag) + cb() + } + try { + this[_handle].params(level, strategy) + } finally { + this[_handle].flush = origFlush + } + /* istanbul ignore else */ + if (this[_handle]) { + this[_level] = level + this[_strategy] = strategy + } + } + } } -function startsWith(str, prefix) -{ - return (str.substr(0, prefix.length) == prefix); +// minimal 2-byte header +class Deflate extends Zlib { + constructor (opts) { + super(opts, 'Deflate') + } } -function endsWith(str, suffix) -{ - return (str.substr( - str.length - suffix.length, suffix.length) == suffix); +class Inflate extends Zlib { + constructor (opts) { + super(opts, 'Inflate') + } } -function iso8601(d) -{ - if (typeof (d) == 'number') - d = new Date(d); - mod_assert.ok(d.constructor === Date); - return (mod_extsprintf.sprintf('%4d-%02d-%02dT%02d:%02d:%02d.%03dZ', - d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate(), - d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), - d.getUTCMilliseconds())); -} +// gzip - bigger header, same deflate compression +const _portable = Symbol('_portable') +class Gzip extends Zlib { + constructor (opts) { + super(opts, 'Gzip') + this[_portable] = opts && !!opts.portable + } -var RFC1123_MONTHS = [ - 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', - 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; -var RFC1123_DAYS = [ - 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; + [_superWrite] (data) { + if (!this[_portable]) + return super[_superWrite](data) -function rfc1123(date) { - return (mod_extsprintf.sprintf('%s, %02d %s %04d %02d:%02d:%02d GMT', - RFC1123_DAYS[date.getUTCDay()], date.getUTCDate(), - RFC1123_MONTHS[date.getUTCMonth()], date.getUTCFullYear(), - date.getUTCHours(), date.getUTCMinutes(), - date.getUTCSeconds())); + // we'll always get the header emitted in one first chunk + // overwrite the OS indicator byte with 0xFF + this[_portable] = false + data[9] = 255 + return super[_superWrite](data) + } } -/* - * Parses a date expressed as a string, as either a number of milliseconds since - * the epoch or any string format that Date accepts, giving preference to the - * former where these two sets overlap (e.g., small numbers). - */ -function parseDateTime(str) -{ - /* - * This is irritatingly implicit, but significantly more concise than - * alternatives. The "+str" will convert a string containing only a - * number directly to a Number, or NaN for other strings. Thus, if the - * conversion succeeds, we use it (this is the milliseconds-since-epoch - * case). Otherwise, we pass the string directly to the Date - * constructor to parse. - */ - var numeric = +str; - if (!isNaN(numeric)) { - return (new Date(numeric)); - } else { - return (new Date(str)); - } +class Gunzip extends Zlib { + constructor (opts) { + super(opts, 'Gunzip') + } } +// raw - no header +class DeflateRaw extends Zlib { + constructor (opts) { + super(opts, 'DeflateRaw') + } +} -/* - * Number.*_SAFE_INTEGER isn't present before node v0.12, so we hardcode - * the ES6 definitions here, while allowing for them to someday be higher. - */ -var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; -var MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991; - - -/* - * Default options for parseInteger(). - */ -var PI_DEFAULTS = { - base: 10, - allowSign: true, - allowPrefix: false, - allowTrailing: false, - allowImprecise: false, - trimWhitespace: false, - leadingZeroIsOctal: false -}; - -var CP_0 = 0x30; -var CP_9 = 0x39; - -var CP_A = 0x41; -var CP_B = 0x42; -var CP_O = 0x4f; -var CP_T = 0x54; -var CP_X = 0x58; -var CP_Z = 0x5a; - -var CP_a = 0x61; -var CP_b = 0x62; -var CP_o = 0x6f; -var CP_t = 0x74; -var CP_x = 0x78; -var CP_z = 0x7a; - -var PI_CONV_DEC = 0x30; -var PI_CONV_UC = 0x37; -var PI_CONV_LC = 0x57; - - -/* - * A stricter version of parseInt() that provides options for changing what - * is an acceptable string (for example, disallowing trailing characters). - */ -function parseInteger(str, uopts) -{ - mod_assert.string(str, 'str'); - mod_assert.optionalObject(uopts, 'options'); - - var baseOverride = false; - var options = PI_DEFAULTS; - - if (uopts) { - baseOverride = hasKey(uopts, 'base'); - options = mergeObjects(options, uopts); - mod_assert.number(options.base, 'options.base'); - mod_assert.ok(options.base >= 2, 'options.base >= 2'); - mod_assert.ok(options.base <= 36, 'options.base <= 36'); - mod_assert.bool(options.allowSign, 'options.allowSign'); - mod_assert.bool(options.allowPrefix, 'options.allowPrefix'); - mod_assert.bool(options.allowTrailing, - 'options.allowTrailing'); - mod_assert.bool(options.allowImprecise, - 'options.allowImprecise'); - mod_assert.bool(options.trimWhitespace, - 'options.trimWhitespace'); - mod_assert.bool(options.leadingZeroIsOctal, - 'options.leadingZeroIsOctal'); - - if (options.leadingZeroIsOctal) { - mod_assert.ok(!baseOverride, - '"base" and "leadingZeroIsOctal" are ' + - 'mutually exclusive'); - } - } - - var c; - var pbase = -1; - var base = options.base; - var start; - var mult = 1; - var value = 0; - var idx = 0; - var len = str.length; - - /* Trim any whitespace on the left side. */ - if (options.trimWhitespace) { - while (idx < len && isSpace(str.charCodeAt(idx))) { - ++idx; - } - } +class InflateRaw extends Zlib { + constructor (opts) { + super(opts, 'InflateRaw') + } +} - /* Check the number for a leading sign. */ - if (options.allowSign) { - if (str[idx] === '-') { - idx += 1; - mult = -1; - } else if (str[idx] === '+') { - idx += 1; - } - } +// auto-detect header. +class Unzip extends Zlib { + constructor (opts) { + super(opts, 'Unzip') + } +} - /* Parse the base-indicating prefix if there is one. */ - if (str[idx] === '0') { - if (options.allowPrefix) { - pbase = prefixToBase(str.charCodeAt(idx + 1)); - if (pbase !== -1 && (!baseOverride || pbase === base)) { - base = pbase; - idx += 2; - } - } +class Brotli extends ZlibBase { + constructor (opts, mode) { + opts = opts || {} - if (pbase === -1 && options.leadingZeroIsOctal) { - base = 8; - } - } + opts.flush = opts.flush || constants.BROTLI_OPERATION_PROCESS + opts.finishFlush = opts.finishFlush || constants.BROTLI_OPERATION_FINISH - /* Parse the actual digits. */ - for (start = idx; idx < len; ++idx) { - c = translateDigit(str.charCodeAt(idx)); - if (c !== -1 && c < base) { - value *= base; - value += c; - } else { - break; - } - } + super(opts, mode) - /* If we didn't parse any digits, we have an invalid number. */ - if (start === idx) { - return (new Error('invalid number: ' + JSON.stringify(str))); - } + this[_fullFlushFlag] = constants.BROTLI_OPERATION_FLUSH + } +} - /* Trim any whitespace on the right side. */ - if (options.trimWhitespace) { - while (idx < len && isSpace(str.charCodeAt(idx))) { - ++idx; - } - } +class BrotliCompress extends Brotli { + constructor (opts) { + super(opts, 'BrotliCompress') + } +} - /* Check for trailing characters. */ - if (idx < len && !options.allowTrailing) { - return (new Error('trailing characters after number: ' + - JSON.stringify(str.slice(idx)))); - } +class BrotliDecompress extends Brotli { + constructor (opts) { + super(opts, 'BrotliDecompress') + } +} - /* If our value is 0, we return now, to avoid returning -0. */ - if (value === 0) { - return (0); - } +exports.Deflate = Deflate +exports.Inflate = Inflate +exports.Gzip = Gzip +exports.Gunzip = Gunzip +exports.DeflateRaw = DeflateRaw +exports.InflateRaw = InflateRaw +exports.Unzip = Unzip +/* istanbul ignore else */ +if (typeof realZlib.BrotliCompress === 'function') { + exports.BrotliCompress = BrotliCompress + exports.BrotliDecompress = BrotliDecompress +} else { + exports.BrotliCompress = exports.BrotliDecompress = class { + constructor () { + throw new Error('Brotli is not supported in this version of Node.js') + } + } +} - /* Calculate our final value. */ - var result = value * mult; - /* - * If the string represents a value that cannot be precisely represented - * by JavaScript, then we want to check that: - * - * - We never increased the value past MAX_SAFE_INTEGER - * - We don't make the result negative and below MIN_SAFE_INTEGER - * - * Because we only ever increment the value during parsing, there's no - * chance of moving past MAX_SAFE_INTEGER and then dropping below it - * again, losing precision in the process. This means that we only need - * to do our checks here, at the end. - */ - if (!options.allowImprecise && - (value > MAX_SAFE_INTEGER || result < MIN_SAFE_INTEGER)) { - return (new Error('number is outside of the supported range: ' + - JSON.stringify(str.slice(start, idx)))); - } +/***/ }), - return (result); -} +/***/ 66186: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const optsArg = __nccwpck_require__(42853) +const pathArg = __nccwpck_require__(12930) -/* - * Interpret a character code as a base-36 digit. - */ -function translateDigit(d) -{ - if (d >= CP_0 && d <= CP_9) { - /* '0' to '9' -> 0 to 9 */ - return (d - PI_CONV_DEC); - } else if (d >= CP_A && d <= CP_Z) { - /* 'A' - 'Z' -> 10 to 35 */ - return (d - PI_CONV_UC); - } else if (d >= CP_a && d <= CP_z) { - /* 'a' - 'z' -> 10 to 35 */ - return (d - PI_CONV_LC); - } else { - /* Invalid character code */ - return (-1); - } -} +const {mkdirpNative, mkdirpNativeSync} = __nccwpck_require__(4983) +const {mkdirpManual, mkdirpManualSync} = __nccwpck_require__(40356) +const {useNative, useNativeSync} = __nccwpck_require__(54518) -/* - * Test if a value matches the ECMAScript definition of trimmable whitespace. - */ -function isSpace(c) -{ - return (c === 0x20) || - (c >= 0x0009 && c <= 0x000d) || - (c === 0x00a0) || - (c === 0x1680) || - (c === 0x180e) || - (c >= 0x2000 && c <= 0x200a) || - (c === 0x2028) || - (c === 0x2029) || - (c === 0x202f) || - (c === 0x205f) || - (c === 0x3000) || - (c === 0xfeff); +const mkdirp = (path, opts) => { + path = pathArg(path) + opts = optsArg(opts) + return useNative(opts) + ? mkdirpNative(path, opts) + : mkdirpManual(path, opts) } - -/* - * Determine which base a character indicates (e.g., 'x' indicates hex). - */ -function prefixToBase(c) -{ - if (c === CP_b || c === CP_B) { - /* 0b/0B (binary) */ - return (2); - } else if (c === CP_o || c === CP_O) { - /* 0o/0O (octal) */ - return (8); - } else if (c === CP_t || c === CP_T) { - /* 0t/0T (decimal) */ - return (10); - } else if (c === CP_x || c === CP_X) { - /* 0x/0X (hexadecimal) */ - return (16); - } else { - /* Not a meaningful character */ - return (-1); - } +const mkdirpSync = (path, opts) => { + path = pathArg(path) + opts = optsArg(opts) + return useNativeSync(opts) + ? mkdirpNativeSync(path, opts) + : mkdirpManualSync(path, opts) } +mkdirp.sync = mkdirpSync +mkdirp.native = (path, opts) => mkdirpNative(pathArg(path), optsArg(opts)) +mkdirp.manual = (path, opts) => mkdirpManual(pathArg(path), optsArg(opts)) +mkdirp.nativeSync = (path, opts) => mkdirpNativeSync(pathArg(path), optsArg(opts)) +mkdirp.manualSync = (path, opts) => mkdirpManualSync(pathArg(path), optsArg(opts)) -function validateJsonObjectJS(schema, input) -{ - var report = mod_jsonschema.validate(input, schema); +module.exports = mkdirp - if (report.errors.length === 0) - return (null); - /* Currently, we only do anything useful with the first error. */ - var error = report.errors[0]; +/***/ }), - /* The failed property is given by a URI with an irrelevant prefix. */ - var propname = error['property']; - var reason = error['message'].toLowerCase(); - var i, j; +/***/ 44992: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /* - * There's at least one case where the property error message is - * confusing at best. We work around this here. - */ - if ((i = reason.indexOf('the property ')) != -1 && - (j = reason.indexOf(' is not defined in the schema and the ' + - 'schema does not allow additional properties')) != -1) { - i += 'the property '.length; - if (propname === '') - propname = reason.substr(i, j - i); - else - propname = propname + '.' + reason.substr(i, j - i); +const {dirname} = __nccwpck_require__(71017) - reason = 'unsupported property'; - } +const findMade = (opts, parent, path = undefined) => { + // we never want the 'made' return value to be a root directory + if (path === parent) + return Promise.resolve() - var rv = new mod_verror.VError('property "%s": %s', propname, reason); - rv.jsv_details = error; - return (rv); + return opts.statAsync(parent).then( + st => st.isDirectory() ? path : undefined, // will fail later + er => er.code === 'ENOENT' + ? findMade(opts, dirname(parent), parent) + : undefined + ) } -function randElt(arr) -{ - mod_assert.ok(Array.isArray(arr) && arr.length > 0, - 'randElt argument must be a non-empty array'); +const findMadeSync = (opts, parent, path = undefined) => { + if (path === parent) + return undefined - return (arr[Math.floor(Math.random() * arr.length)]); + try { + return opts.statSync(parent).isDirectory() ? path : undefined + } catch (er) { + return er.code === 'ENOENT' + ? findMadeSync(opts, dirname(parent), parent) + : undefined + } } -function assertHrtime(a) -{ - mod_assert.ok(a[0] >= 0 && a[1] >= 0, - 'negative numbers not allowed in hrtimes'); - mod_assert.ok(a[1] < 1e9, 'nanoseconds column overflow'); -} +module.exports = {findMade, findMadeSync} -/* - * Compute the time elapsed between hrtime readings A and B, where A is later - * than B. hrtime readings come from Node's process.hrtime(). There is no - * defined way to represent negative deltas, so it's illegal to diff B from A - * where the time denoted by B is later than the time denoted by A. If this - * becomes valuable, we can define a representation and extend the - * implementation to support it. - */ -function hrtimeDiff(a, b) -{ - assertHrtime(a); - assertHrtime(b); - mod_assert.ok(a[0] > b[0] || (a[0] == b[0] && a[1] >= b[1]), - 'negative differences not allowed'); - var rv = [ a[0] - b[0], 0 ]; +/***/ }), - if (a[1] >= b[1]) { - rv[1] = a[1] - b[1]; - } else { - rv[0]--; - rv[1] = 1e9 - (b[1] - a[1]); - } +/***/ 40356: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return (rv); -} +const {dirname} = __nccwpck_require__(71017) -/* - * Convert a hrtime reading from the array format returned by Node's - * process.hrtime() into a scalar number of nanoseconds. - */ -function hrtimeNanosec(a) -{ - assertHrtime(a); +const mkdirpManual = (path, opts, made) => { + opts.recursive = false + const parent = dirname(path) + if (parent === path) { + return opts.mkdirAsync(path, opts).catch(er => { + // swallowed by recursive implementation on posix systems + // any other error is a failure + if (er.code !== 'EISDIR') + throw er + }) + } - return (Math.floor(a[0] * 1e9 + a[1])); + return opts.mkdirAsync(path, opts).then(() => made || path, er => { + if (er.code === 'ENOENT') + return mkdirpManual(parent, opts) + .then(made => mkdirpManual(path, opts, made)) + if (er.code !== 'EEXIST' && er.code !== 'EROFS') + throw er + return opts.statAsync(path).then(st => { + if (st.isDirectory()) + return made + else + throw er + }, () => { throw er }) + }) } -/* - * Convert a hrtime reading from the array format returned by Node's - * process.hrtime() into a scalar number of microseconds. - */ -function hrtimeMicrosec(a) -{ - assertHrtime(a); - - return (Math.floor(a[0] * 1e6 + a[1] / 1e3)); -} +const mkdirpManualSync = (path, opts, made) => { + const parent = dirname(path) + opts.recursive = false -/* - * Convert a hrtime reading from the array format returned by Node's - * process.hrtime() into a scalar number of milliseconds. - */ -function hrtimeMillisec(a) -{ - assertHrtime(a); + if (parent === path) { + try { + return opts.mkdirSync(path, opts) + } catch (er) { + // swallowed by recursive implementation on posix systems + // any other error is a failure + if (er.code !== 'EISDIR') + throw er + else + return + } + } - return (Math.floor(a[0] * 1e3 + a[1] / 1e6)); + try { + opts.mkdirSync(path, opts) + return made || path + } catch (er) { + if (er.code === 'ENOENT') + return mkdirpManualSync(path, opts, mkdirpManualSync(parent, opts, made)) + if (er.code !== 'EEXIST' && er.code !== 'EROFS') + throw er + try { + if (!opts.statSync(path).isDirectory()) + throw er + } catch (_) { + throw er + } + } } -/* - * Add two hrtime readings A and B, overwriting A with the result of the - * addition. This function is useful for accumulating several hrtime intervals - * into a counter. Returns A. - */ -function hrtimeAccum(a, b) -{ - assertHrtime(a); - assertHrtime(b); +module.exports = {mkdirpManual, mkdirpManualSync} - /* - * Accumulate the nanosecond component. - */ - a[1] += b[1]; - if (a[1] >= 1e9) { - /* - * The nanosecond component overflowed, so carry to the seconds - * field. - */ - a[0]++; - a[1] -= 1e9; - } - /* - * Accumulate the seconds component. - */ - a[0] += b[0]; +/***/ }), - return (a); -} +/***/ 4983: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/* - * Add two hrtime readings A and B, returning the result as a new hrtime array. - * Does not modify either input argument. - */ -function hrtimeAdd(a, b) -{ - assertHrtime(a); +const {dirname} = __nccwpck_require__(71017) +const {findMade, findMadeSync} = __nccwpck_require__(44992) +const {mkdirpManual, mkdirpManualSync} = __nccwpck_require__(40356) - var rv = [ a[0], a[1] ]; +const mkdirpNative = (path, opts) => { + opts.recursive = true + const parent = dirname(path) + if (parent === path) + return opts.mkdirAsync(path, opts) - return (hrtimeAccum(rv, b)); + return findMade(opts, path).then(made => + opts.mkdirAsync(path, opts).then(() => made) + .catch(er => { + if (er.code === 'ENOENT') + return mkdirpManual(path, opts) + else + throw er + })) } +const mkdirpNativeSync = (path, opts) => { + opts.recursive = true + const parent = dirname(path) + if (parent === path) + return opts.mkdirSync(path, opts) -/* - * Check an object for unexpected properties. Accepts the object to check, and - * an array of allowed property names (strings). Returns an array of key names - * that were found on the object, but did not appear in the list of allowed - * properties. If no properties were found, the returned array will be of - * zero length. - */ -function extraProperties(obj, allowed) -{ - mod_assert.ok(typeof (obj) === 'object' && obj !== null, - 'obj argument must be a non-null object'); - mod_assert.ok(Array.isArray(allowed), - 'allowed argument must be an array of strings'); - for (var i = 0; i < allowed.length; i++) { - mod_assert.ok(typeof (allowed[i]) === 'string', - 'allowed argument must be an array of strings'); - } - - return (Object.keys(obj).filter(function (key) { - return (allowed.indexOf(key) === -1); - })); + const made = findMadeSync(opts, path) + try { + opts.mkdirSync(path, opts) + return made + } catch (er) { + if (er.code === 'ENOENT') + return mkdirpManualSync(path, opts) + else + throw er + } } -/* - * Given three sets of properties "provided" (may be undefined), "overrides" - * (required), and "defaults" (may be undefined), construct an object containing - * the union of these sets with "overrides" overriding "provided", and - * "provided" overriding "defaults". None of the input objects are modified. - */ -function mergeObjects(provided, overrides, defaults) -{ - var rv, k; +module.exports = {mkdirpNative, mkdirpNativeSync} - rv = {}; - if (defaults) { - for (k in defaults) - rv[k] = defaults[k]; - } - if (provided) { - for (k in provided) - rv[k] = provided[k]; - } +/***/ }), - if (overrides) { - for (k in overrides) - rv[k] = overrides[k]; - } +/***/ 42853: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return (rv); +const { promisify } = __nccwpck_require__(73837) +const fs = __nccwpck_require__(57147) +const optsArg = opts => { + if (!opts) + opts = { mode: 0o777, fs } + else if (typeof opts === 'object') + opts = { mode: 0o777, fs, ...opts } + else if (typeof opts === 'number') + opts = { mode: opts, fs } + else if (typeof opts === 'string') + opts = { mode: parseInt(opts, 8), fs } + else + throw new TypeError('invalid options argument') + + opts.mkdir = opts.mkdir || opts.fs.mkdir || fs.mkdir + opts.mkdirAsync = promisify(opts.mkdir) + opts.stat = opts.stat || opts.fs.stat || fs.stat + opts.statAsync = promisify(opts.stat) + opts.statSync = opts.statSync || opts.fs.statSync || fs.statSync + opts.mkdirSync = opts.mkdirSync || opts.fs.mkdirSync || fs.mkdirSync + return opts } +module.exports = optsArg /***/ }), -/***/ 9662: -/***/ ((module) => { - -"use strict"; +/***/ 12930: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports = object => { - const result = {}; +const platform = process.env.__TESTING_MKDIRP_PLATFORM__ || process.platform +const { resolve, parse } = __nccwpck_require__(71017) +const pathArg = path => { + if (/\0/.test(path)) { + // simulate same failure that node raises + throw Object.assign( + new TypeError('path must be a string without null bytes'), + { + path, + code: 'ERR_INVALID_ARG_VALUE', + } + ) + } - for (const [key, value] of Object.entries(object)) { - result[key.toLowerCase()] = value; - } + path = resolve(path) + if (platform === 'win32') { + const badWinChars = /[*|"<>?:]/ + const {root} = parse(path) + if (badWinChars.test(path.substr(root.length))) { + throw Object.assign(new Error('Illegal characters in path.'), { + path, + code: 'EINVAL', + }) + } + } - return result; -}; + return path +} +module.exports = pathArg /***/ }), -/***/ 7129: +/***/ 54518: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - +const fs = __nccwpck_require__(57147) -// A linked list to keep track of recently-used-ness -const Yallist = __nccwpck_require__(40665) +const version = process.env.__TESTING_MKDIRP_NODE_VERSION__ || process.version +const versArr = version.replace(/^v/, '').split('.') +const hasNative = +versArr[0] > 10 || +versArr[0] === 10 && +versArr[1] >= 12 -const MAX = Symbol('max') -const LENGTH = Symbol('length') -const LENGTH_CALCULATOR = Symbol('lengthCalculator') -const ALLOW_STALE = Symbol('allowStale') -const MAX_AGE = Symbol('maxAge') -const DISPOSE = Symbol('dispose') -const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') -const LRU_LIST = Symbol('lruList') -const CACHE = Symbol('cache') -const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') +const useNative = !hasNative ? () => false : opts => opts.mkdir === fs.mkdir +const useNativeSync = !hasNative ? () => false : opts => opts.mkdirSync === fs.mkdirSync -const naiveLength = () => 1 +module.exports = {useNative, useNativeSync} -// lruList is a yallist where the head is the youngest -// item, and the tail is the oldest. the list contains the Hit -// objects as the entries. -// Each Hit object has a reference to its Yallist.Node. This -// never changes. -// -// cache is a Map (or PseudoMap) that matches the keys to -// the Yallist.Node object. -class LRUCache { - constructor (options) { - if (typeof options === 'number') - options = { max: options } - if (!options) - options = {} +/***/ }), - if (options.max && (typeof options.max !== 'number' || options.max < 0)) - throw new TypeError('max must be a non-negative number') - // Kind of weird to have a default max of Infinity, but oh well. - const max = this[MAX] = options.max || Infinity +/***/ 80900: +/***/ ((module) => { - const lc = options.length || naiveLength - this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc - this[ALLOW_STALE] = options.stale || false - if (options.maxAge && typeof options.maxAge !== 'number') - throw new TypeError('maxAge must be a number') - this[MAX_AGE] = options.maxAge || 0 - this[DISPOSE] = options.dispose - this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false - this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false - this.reset() - } +/** + * Helpers. + */ - // resize the cache when the max changes. - set max (mL) { - if (typeof mL !== 'number' || mL < 0) - throw new TypeError('max must be a non-negative number') +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; - this[MAX] = mL || Infinity - trim(this) - } - get max () { - return this[MAX] - } +/** + * 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 + */ - set allowStale (allowStale) { - this[ALLOW_STALE] = !!allowStale - } - get allowStale () { - return this[ALLOW_STALE] +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) + ); +}; - set maxAge (mA) { - if (typeof mA !== 'number') - throw new TypeError('maxAge must be a non-negative number') +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ - this[MAX_AGE] = mA - trim(this) +function parse(str) { + str = String(str); + if (str.length > 100) { + return; } - get maxAge () { - return this[MAX_AGE] + 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; } - - // resize the cache when the lengthCalculator changes. - set lengthCalculator (lC) { - if (typeof lC !== 'function') - lC = naiveLength - - if (lC !== this[LENGTH_CALCULATOR]) { - this[LENGTH_CALCULATOR] = lC - this[LENGTH] = 0 - this[LRU_LIST].forEach(hit => { - hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) - this[LENGTH] += hit.length - }) - } - trim(this) + 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; } - get lengthCalculator () { return this[LENGTH_CALCULATOR] } +} - get length () { return this[LENGTH] } - get itemCount () { return this[LRU_LIST].length } +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - rforEach (fn, thisp) { - thisp = thisp || this - for (let walker = this[LRU_LIST].tail; walker !== null;) { - const prev = walker.prev - forEachStep(this, fn, walker, thisp) - walker = prev - } +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; } - - forEach (fn, thisp) { - thisp = thisp || this - for (let walker = this[LRU_LIST].head; walker !== null;) { - const next = walker.next - forEachStep(this, fn, walker, thisp) - walker = next - } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; } - - keys () { - return this[LRU_LIST].toArray().map(k => k.key) + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; } - - values () { - return this[LRU_LIST].toArray().map(k => k.value) + if (msAbs >= s) { + return Math.round(ms / s) + 's'; } + return ms + 'ms'; +} - reset () { - if (this[DISPOSE] && - this[LRU_LIST] && - this[LRU_LIST].length) { - this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) - } +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - this[CACHE] = new Map() // hash of items by key - this[LRU_LIST] = new Yallist() // list of items in order of use recency - this[LENGTH] = 0 // length of items in the list +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); } - - dump () { - return this[LRU_LIST].map(hit => - isStale(this, hit) ? false : { - k: hit.key, - v: hit.value, - e: hit.now + (hit.maxAge || 0) - }).toArray().filter(h => h) + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); } - - dumpLru () { - return this[LRU_LIST] + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); } + return ms + ' ms'; +} - set (key, value, maxAge) { - maxAge = maxAge || this[MAX_AGE] +/** + * Pluralization helper. + */ - if (maxAge && typeof maxAge !== 'number') - throw new TypeError('maxAge must be a number') +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} - const now = maxAge ? Date.now() : 0 - const len = this[LENGTH_CALCULATOR](value, key) - if (this[CACHE].has(key)) { - if (len > this[MAX]) { - del(this, this[CACHE].get(key)) - return false - } +/***/ }), - const node = this[CACHE].get(key) - const item = node.value +/***/ 80467: +/***/ ((module, exports, __nccwpck_require__) => { - // dispose of the old one before overwriting - // split out into 2 ifs for better coverage tracking - if (this[DISPOSE]) { - if (!this[NO_DISPOSE_ON_SET]) - this[DISPOSE](key, item.value) - } +"use strict"; - item.now = now - item.maxAge = maxAge - item.value = value - this[LENGTH] += len - item.length - item.length = len - this.get(key) - trim(this) - return true - } - const hit = new Entry(key, value, len, now, maxAge) +Object.defineProperty(exports, "__esModule", ({ value: true })); - // oversized objects fall out of cache automatically. - if (hit.length > this[MAX]) { - if (this[DISPOSE]) - this[DISPOSE](key, value) +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - return false - } +var Stream = _interopDefault(__nccwpck_require__(12781)); +var http = _interopDefault(__nccwpck_require__(13685)); +var Url = _interopDefault(__nccwpck_require__(57310)); +var whatwgUrl = _interopDefault(__nccwpck_require__(28665)); +var https = _interopDefault(__nccwpck_require__(95687)); +var zlib = _interopDefault(__nccwpck_require__(59796)); - this[LENGTH] += hit.length - this[LRU_LIST].unshift(hit) - this[CACHE].set(key, this[LRU_LIST].head) - trim(this) - return true - } +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js - has (key) { - if (!this[CACHE].has(key)) return false - const hit = this[CACHE].get(key).value - return !isStale(this, hit) - } +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; - get (key) { - return get(this, key, true) - } +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); - peek (key) { - return get(this, key, false) - } +class Blob { + constructor() { + this[TYPE] = ''; - pop () { - const node = this[LRU_LIST].tail - if (!node) - return null + const blobParts = arguments[0]; + const options = arguments[1]; - del(this, node) - return node.value - } + const buffers = []; + let size = 0; - del (key) { - del(this, this[CACHE].get(key)) - } + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } - load (arr) { - // reset the cache - this.reset() + this[BUFFER] = Buffer.concat(buffers); - const now = Date.now() - // A previous serialized cache has the most recent items first - for (let l = arr.length - 1; l >= 0; l--) { - const hit = arr[l] - const expiresAt = hit.e || 0 - if (expiresAt === 0) - // the item was created without expiration in a non aged cache - this.set(hit.k, hit.v) - else { - const maxAge = expiresAt - now - // dont add already expired items - if (maxAge > 0) { - this.set(hit.k, hit.v, maxAge) - } - } - } - } + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; - prune () { - this[CACHE].forEach((value, key) => get(this, key, false)) - } -} + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); -const get = (self, key, doUse) => { - const node = self[CACHE].get(key) - if (node) { - const hit = node.value - if (isStale(self, hit)) { - del(self, node) - if (!self[ALLOW_STALE]) - return undefined - } else { - if (doUse) { - if (self[UPDATE_AGE_ON_GET]) - node.value.now = Date.now() - self[LRU_LIST].unshiftNode(node) - } - } - return hit.value - } + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } } -const isStale = (self, hit) => { - if (!hit || (!hit.maxAge && !self[MAX_AGE])) - return false +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); - const diff = Date.now() - hit.now - return hit.maxAge ? diff > hit.maxAge - : self[MAX_AGE] && (diff > self[MAX_AGE]) -} +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); -const trim = self => { - if (self[LENGTH] > self[MAX]) { - for (let walker = self[LRU_LIST].tail; - self[LENGTH] > self[MAX] && walker !== null;) { - // We know that we're about to delete this one, and also - // what the next least recently used key will be, so just - // go ahead and set it now. - const prev = walker.prev - del(self, walker) - walker = prev - } - } -} +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ -const del = (self, node) => { - if (node) { - const hit = node.value - if (self[DISPOSE]) - self[DISPOSE](hit.key, hit.value) +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); - self[LENGTH] -= hit.length - self[CACHE].delete(hit.key) - self[LRU_LIST].removeNode(node) - } -} + this.message = message; + this.type = type; -class Entry { - constructor (key, value, length, now, maxAge) { - this.key = key - this.value = value - this.length = length - this.now = now - this.maxAge = maxAge || 0 + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; } -} -const forEachStep = (self, fn, node, thisp) => { - let hit = node.value - if (isStale(self, hit)) { - del(self, node) - if (!self[ALLOW_STALE]) - hit = undefined - } - if (hit) - fn.call(thisp, hit.value, hit.key, self) + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); } -module.exports = LRUCache +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = (__nccwpck_require__(22877).convert); +} catch (e) {} +const INTERNALS = Symbol('Body internals'); -/***/ }), +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; -/***/ 21381: -/***/ ((module, exports) => { +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; -"use strict"; -// ISC @ Julien Fontanet + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; -// =================================================================== + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} -var construct = typeof Reflect !== "undefined" ? Reflect.construct : undefined; -var defineProperty = Object.defineProperty; +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, -// ------------------------------------------------------------------- + get bodyUsed() { + return this[INTERNALS].disturbed; + }, -var captureStackTrace = Error.captureStackTrace; -if (captureStackTrace === undefined) { - captureStackTrace = function captureStackTrace(error) { - var container = new Error(); + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, - defineProperty(error, "stack", { - configurable: true, - get: function getStack() { - var stack = container.stack; + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, - // Replace property with value for faster future accesses. - defineProperty(this, "stack", { - configurable: true, - value: stack, - writable: true, - }); + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; - return stack; - }, - set: function setStack(stack) { - defineProperty(error, "stack", { - configurable: true, - value: stack, - writable: true, - }); - }, - }); - }; -} + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, -// ------------------------------------------------------------------- + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, -function BaseError(message) { - if (message !== undefined) { - defineProperty(this, "message", { - configurable: true, - value: message, - writable: true, - }); - } + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, - var cname = this.constructor.name; - if (cname !== undefined && cname !== this.name) { - defineProperty(this, "name", { - configurable: true, - value: cname, - writable: true, - }); - } + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; - captureStackTrace(this, this.constructor); -} + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; -BaseError.prototype = Object.create(Error.prototype, { - // See: https://github.com/JsCommunity/make-error/issues/4 - constructor: { - configurable: true, - value: BaseError, - writable: true, - }, +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } }); -// ------------------------------------------------------------------- +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; -// Sets the name of a function if possible (depends of the JS engine). -var setFunctionName = (function() { - function setFunctionName(fn, name) { - return defineProperty(fn, "name", { - configurable: true, - value: name, - }); - } - try { - var f = function() {}; - setFunctionName(f, "foo"); - if (f.name === "foo") { - return setFunctionName; - } - } catch (_) {} -})(); +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; -// ------------------------------------------------------------------- + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } -function makeError(constructor, super_) { - if (super_ == null || super_ === Error) { - super_ = BaseError; - } else if (typeof super_ !== "function") { - throw new TypeError("super_ should be a function"); - } + this[INTERNALS].disturbed = true; - var name; - if (typeof constructor === "string") { - name = constructor; - constructor = - construct !== undefined - ? function() { - return construct(super_, arguments, this.constructor); - } - : function() { - super_.apply(this, arguments); - }; + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } - // If the name can be set, do it once and for all. - if (setFunctionName !== undefined) { - setFunctionName(constructor, name); - name = undefined; - } - } else if (typeof constructor !== "function") { - throw new TypeError("constructor should be either a string or a function"); - } + let body = this.body; - // Also register the super constructor also as `constructor.super_` just - // like Node's `util.inherits()`. - // - // eslint-disable-next-line dot-notation - constructor.super_ = constructor["super"] = super_; + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } - var properties = { - constructor: { - configurable: true, - value: constructor, - writable: true, - }, - }; + // body is blob + if (isBlob(body)) { + body = body.stream(); + } - // If the name could not be set on the constructor, set it on the - // prototype. - if (name !== undefined) { - properties.name = { - configurable: true, - value: name, - writable: true, - }; - } - constructor.prototype = Object.create(super_.prototype, properties); + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } - return constructor; -} -exports = module.exports = makeError; -exports.BaseError = BaseError; + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; -/***/ }), + return new Body.Promise(function (resolve, reject) { + let resTimeout; -/***/ 19775: -/***/ ((module) => { + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } -"use strict"; + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } -/** @type {import('./abs')} */ -module.exports = Math.abs; + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + accumBytes += chunk.length; + accum.push(chunk); + }); -/***/ }), + body.on('end', function () { + if (abort) { + return; + } -/***/ 60924: -/***/ ((module) => { + clearTimeout(resTimeout); -"use strict"; + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } -/** @type {import('./floor')} */ -module.exports = Math.floor; + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } -/***/ }), + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); -/***/ 57661: -/***/ ((module) => { + // html5 + if (!res && str) { + res = / { + // turn raw buffers into a single utf-8 buffer + return convert(buffer, 'UTF-8', charset).toString(); +} -"use strict"; +/** + * Detect a URLSearchParams object + * ref: https://github.com/bitinn/node-fetch/issues/296#issuecomment-307598143 + * + * @param Object obj Object to detect by type or brand + * @return String + */ +function isURLSearchParams(obj) { + // Duck-typing as a necessary condition. + if (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') { + return false; + } + // Brand-checking and more duck-typing as optional condition. + return obj.constructor.name === 'URLSearchParams' || Object.prototype.toString.call(obj) === '[object URLSearchParams]' || typeof obj.sort === 'function'; +} -/** @type {import('./max')} */ -module.exports = Math.max; +/** + * Check if `obj` is a W3C `Blob` object (which `File` inherits from) + * @param {*} obj + * @return {boolean} + */ +function isBlob(obj) { + return 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]); +} +/** + * Clone body given Res/Req instance + * + * @param Mixed instance Response or Request instance + * @return Mixed + */ +function clone(instance) { + let p1, p2; + let body = instance.body; -/***/ }), + // don't allow cloning a used body + if (instance.bodyUsed) { + throw new Error('cannot clone body after it is used'); + } -/***/ 73373: -/***/ ((module) => { + // check that body is a stream and not form-data object + // note: we can't clone the form-data object without having it as a dependency + if (body instanceof Stream && typeof body.getBoundary !== 'function') { + // tee instance body + p1 = new PassThrough(); + p2 = new PassThrough(); + body.pipe(p1); + body.pipe(p2); + // set instance body to teed body and return the other teed body + instance[INTERNALS].body = p1; + body = p2; + } -"use strict"; + return body; +} +/** + * Performs the operation "extract a `Content-Type` value from |object|" as + * specified in the specification: + * https://fetch.spec.whatwg.org/#concept-bodyinit-extract + * + * This function assumes that instance.body is present. + * + * @param Mixed instance Any options.body input + */ +function extractContentType(body) { + if (body === null) { + // body is null + return null; + } else if (typeof body === 'string') { + // body is string + return 'text/plain;charset=UTF-8'; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + return 'application/x-www-form-urlencoded;charset=UTF-8'; + } else if (isBlob(body)) { + // body is blob + return body.type || null; + } else if (Buffer.isBuffer(body)) { + // body is buffer + return null; + } else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + return null; + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + return null; + } else if (typeof body.getBoundary === 'function') { + // detect form data input from form-data module + return `multipart/form-data;boundary=${body.getBoundary()}`; + } else if (body instanceof Stream) { + // body is stream + // can't really do much about this + return null; + } else { + // Body constructor defaults other things to string + return 'text/plain;charset=UTF-8'; + } +} -/** @type {import('./min')} */ -module.exports = Math.min; +/** + * The Fetch Standard treats this as if "total bytes" is a property on the body. + * For us, we have to explicitly get it with a function. + * + * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes + * + * @param Body instance Instance of Body + * @return Number? Number of bytes, or null if not possible + */ +function getTotalBytes(instance) { + const body = instance.body; -/***/ }), + if (body === null) { + // body is null + return 0; + } else if (isBlob(body)) { + return body.size; + } else if (Buffer.isBuffer(body)) { + // body is buffer + return body.length; + } else if (body && typeof body.getLengthSync === 'function') { + // detect form data input from form-data module + if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x + body.hasKnownLength && body.hasKnownLength()) { + // 2.x + return body.getLengthSync(); + } + return null; + } else { + // body is stream + return null; + } +} -/***/ 78029: -/***/ ((module) => { +/** + * Write a Body to a Node.js WritableStream (e.g. http.Request) object. + * + * @param Body instance Instance of Body + * @return Void + */ +function writeToStream(dest, instance) { + const body = instance.body; -"use strict"; + if (body === null) { + // body is null + dest.end(); + } else if (isBlob(body)) { + body.stream().pipe(dest); + } else if (Buffer.isBuffer(body)) { + // body is buffer + dest.write(body); + dest.end(); + } else { + // body is stream + body.pipe(dest); + } +} -/** @type {import('./pow')} */ -module.exports = Math.pow; +// expose Promise +Body.Promise = global.Promise; +/** + * headers.js + * + * Headers class offers convenient helpers + */ -/***/ }), +const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/; +const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/; -/***/ 59396: -/***/ ((module) => { +function validateName(name) { + name = `${name}`; + if (invalidTokenRegex.test(name) || name === '') { + throw new TypeError(`${name} is not a legal HTTP header name`); + } +} -"use strict"; +function validateValue(value) { + value = `${value}`; + if (invalidHeaderCharRegex.test(value)) { + throw new TypeError(`${value} is not a legal HTTP header value`); + } +} +/** + * Find the key in the map object given a header name. + * + * Returns undefined if not found. + * + * @param String name Header name + * @return String|Undefined + */ +function find(map, name) { + name = name.toLowerCase(); + for (const key in map) { + if (key.toLowerCase() === name) { + return key; + } + } + return undefined; +} -/** @type {import('./round')} */ -module.exports = Math.round; +const MAP = Symbol('map'); +class Headers { + /** + * Headers class + * + * @param Object headers Response headers + * @return Void + */ + constructor() { + let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined; + this[MAP] = Object.create(null); -/***/ }), + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); -/***/ 39091: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } -"use strict"; + return; + } + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } -var $isNaN = __nccwpck_require__(57661); + // 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'); + } + pairs.push(Array.from(pair)); + } -/** @type {import('./sign')} */ -module.exports = function sign(number) { - if ($isNaN(number) || number === 0) { - return number; + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } } - return number < 0 ? -1 : +1; -}; - - -/***/ }), -/***/ 2621: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + return this[MAP][key].join(', '); + } -const { PassThrough } = __nccwpck_require__(12781); + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; -module.exports = function (/*streams...*/) { - var sources = [] - var output = new PassThrough({objectMode: true}) + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; - output.setMaxListeners(0) + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } - output.add = add - output.isEmpty = isEmpty + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } - output.on('unpipe', remove) + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + 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]; + } + } - Array.prototype.slice.call(arguments).forEach(add) + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } - return output + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } - function add (source) { - if (Array.isArray(source)) { - source.forEach(add) - return this - } + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } - sources.push(source); - source.once('end', remove.bind(null, source)) - source.once('error', output.emit.bind(output, 'error')) - source.pipe(output, {end: false}) - return this - } + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } - function isEmpty () { - return sources.length == 0; - } + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } - function remove (source) { - sources = sources.filter(function (it) { return it !== source }) - if (!sources.length && output.readable) { output.end() } - } + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } } +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); -/***/ }), +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 } +}); -/***/ 47426: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; -/*! - * mime-db - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015-2022 Douglas Christopher Wilson - * MIT Licensed - */ + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} -/** - * Module exports. - */ +const INTERNAL = Symbol('internal'); -module.exports = __nccwpck_require__(53765) +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } -/***/ }), + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; -/***/ 43583: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } -"use strict"; -/*! - * mime-types - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ + this[INTERNAL].index = index + 1; + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); /** - * Module dependencies. - * @private + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); -var db = __nccwpck_require__(47426) -var extname = (__nccwpck_require__(71017).extname) - -/** - * Module variables. - * @private - */ + // 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]; + } -var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ -var TEXT_TYPE_REGEXP = /^text\//i + return obj; +} /** - * Module exports. - * @public + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + 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; +} -exports.charset = charset -exports.charsets = { lookup: charset } -exports.contentType = contentType -exports.extension = extension -exports.extensions = Object.create(null) -exports.lookup = lookup -exports.types = Object.create(null) +const INTERNALS$1 = Symbol('Response internals'); -// Populate the extensions/types maps -populateMaps(exports.extensions, exports.types) +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; /** - * Get the default charset for a MIME type. + * Response class * - * @param {string} type - * @return {boolean|string} + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; -function charset (type) { - if (!type || typeof type !== 'string') { - return false - } + Body.call(this, body, opts); - // TODO: use media-typer - var match = EXTRACT_TYPE_REGEXP.exec(type) - var mime = match && db[match[1].toLowerCase()] + const status = opts.status || 200; + const headers = new Headers(opts.headers); - if (mime && mime.charset) { - return mime.charset - } + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } - // default text/* to utf-8 - if (match && TEXT_TYPE_REGEXP.test(match[1])) { - return 'UTF-8' - } + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } - return false -} + get url() { + return this[INTERNALS$1].url || ''; + } -/** - * Create a full Content-Type header given a MIME type or extension. - * - * @param {string} str - * @return {boolean|string} - */ + get status() { + return this[INTERNALS$1].status; + } -function contentType (str) { - // TODO: should this even be in this module? - if (!str || typeof str !== 'string') { - return false - } + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } - var mime = str.indexOf('/') === -1 - ? exports.lookup(str) - : str + get redirected() { + return this[INTERNALS$1].counter > 0; + } - if (!mime) { - return false - } + get statusText() { + return this[INTERNALS$1].statusText; + } - // TODO: use content-type or other module - if (mime.indexOf('charset') === -1) { - var charset = exports.charset(mime) - if (charset) mime += '; charset=' + charset.toLowerCase() - } + get headers() { + return this[INTERNALS$1].headers; + } - return mime + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } } -/** - * Get the default extension for a MIME type. - * - * @param {string} type - * @return {boolean|string} - */ - -function extension (type) { - if (!type || typeof type !== 'string') { - return false - } +Body.mixIn(Response.prototype); - // TODO: use media-typer - var match = EXTRACT_TYPE_REGEXP.exec(type) +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 extensions - var exts = match && exports.extensions[match[1].toLowerCase()] +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); - if (!exts || !exts.length) { - return false - } +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; - return exts[0] -} +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; /** - * Lookup the MIME type for a file path/extension. + * Wrapper around `new URL` to handle arbitrary URLs * - * @param {string} path - * @return {boolean|string} + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } -function lookup (path) { - if (!path || typeof path !== 'string') { - return false - } + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} - // get the extension ("ext" or ".ext" or full path) - var extension = extname('x.' + path) - .toLowerCase() - .substr(1) +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; - if (!extension) { - return false - } +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} - return exports.types[extension] || false +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); } /** - * Populate the extensions and types maps. - * @private + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; -function populateMaps (extensions, types) { - // source preference (least -> most) - var preference = ['nginx', 'apache', undefined, 'iana'] + let parsedURL; - Object.keys(db).forEach(function forEachMimeType (type) { - var mime = db[type] - var exts = mime.extensions + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } - if (!exts || !exts.length) { - return - } + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); - // mime -> extensions - extensions[type] = exts + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } - // extension -> mime - for (var i = 0; i < exts.length; i++) { - var extension = exts[i] + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; - if (types[extension]) { - var from = preference.indexOf(db[types[extension]].source) - var to = preference.indexOf(mime.source) + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); - if (types[extension] !== 'application/octet-stream' && - (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { - // skip the remapping - continue - } - } + const headers = new Headers(init.headers || input.headers || {}); - // set the extension -> mime - types[extension] = type - } - }) -} + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; -/***/ }), + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } -/***/ 76047: -/***/ ((module) => { + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; -"use strict"; + // 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; + } + get method() { + return this[INTERNALS$2].method; + } -const mimicFn = (to, from) => { - for (const prop of Reflect.ownKeys(from)) { - Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop)); + get url() { + return format_url(this[INTERNALS$2].parsedURL); } - return to; -}; + get headers() { + return this[INTERNALS$2].headers; + } -module.exports = mimicFn; -// TODO: Remove this for the next major release -module.exports["default"] = mimicFn; + get redirect() { + return this[INTERNALS$2].redirect; + } + get signal() { + return this[INTERNALS$2].signal; + } -/***/ }), + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} -/***/ 42610: -/***/ ((module) => { +Body.mixIn(Request.prototype); -"use strict"; +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); -// We define these manually to ensure they're always copied -// even if they would move up the prototype chain -// https://nodejs.org/api/http.html#http_class_http_incomingmessage -const knownProps = [ - 'destroy', - 'setTimeout', - 'socket', - 'headers', - 'trailers', - 'rawHeaders', - 'statusCode', - 'httpVersion', - 'httpVersionMinor', - 'httpVersionMajor', - 'rawTrailers', - 'statusMessage' -]; +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); -module.exports = (fromStream, toStream) => { - const fromProps = new Set(Object.keys(fromStream).concat(knownProps)); + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } - for (const prop of fromProps) { - // Don't overwrite existing properties - if (prop in toStream) { - continue; - } + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } - toStream[prop] = typeof fromStream[prop] === 'function' ? fromStream[prop].bind(fromStream) : fromStream[prop]; + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); } -}; + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } -/***/ }), + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } -/***/ 83973: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } -module.exports = minimatch -minimatch.Minimatch = Minimatch + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } -var path = (function () { try { return __nccwpck_require__(71017) } catch (e) {}}()) || { - sep: '/' -} -minimatch.sep = path.sep + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } -var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} -var expand = __nccwpck_require__(33717) + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js -var plTypes = { - '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, - '?': { open: '(?:', close: ')?' }, - '+': { open: '(?:', close: ')+' }, - '*': { open: '(?:', close: ')*' }, - '@': { open: '(?:', close: ')' } + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); } -// any single thing other than / -// don't need to escape / when using new RegExp() -var qmark = '[^/]' - -// * => 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 = '(?:(?!(?:\\\/|^)\\.).)*?' - -// 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 - }, {}) -} +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ -// normalizes slashes. -var slashSplit = /\/+/ +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); -minimatch.filter = filter -function filter (pattern, options) { - options = options || {} - return function (p, i, list) { - return minimatch(p, pattern, options) - } -} + this.type = 'aborted'; + this.message = message; -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 + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); } -minimatch.defaults = function (def) { - if (!def || typeof def !== 'object' || !Object.keys(def).length) { - return minimatch - } +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; - var orig = minimatch +const URL$1 = Url.URL || whatwgUrl.URL; - var m = function minimatch (p, pattern, options) { - return orig(p, pattern, ext(def, options)) - } +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; - 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 - } +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; - m.filter = function filter (pattern, options) { - return orig.filter(pattern, ext(def, options)) - } + return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); +}; - m.defaults = function defaults (options) { - return orig.defaults(ext(def, options)) - } +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; - m.makeRe = function makeRe (pattern, options) { - return orig.makeRe(pattern, ext(def, options)) - } + return orig === dest; +}; - m.braceExpand = function braceExpand (pattern, options) { - return orig.braceExpand(pattern, ext(def, options)) - } +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { - m.match = function (list, pattern, options) { - return orig.match(list, pattern, ext(def, options)) - } + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } - return m -} + Body.Promise = fetch.Promise; -Minimatch.defaults = function (def) { - return minimatch.defaults(def).Minimatch -} + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); -function minimatch (p, pattern, options) { - assertValidPattern(pattern) + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; - if (!options) options = {} + let response = null; - // shortcut: comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - return false - } + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + destroyStream(request.body, error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; - return new Minimatch(pattern, options).match(p) -} + if (signal && signal.aborted) { + abort(); + return; + } -function Minimatch (pattern, options) { - if (!(this instanceof Minimatch)) { - return new Minimatch(pattern, options) - } + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; - assertValidPattern(pattern) + // send request + const req = send(options); + let reqTimeout; - if (!options) options = {} + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } - pattern = pattern.trim() + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } - // windows support: need to use /, not \ - if (!options.allowWindowsEscape && path.sep !== '/') { - pattern = pattern.split(path.sep).join('/') - } + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } - this.options = options - this.set = [] - this.pattern = pattern - this.regexp = null - this.negate = false - this.comment = false - this.empty = false - this.partial = !!options.partial + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); - // make the set of regexps etc. - this.make() -} + if (response && response.body) { + destroyStream(response.body, err); + } -Minimatch.prototype.debug = function () {} + finalize(); + }); -Minimatch.prototype.make = make -function make () { - var pattern = this.pattern - var options = this.options + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } - // empty patterns and comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - this.comment = true - return - } - if (!pattern) { - this.empty = true - return - } + if (response && response.body) { + destroyStream(response.body, err); + } + }); - // step 1: figure out negation, etc. - this.parseNegate() + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; - // step 2: expand braces - var set = this.globSet = this.braceExpand() + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } - if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) } + req.on('response', function (res) { + clearTimeout(reqTimeout); - this.debug(this.pattern, set) + const headers = createHeadersLenient(res.headers); - // 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) - }) + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); - this.debug(this.pattern, set) + // HTTP fetch step 5.3 + let locationURL = null; + try { + locationURL = location === null ? null : new URL$1(location, request.url).toString(); + } catch (err) { + // 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') { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); + finalize(); + return; + } + } - // glob --> regexps - set = set.map(function (s, si, set) { - return s.map(this.parse, this) - }, this) + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case '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); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } - this.debug(this.pattern, set) + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } - // filter out everything that didn't compile properly. - set = set.filter(function (s) { - return s.indexOf(false) === -1 - }) + // 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, + size: request.size + }; - this.debug(this.pattern, set) + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } - this.set = set -} + // 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; + } -Minimatch.prototype.parseNegate = parseNegate -function parseNegate () { - var pattern = this.pattern - var negate = false - var options = this.options - var negateOffset = 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'); + } - if (options.nonegate) return + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } - for (var i = 0, l = pattern.length - ; i < l && pattern.charAt(i) === '!' - ; i++) { - negate = !negate - negateOffset++ - } + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); - if (negateOffset) this.pattern = pattern.substr(negateOffset) - this.negate = negate -} + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; -// 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) -} + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); -Minimatch.prototype.braceExpand = braceExpand + // HTTP-network fetch step 12.1.1.4: handle content codings -function braceExpand (pattern, options) { - if (!options) { - if (this instanceof Minimatch) { - options = this.options - } else { - options = {} - } - } + // 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, response_options); + resolve(response); + return; + } - pattern = typeof pattern === 'undefined' - ? this.pattern : pattern + // For Node v6+ + // 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.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; - assertValidPattern(pattern) + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } - // 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] - } + // 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 PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); + return; + } - return expand(pattern) -} + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } -var MAX_PATTERN_LENGTH = 1024 * 64 -var assertValidPattern = function (pattern) { - if (typeof pattern !== 'string') { - throw new TypeError('invalid pattern') - } + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); - if (pattern.length > MAX_PATTERN_LENGTH) { - throw new TypeError('pattern is too long') - } + writeToStream(req, request); + }); } +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; -// 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 '' - - 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 - } - self.debug('clearStateChar %j %j', stateChar, re) - stateChar = false - } - } - - 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 - } - - switch (c) { - /* istanbul ignore next */ - case '/': { - // completely not allowed, even escaped. - // Should already be path-split by now. - return false - } + request.on('socket', function (s) { + socket = s; + }); - case '\\': - clearStateChar() - escaping = true - continue + request.on('response', function (response) { + const headers = response.headers; - // 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) + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; - // 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 (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} - // 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 +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} - case '(': - if (inClass) { - re += '(' - continue - } +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; - if (!stateChar) { - re += '\\(' - continue - } +// expose Promise +fetch.Promise = global.Promise; - 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 +module.exports = exports = fetch; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports["default"] = exports; +exports.Headers = Headers; +exports.Request = Request; +exports.Response = Response; +exports.FetchError = FetchError; +exports.AbortError = AbortError; - case ')': - if (inClass || !patternListStack.length) { - re += '\\)' - continue - } - 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 +/***/ }), - case '|': - if (inClass || !patternListStack.length || escaping) { - re += '\\|' - escaping = false - continue - } +/***/ 17952: +/***/ ((module) => { - clearStateChar() - re += '|' - continue +"use strict"; - // these are mostly the same in regexp and glob - case '[': - // swallow any state-tracking char before the [ - clearStateChar() - if (inClass) { - re += '\\' + c - continue - } +// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs +const DATA_URL_DEFAULT_MIME_TYPE = 'text/plain'; +const DATA_URL_DEFAULT_CHARSET = 'us-ascii'; - inClass = true - classStart = i - reClassStart = re.length - re += c - continue +const testParameter = (name, filters) => { + return filters.some(filter => filter instanceof RegExp ? filter.test(name) : filter === name); +}; - 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 - } +const normalizeDataURL = (urlString, {stripHash}) => { + const match = /^data:(?[^,]*?),(?[^#]*?)(?:#(?.*))?$/.exec(urlString); - // 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 - } + if (!match) { + throw new Error(`Invalid URL: ${urlString}`); + } - // finish up the class. - hasMagic = true - inClass = false - re += c - continue + let {type, data, hash} = match.groups; + const mediaType = type.split(';'); + hash = stripHash ? '' : hash; - default: - // swallow any state char that wasn't consumed - clearStateChar() + let isBase64 = false; + if (mediaType[mediaType.length - 1] === 'base64') { + mediaType.pop(); + isBase64 = true; + } - if (escaping) { - // no need - escaping = false - } else if (reSpecials[c] - && !(c === '^' && inClass)) { - re += '\\' - } + // Lowercase MIME type + const mimeType = (mediaType.shift() || '').toLowerCase(); + const attributes = mediaType + .map(attribute => { + let [key, value = ''] = attribute.split('=').map(string => string.trim()); - re += c + // Lowercase `charset` + if (key === 'charset') { + value = value.toLowerCase(); - } // switch - } // for + if (value === DATA_URL_DEFAULT_CHARSET) { + return ''; + } + } - // 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 `${key}${value ? `=${value}` : ''}`; + }) + .filter(Boolean); - // 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 = '\\' - } + const normalizedMediaType = [ + ...attributes + ]; - // 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 (isBase64) { + normalizedMediaType.push('base64'); + } - this.debug('tail=%j\n %s', tail, tail, pl, re) - var t = pl.type === '*' ? star - : pl.type === '?' ? qmark - : '\\' + pl.type + if (normalizedMediaType.length !== 0 || (mimeType && mimeType !== DATA_URL_DEFAULT_MIME_TYPE)) { + normalizedMediaType.unshift(mimeType); + } - hasMagic = true - re = re.slice(0, pl.reStart) + t + '\\(' + tail - } + return `data:${normalizedMediaType.join(';')},${isBase64 ? data.trim() : data}${hash ? `#${hash}` : ''}`; +}; - // handle trailing things that only matter at the very end. - clearStateChar() - if (escaping) { - // trailing \\ - re += '\\\\' - } +const normalizeUrl = (urlString, options) => { + options = { + defaultProtocol: 'http:', + normalizeProtocol: true, + forceHttp: false, + forceHttps: false, + stripAuthentication: true, + stripHash: false, + stripTextFragment: true, + stripWWW: true, + removeQueryParameters: [/^utm_\w+/i], + removeTrailingSlash: true, + removeSingleSlash: true, + removeDirectoryIndex: false, + sortQueryParameters: true, + ...options + }; - // 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 - } + urlString = urlString.trim(); - // 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] + // Data URL + if (/^data:/i.test(urlString)) { + return normalizeDataURL(urlString, options); + } - 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 (/^view-source:/i.test(urlString)) { + throw new Error('`view-source:` is not supported as it is a non-standard protocol'); + } - nlLast += nlAfter + const hasRelativeProtocol = urlString.startsWith('//'); + const isRelativeUrl = !hasRelativeProtocol && /^\.*\//.test(urlString); - // 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 + // Prepend protocol + if (!isRelativeUrl) { + urlString = urlString.replace(/^(?!(?:\w+:)?\/\/)|^\/\//, options.defaultProtocol); + } - var dollar = '' - if (nlAfter === '' && isSub !== SUBPARSE) { - dollar = '$' - } - var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast - re = newRe - } + const urlObj = new URL(urlString); - // 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 (options.forceHttp && options.forceHttps) { + throw new Error('The `forceHttp` and `forceHttps` options cannot be used together'); + } - if (addPatternStart) { - re = patternStart + re - } + if (options.forceHttp && urlObj.protocol === 'https:') { + urlObj.protocol = 'http:'; + } - // parsing just a piece of a larger pattern. - if (isSub === SUBPARSE) { - return [re, hasMagic] - } + if (options.forceHttps && urlObj.protocol === 'http:') { + urlObj.protocol = 'https:'; + } - // 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) - } + // Remove auth + if (options.stripAuthentication) { + urlObj.username = ''; + urlObj.password = ''; + } - 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('$.') - } + // Remove hash + if (options.stripHash) { + urlObj.hash = ''; + } else if (options.stripTextFragment) { + urlObj.hash = urlObj.hash.replace(/#?:~:text.*?$/i, ''); + } - regExp._glob = pattern - regExp._src = re + // Remove duplicate slashes if not preceded by a protocol + if (urlObj.pathname) { + urlObj.pathname = urlObj.pathname.replace(/(? 0) { + let pathComponents = urlObj.pathname.split('/'); + const lastComponent = pathComponents[pathComponents.length - 1]; - // 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 (testParameter(lastComponent, options.removeDirectoryIndex)) { + pathComponents = pathComponents.slice(0, pathComponents.length - 1); + urlObj.pathname = pathComponents.slice(1).join('/') + '/'; + } + } - if (!set.length) { - this.regexp = false - return this.regexp - } - var options = this.options + if (urlObj.hostname) { + // Remove trailing dot + urlObj.hostname = urlObj.hostname.replace(/\.$/, ''); - var twoStar = options.noglobstar ? star - : options.dot ? twoStarDot - : twoStarNoDot - var flags = options.nocase ? 'i' : '' + // Remove `www.` + if (options.stripWWW && /^www\.(?!www\.)(?:[a-z\-\d]{1,63})\.(?:[a-z.\-\d]{2,63})$/.test(urlObj.hostname)) { + // Each label should be max 63 at length (min: 1). + // Source: https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names + // Each TLD should be up to 63 characters long (min: 2). + // It is technically possible to have a single character TLD, but none currently exist. + urlObj.hostname = urlObj.hostname.replace(/^www\./, ''); + } + } - var re = set.map(function (pattern) { - return pattern.map(function (p) { - return (p === GLOBSTAR) ? twoStar - : (typeof p === 'string') ? regExpEscape(p) - : p._src - }).join('\\\/') - }).join('|') + // Remove query unwanted parameters + if (Array.isArray(options.removeQueryParameters)) { + for (const key of [...urlObj.searchParams.keys()]) { + if (testParameter(key, options.removeQueryParameters)) { + urlObj.searchParams.delete(key); + } + } + } - // must match entire pattern - // ending in a * or ** will make it less strict. - re = '^(?:' + re + ')$' + if (options.removeQueryParameters === true) { + urlObj.search = ''; + } - // can match anything, as long as it's not this. - if (this.negate) re = '^(?!' + re + ').*$' + // Sort query parameters + if (options.sortQueryParameters) { + urlObj.searchParams.sort(); + } - try { - this.regexp = new RegExp(re, flags) - } catch (ex) /* istanbul ignore next - should be impossible */ { - this.regexp = false - } - return this.regexp -} + if (options.removeTrailingSlash) { + urlObj.pathname = urlObj.pathname.replace(/\/$/, ''); + } -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 -} + const oldUrlString = urlString; -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 === '' + // Take advantage of many of the Node `url` normalizations + urlString = urlObj.toString(); - if (f === '/' && partial) return true + if (!options.removeSingleSlash && urlObj.pathname === '/' && !oldUrlString.endsWith('/') && urlObj.hash === '') { + urlString = urlString.replace(/\/$/, ''); + } - var options = this.options + // Remove ending `/` unless removeSingleSlash is false + if ((options.removeTrailingSlash || urlObj.pathname === '/') && urlObj.hash === '' && options.removeSingleSlash) { + urlString = urlString.replace(/\/$/, ''); + } - // windows: need to use /, not \ - if (path.sep !== '/') { - f = f.split(path.sep).join('/') - } + // Restore relative protocol, if applicable + if (hasRelativeProtocol && !options.normalizeProtocol) { + urlString = urlString.replace(/^http:\/\//, '//'); + } - // treat the test path as a set of pathparts. - f = f.split(slashSplit) - this.debug(this.pattern, 'split', f) + // Remove http/https + if (options.stripProtocol) { + urlString = urlString.replace(/^(?:https?:)?\/\//, ''); + } - // 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. + return urlString; +}; - var set = this.set - this.debug(this.pattern, 'set', set) +module.exports = normalizeUrl; - // 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 - } - 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 - } - } +/***/ }), - // didn't get any hits. this is success if it's a negative - // pattern, failure otherwise. - if (options.flipNegate) return false - return this.negate -} +/***/ 20502: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// 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 +"use strict"; - this.debug('matchOne', - { 'this': this, file: file, pattern: pattern }) +const path = __nccwpck_require__(71017); +const pathKey = __nccwpck_require__(20539); - this.debug('matchOne', file.length, pattern.length) +const npmRunPath = options => { + options = { + cwd: process.cwd(), + path: process.env[pathKey()], + execPath: process.execPath, + ...options + }; - 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] + let previous; + let cwdPath = path.resolve(options.cwd); + const result = []; - this.debug(pattern, p, f) + while (previous !== cwdPath) { + result.push(path.join(cwdPath, 'node_modules/.bin')); + previous = cwdPath; + cwdPath = path.resolve(cwdPath, '..'); + } - // 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 - } + // Ensure the running `node` binary is used + const execPathDir = path.resolve(options.cwd, options.execPath, '..'); + result.push(execPathDir); - // ok, let's see if we can swallow whatever we can. - while (fr < fl) { - var swallowee = file[fr] + return result.concat(options.path).join(path.delimiter); +}; - this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) +module.exports = npmRunPath; +// TODO: Remove this for the next major release +module.exports["default"] = npmRunPath; - // 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 - } +module.exports.env = options => { + options = { + env: process.env, + ...options + }; - // ** swallows a segment, and continue. - this.debug('globstar swallow a segment, and continue') - fr++ - } - } + const env = {...options.env}; + const path = pathKey({env}); - // 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 - } + options.path = env[path]; + env[path] = module.exports(options); - // 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 env; +}; - 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 - } 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] === '') - } +/***/ 43248: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // should be unreachable. - /* istanbul ignore next */ - throw new Error('wtf?') -} +var crypto = __nccwpck_require__(6113) -// replace stuff like \* with * -function globUnescape (s) { - return s.replace(/\\(.)/g, '$1') +function sha (key, body, algorithm) { + return crypto.createHmac(algorithm, key).update(body).digest('base64') } -function regExpEscape (s) { - return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +function rsa (key, body) { + return crypto.createSign('RSA-SHA1').update(body).sign(key, 'base64') } +function rfc3986 (str) { + return encodeURIComponent(str) + .replace(/!/g,'%21') + .replace(/\*/g,'%2A') + .replace(/\(/g,'%28') + .replace(/\)/g,'%29') + .replace(/'/g,'%27') +} -/***/ }), - -/***/ 41077: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const proc = typeof process === 'object' && process ? process : { - stdout: null, - stderr: null, +// Maps object to bi-dimensional array +// Converts { foo: 'A', bar: [ 'b', 'B' ]} to +// [ ['foo', 'A'], ['bar', 'b'], ['bar', 'B'] ] +function map (obj) { + var key, val, arr = [] + for (key in obj) { + val = obj[key] + if (Array.isArray(val)) + for (var i = 0; i < val.length; i++) + arr.push([key, val[i]]) + else if (typeof val === 'object') + for (var prop in val) + arr.push([key + '[' + prop + ']', val[prop]]) + else + arr.push([key, val]) + } + return arr } -const EE = __nccwpck_require__(82361) -const Stream = __nccwpck_require__(12781) -const SD = (__nccwpck_require__(71576).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') +// Compare function for sort +function compare (a, b) { + return a > b ? 1 : a < b ? -1 : 0 +} -const defer = fn => Promise.resolve().then(fn) +function generateBase (httpMethod, base_uri, params) { + // adapted from https://dev.twitter.com/docs/auth/oauth and + // https://dev.twitter.com/docs/auth/creating-signature -// 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') + // Parameter normalization + // http://tools.ietf.org/html/rfc5849#section-3.4.1.3.2 + var normalized = map(params) + // 1. First, the name and value of each parameter are encoded + .map(function (p) { + return [ rfc3986(p[0]), rfc3986(p[1] || '') ] + }) + // 2. The parameters are sorted by name, using ascending byte value + // ordering. If two or more parameters share the same name, they + // are sorted by their value. + .sort(function (a, b) { + return compare(a[0], b[0]) || compare(a[1], b[1]) + }) + // 3. The name of each parameter is concatenated to its corresponding + // value using an "=" character (ASCII code 61) as a separator, even + // if the value is empty. + .map(function (p) { return p.join('=') }) + // 4. The sorted name/value pairs are concatenated together into a + // single string by using an "&" character (ASCII code 38) as + // separator. + .join('&') -// 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' + var base = [ + rfc3986(httpMethod ? httpMethod.toUpperCase() : 'GET'), + rfc3986(base_uri), + rfc3986(normalized) + ].join('&') -const isArrayBuffer = b => b instanceof ArrayBuffer || - typeof b === 'object' && - b.constructor && - b.constructor.name === 'ArrayBuffer' && - b.byteLength >= 0 + return base +} -const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) +function hmacsign (httpMethod, base_uri, params, consumer_secret, token_secret) { + var base = generateBase(httpMethod, base_uri, params) + var key = [ + consumer_secret || '', + token_secret || '' + ].map(rfc3986).join('&') -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 sha(key, base, 'sha1') } -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) - } +function hmacsign256 (httpMethod, base_uri, params, consumer_secret, token_secret) { + var base = generateBase(httpMethod, base_uri, params) + var key = [ + consumer_secret || '', + token_secret || '' + ].map(rfc3986).join('&') + + return sha(key, base, 'sha256') } -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 - } +function rsasign (httpMethod, base_uri, params, private_key, token_secret) { + var base = generateBase(httpMethod, base_uri, params) + var key = private_key || '' - get bufferLength () { return this[BUFFERLENGTH] } + return rsa(key, base) +} - get encoding () { return this[ENCODING] } - set encoding (enc) { - if (this[OBJECTMODE]) - throw new Error('cannot set encoding in objectMode') +function plaintext (consumer_secret, token_secret) { + var key = [ + consumer_secret || '', + token_secret || '' + ].map(rfc3986).join('&') - if (this[ENCODING] && enc !== this[ENCODING] && - (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH])) - throw new Error('cannot change encoding') + return key +} - 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 sign (signMethod, httpMethod, base_uri, params, consumer_secret, token_secret) { + var method + var skipArgs = 1 - this[ENCODING] = enc + switch (signMethod) { + case 'RSA-SHA1': + method = rsasign + break + case 'HMAC-SHA1': + method = hmacsign + break + case 'HMAC-SHA256': + method = hmacsign256 + break + case 'PLAINTEXT': + method = plaintext + skipArgs = 4 + break + default: + throw new Error('Signature method not supported: ' + signMethod) } - setEncoding (enc) { - this.encoding = enc - } + return method.apply(null, [].slice.call(arguments, skipArgs)) +} - get objectMode () { return this[OBJECTMODE] } - set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om } +exports.hmacsign = hmacsign +exports.hmacsign256 = hmacsign256 +exports.rsasign = rsasign +exports.plaintext = plaintext +exports.sign = sign +exports.rfc3986 = rfc3986 +exports.generateBase = generateBase - 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') +/***/ 24856: +/***/ ((module, 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' - if (!encoding) - encoding = 'utf8' +var crypto = __nccwpck_require__(6113); - const fn = this[ASYNC] ? defer : f => f() +/** + * Exported function + * + * Options: + * + * - `algorithm` hash algo to be used by this instance: *'sha1', 'md5' + * - `excludeValues` {true|*false} hash object keys, values ignored + * - `encoding` hash encoding, supports 'buffer', '*hex', 'binary', 'base64' + * - `ignoreUnknown` {true|*false} ignore unknown object types + * - `replacer` optional function that replaces values before hashing + * - `respectFunctionProperties` {*true|false} consider function properties when hashing + * - `respectFunctionNames` {*true|false} consider 'name' property of functions for hashing + * - `respectType` {*true|false} Respect special properties (prototype, constructor) + * when hashing to distinguish between types + * - `unorderedArrays` {true|*false} Sort all arrays before hashing + * - `unorderedSets` {*true|false} Sort `Set` and `Map` instances before hashing + * * = default + * + * @param {object} object value to hash + * @param {object} options hashing options + * @return {string} hash value + * @api public + */ +exports = module.exports = objectHash; - // 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 - } +function objectHash(object, options){ + options = applyDefaults(object, options); - // 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 hash(object, options); +} + +/** + * Exported sugar methods + * + * @param {object} object value to hash + * @return {string} hash value + * @api public + */ +exports.sha1 = function(object){ + return objectHash(object); +}; +exports.keys = function(object){ + return objectHash(object, {excludeValues: true, algorithm: 'sha1', encoding: 'hex'}); +}; +exports.MD5 = function(object){ + return objectHash(object, {algorithm: 'md5', encoding: 'hex'}); +}; +exports.keysMD5 = function(object){ + return objectHash(object, {algorithm: 'md5', encoding: 'hex', excludeValues: true}); +}; - if (this.flowing) - this.emit('data', chunk) - else - this[BUFFERPUSH](chunk) +// Internals +var hashes = crypto.getHashes ? crypto.getHashes().slice() : ['sha1', 'md5']; +hashes.push('passthrough'); +var encodings = ['buffer', 'hex', 'binary', 'base64']; - if (this[BUFFERLENGTH] !== 0) - this.emit('readable') +function applyDefaults(object, sourceOptions){ + sourceOptions = sourceOptions || {}; - if (cb) - fn(cb) + // create a copy rather than mutating + var options = {}; + options.algorithm = sourceOptions.algorithm || 'sha1'; + options.encoding = sourceOptions.encoding || 'hex'; + options.excludeValues = sourceOptions.excludeValues ? true : false; + options.algorithm = options.algorithm.toLowerCase(); + options.encoding = options.encoding.toLowerCase(); + options.ignoreUnknown = sourceOptions.ignoreUnknown !== true ? false : true; // default to false + options.respectType = sourceOptions.respectType === false ? false : true; // default to true + options.respectFunctionNames = sourceOptions.respectFunctionNames === false ? false : true; + options.respectFunctionProperties = sourceOptions.respectFunctionProperties === false ? false : true; + options.unorderedArrays = sourceOptions.unorderedArrays !== true ? false : true; // default to false + options.unorderedSets = sourceOptions.unorderedSets === false ? false : true; // default to false + options.unorderedObjects = sourceOptions.unorderedObjects === false ? false : true; // default to true + options.replacer = sourceOptions.replacer || undefined; + options.excludeKeys = sourceOptions.excludeKeys || undefined; - return this.flowing - } + if(typeof object === 'undefined') { + throw new Error('Object argument required.'); + } - // 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 there is a case-insensitive match in the hashes list, accept it + // (i.e. SHA256 for sha256) + for (var i = 0; i < hashes.length; ++i) { + if (hashes[i].toLowerCase() === options.algorithm.toLowerCase()) { + options.algorithm = hashes[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(hashes.indexOf(options.algorithm) === -1){ + throw new Error('Algorithm "' + options.algorithm + '" not supported. ' + + 'supported values: ' + hashes.join(', ')); + } - if (Buffer.isBuffer(chunk) && this[ENCODING]) - chunk = this[DECODER].write(chunk) + if(encodings.indexOf(options.encoding) === -1 && + options.algorithm !== 'passthrough'){ + throw new Error('Encoding "' + options.encoding + '" not supported. ' + + 'supported values: ' + encodings.join(', ')); + } - // Note: flushing CAN potentially switch us into not-flowing mode - if (this.flowing && this[BUFFERLENGTH] !== 0) - this[FLUSH](true) + return options; +} - if (this.flowing) - this.emit('data', chunk) - else - this[BUFFERPUSH](chunk) +/** Check if the given function is a native function */ +function isNativeFunction(f) { + if ((typeof f) !== 'function') { + return false; + } + var exp = /^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i; + return exp.exec(Function.prototype.toString.call(f)) != null; +} - if (this[BUFFERLENGTH] !== 0) - this.emit('readable') +function hash(object, options) { + var hashingStream; - if (cb) - fn(cb) + if (options.algorithm !== 'passthrough') { + hashingStream = crypto.createHash(options.algorithm); + } else { + hashingStream = new PassThrough(); + } - return this.flowing + if (typeof hashingStream.write === 'undefined') { + hashingStream.write = hashingStream.update; + hashingStream.end = hashingStream.update; } - read (n) { - if (this[DESTROYED]) - return null + var hasher = typeHasher(options, hashingStream); + hasher.dispatch(object); + if (!hashingStream.update) { + hashingStream.end(''); + } - if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) { - this[MAYBE_EMIT_END]() - return null - } + if (hashingStream.digest) { + return hashingStream.digest(options.encoding === 'buffer' ? undefined : options.encoding); + } - if (this[OBJECTMODE]) - n = null + var buf = hashingStream.read(); + if (options.encoding === 'buffer') { + return buf; + } - if (this.buffer.length > 1 && !this[OBJECTMODE]) { - if (this.encoding) - this.buffer = [this.buffer.join('')] - else - this.buffer = [Buffer.concat(this.buffer, this[BUFFERLENGTH])] - } + return buf.toString(options.encoding); +} - const ret = this[READ](n || null, this.buffer[0]) - this[MAYBE_EMIT_END]() - return ret +/** + * Expose streaming API + * + * @param {object} object Value to serialize + * @param {object} options Options, as for hash() + * @param {object} stream A stream to write the serializiation to + * @api public + */ +exports.writeToStream = function(object, options, stream) { + if (typeof stream === 'undefined') { + stream = options; + options = {}; } - [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 + options = applyDefaults(object, options); + + return typeHasher(options, stream).dispatch(object); +}; + +function typeHasher(options, writeTo, context){ + context = context || []; + var write = function(str) { + if (writeTo.update) { + return writeTo.update(str, 'utf8'); + } else { + return writeTo.write(str, 'utf8'); } + }; - this.emit('data', chunk) + return { + dispatch: function(value){ + if (options.replacer) { + value = options.replacer(value); + } - if (!this.buffer.length && !this[EOF]) - this.emit('drain') + var type = typeof value; + if (value === null) { + type = 'null'; + } - return chunk - } + //console.log("[DEBUG] Dispatch: ", value, "->", type, " -> ", "_" + type); - 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 + return this['_' + type](value); + }, + _object: function(object) { + var pattern = (/\[object (.*)\]/i); + var objString = Object.prototype.toString.call(object); + var objType = pattern.exec(objString); + if (!objType) { // object type did not match [object ...] + objType = 'unknown:[' + objString + ']'; + } else { + objType = objType[1]; // take only the class name + } - // 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 - } + objType = objType.toLowerCase(); - // don't let the internal resume be overwritten - [RESUME] () { - if (this[DESTROYED]) - return + var objectNumber = null; - 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 ((objectNumber = context.indexOf(object)) >= 0) { + return this.dispatch('[CIRCULAR:' + objectNumber + ']'); + } else { + context.push(object); + } - resume () { - return this[RESUME]() - } + if (typeof Buffer !== 'undefined' && Buffer.isBuffer && Buffer.isBuffer(object)) { + write('buffer:'); + return write(object); + } - pause () { - this[FLOWING] = false - this[PAUSED] = true - } + if(objType !== 'object' && objType !== 'function' && objType !== 'asyncfunction') { + if(this['_' + objType]) { + this['_' + objType](object); + } else if (options.ignoreUnknown) { + return write('[' + objType + ']'); + } else { + throw new Error('Unknown object type "' + objType + '"'); + } + }else{ + var keys = Object.keys(object); + if (options.unorderedObjects) { + keys = keys.sort(); + } + // Make sure to incorporate special properties, so + // Types with different prototypes will produce + // a different hash and objects derived from + // different functions (`new Foo`, `new Bar`) will + // produce different hashes. + // We never do this for native functions since some + // seem to break because of that. + if (options.respectType !== false && !isNativeFunction(object)) { + keys.splice(0, 0, 'prototype', '__proto__', 'constructor'); + } - get destroyed () { - return this[DESTROYED] - } + if (options.excludeKeys) { + keys = keys.filter(function(key) { return !options.excludeKeys(key); }); + } - get flowing () { - return this[FLOWING] - } + write('object:' + keys.length + ':'); + var self = this; + return keys.forEach(function(key){ + self.dispatch(key); + write(':'); + if(!options.excludeValues) { + self.dispatch(object[key]); + } + write(','); + }); + } + }, + _array: function(arr, unordered){ + unordered = typeof unordered !== 'undefined' ? unordered : + options.unorderedArrays !== false; // default to options.unorderedArrays - get paused () { - return this[PAUSED] - } + var self = this; + write('array:' + arr.length + ':'); + if (!unordered || arr.length <= 1) { + return arr.forEach(function(entry) { + return self.dispatch(entry); + }); + } - [BUFFERPUSH] (chunk) { - if (this[OBJECTMODE]) - this[BUFFERLENGTH] += 1 - else - this[BUFFERLENGTH] += chunk.length - this.buffer.push(chunk) - } + // the unordered case is a little more complicated: + // since there is no canonical ordering on objects, + // i.e. {a:1} < {a:2} and {a:1} > {a:2} are both false, + // we first serialize each entry using a PassThrough stream + // before sorting. + // also: we can’t use the same context array for all entries + // since the order of hashing should *not* matter. instead, + // we keep track of the additions to a copy of the context array + // and add all of them to the global context array when we’re done + var contextAdditions = []; + var entries = arr.map(function(entry) { + var strm = new PassThrough(); + var localContext = context.slice(); // make copy + var hasher = typeHasher(options, strm, localContext); + hasher.dispatch(entry); + // take only what was added to localContext and append it to contextAdditions + contextAdditions = contextAdditions.concat(localContext.slice(context.length)); + return strm.read().toString(); + }); + context = context.concat(contextAdditions); + entries.sort(); + return this._array(entries, false); + }, + _date: function(date){ + return write('date:' + date.toJSON()); + }, + _symbol: function(sym){ + return write('symbol:' + sym.toString()); + }, + _error: function(err){ + return write('error:' + err.toString()); + }, + _boolean: function(bool){ + return write('bool:' + bool.toString()); + }, + _string: function(string){ + write('string:' + string.length + ':'); + write(string.toString()); + }, + _function: function(fn){ + write('fn:'); + if (isNativeFunction(fn)) { + this.dispatch('[native]'); + } else { + this.dispatch(fn.toString()); + } - [BUFFERSHIFT] () { - if (this.buffer.length) { - if (this[OBJECTMODE]) - this[BUFFERLENGTH] -= 1 - else - this[BUFFERLENGTH] -= this.buffer[0].length - } - return this.buffer.shift() - } + if (options.respectFunctionNames !== false) { + // Make sure we can still distinguish native functions + // by their name, otherwise String and Function will + // have the same hash + this.dispatch("function-name:" + String(fn.name)); + } - [FLUSH] (noDrain) { - do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]())) + if (options.respectFunctionProperties) { + this._object(fn); + } + }, + _number: function(number){ + return write('number:' + number.toString()); + }, + _xml: function(xml){ + return write('xml:' + xml.toString()); + }, + _null: function() { + return write('Null'); + }, + _undefined: function() { + return write('Undefined'); + }, + _regexp: function(regex){ + return write('regex:' + regex.toString()); + }, + _uint8array: function(arr){ + write('uint8array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _uint8clampedarray: function(arr){ + write('uint8clampedarray:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _int8array: function(arr){ + write('uint8array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _uint16array: function(arr){ + write('uint16array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _int16array: function(arr){ + write('uint16array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _uint32array: function(arr){ + write('uint32array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _int32array: function(arr){ + write('uint32array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _float32array: function(arr){ + write('float32array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _float64array: function(arr){ + write('float64array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _arraybuffer: function(arr){ + write('arraybuffer:'); + return this.dispatch(new Uint8Array(arr)); + }, + _url: function(url) { + return write('url:' + url.toString(), 'utf8'); + }, + _map: function(map) { + write('map:'); + var arr = Array.from(map); + return this._array(arr, options.unorderedSets !== false); + }, + _set: function(set) { + write('set:'); + var arr = Array.from(set); + return this._array(arr, options.unorderedSets !== false); + }, + _file: function(file) { + write('file:'); + return this.dispatch([file.name, file.size, file.type, file.lastModfied]); + }, + _blob: function() { + if (options.ignoreUnknown) { + return write('[blob]'); + } - if (!noDrain && !this.buffer.length && !this[EOF]) - this.emit('drain') - } + throw Error('Hashing Blob objects is currently not supported\n' + + '(see https://github.com/puleos/object-hash/issues/26)\n' + + 'Use "options.replacer" or "options.ignoreUnknown"\n'); + }, + _domwindow: function() { return write('domwindow'); }, + _bigint: function(number){ + return write('bigint:' + number.toString()); + }, + /* Node.js standard native objects */ + _process: function() { return write('process'); }, + _timer: function() { return write('timer'); }, + _pipe: function() { return write('pipe'); }, + _tcp: function() { return write('tcp'); }, + _udp: function() { return write('udp'); }, + _tty: function() { return write('tty'); }, + _statwatcher: function() { return write('statwatcher'); }, + _securecontext: function() { return write('securecontext'); }, + _connection: function() { return write('connection'); }, + _zlib: function() { return write('zlib'); }, + _context: function() { return write('context'); }, + _nodescript: function() { return write('nodescript'); }, + _httpparser: function() { return write('httpparser'); }, + _dataview: function() { return write('dataview'); }, + _signal: function() { return write('signal'); }, + _fsevent: function() { return write('fsevent'); }, + _tlswrap: function() { return write('tlswrap'); }, + }; +} - [FLUSHCHUNK] (chunk) { - return chunk ? (this.emit('data', chunk), this.flowing) : false - } +// Mini-implementation of stream.PassThrough +// We are far from having need for the full implementation, and we can +// make assumptions like "many writes, then only one final read" +// and we can ignore encoding specifics +function PassThrough() { + return { + buf: '', - pipe (dest, opts) { - if (this[DESTROYED]) - return + write: function(b) { + this.buf += b; + }, - 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 + end: function(b) { + this.buf += b; + }, - // 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]() + read: function() { + return this.buf; } + }; +} - return dest - } - unpipe (dest) { - const p = this.pipes.find(p => p.dest === dest) - if (p) { - this.pipes.splice(this.pipes.indexOf(p), 1) - p.unpipe() - } - } +/***/ }), - addListener (ev, fn) { - return this.on(ev, fn) - } +/***/ 1270: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - 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 { strict: assert } = __nccwpck_require__(39491); +const { createHash } = __nccwpck_require__(6113); +const { format } = __nccwpck_require__(73837); - get emittedEnd () { - return this[EMITTED_END] - } +const shake256 = __nccwpck_require__(19811); - [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 encode; +if (Buffer.isEncoding('base64url')) { + encode = (input) => input.toString('base64url'); +} else { + const fromBase64 = (base64) => base64.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); + encode = (input) => fromBase64(input.toString('base64')); +} - 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 - } +/** SPECIFICATION + * Its (_hash) value is the base64url encoding of the left-most half of the hash of the octets of + * the ASCII representation of the token value, where the hash algorithm used is the hash algorithm + * used in the alg Header Parameter of the ID Token's JOSE Header. For instance, if the alg is + * RS256, hash the token value with SHA-256, then take the left-most 128 bits and base64url encode + * them. The _hash value is a case sensitive string. + */ - // Some other unknown event - const ret = super.emit(ev, data, ...extra) - this[MAYBE_EMIT_END]() - return ret - } +/** + * @name getHash + * @api private + * + * returns the sha length based off the JOSE alg heade value, defaults to sha256 + * + * @param token {String} token value to generate the hash from + * @param alg {String} ID Token JOSE header alg value (i.e. RS256, HS384, ES512, PS256) + * @param [crv] {String} For EdDSA the curve decides what hash algorithm is used. Required for EdDSA + */ +function getHash(alg, crv) { + switch (alg) { + case 'HS256': + case 'RS256': + case 'PS256': + case 'ES256': + case 'ES256K': + return createHash('sha256'); - [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 - } + case 'HS384': + case 'RS384': + case 'PS384': + case 'ES384': + return createHash('sha384'); - [EMITEND] () { - if (this[EMITTED_END]) - return + case 'HS512': + case 'RS512': + case 'PS512': + case 'ES512': + return createHash('sha512'); - this[EMITTED_END] = true - this.readable = false - if (this[ASYNC]) - defer(() => this[EMITEND2]()) - else - this[EMITEND2]() - } + case 'EdDSA': + switch (crv) { + case 'Ed25519': + return createHash('sha512'); + case 'Ed448': + if (!shake256) { + throw new TypeError('Ed448 *_hash calculation is not supported in your Node.js runtime version'); + } - [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) + return createHash('shake256', { outputLength: 114 }); + default: + throw new TypeError('unrecognized or invalid EdDSA curve provided'); } - } - for (const p of this.pipes) { - p.end() - } - const ret = super.emit('end') - this.removeAllListeners('end') - return ret + default: + throw new TypeError('unrecognized or invalid JWS algorithm provided'); } +} - // 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) +function generate(token, alg, crv) { + const digest = getHash(alg, crv).update(token).digest(); + return encode(digest.slice(0, digest.length / 2)); +} + +function validate(names, actual, source, alg, crv) { + if (typeof names.claim !== 'string' || !names.claim) { + throw new TypeError('names.claim must be a non-empty string'); } - // 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 (typeof names.source !== 'string' || !names.source) { + throw new TypeError('names.source must be a non-empty string'); } - // 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()) - }) + assert(typeof actual === 'string' && actual, `${names.claim} must be a non-empty string`); + assert(typeof source === 'string' && source, `${names.source} must be a non-empty string`); + + let expected; + let msg; + try { + expected = generate(source, alg, crv); + } catch (err) { + msg = format('%s could not be validated (%s)', names.claim, err.message); } - // for await (let chunk of stream) - [ASYNCITERATOR] () { - const next = () => { - const res = this.read() - if (res !== null) - return Promise.resolve({ done: false, value: res }) + msg = msg || format('%s mismatch, expected %s, got: %s', names.claim, expected, actual); - if (this[EOF]) - return Promise.resolve({ done: true }) + assert.equal(expected, actual, msg); +} - 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) - }) - } +module.exports = { + validate, + generate, +}; - return { next } - } - // for (let chunk of stream) - [ITERATOR] () { - const next = () => { - const value = this.read() - const done = value === null - return { value, done } - } - return { next } - } +/***/ }), - destroy (er) { - if (this[DESTROYED]) { - if (er) - this.emit('error', er) - else - this.emit(DESTROYED) - return this - } +/***/ 19811: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - this[DESTROYED] = true +const crypto = __nccwpck_require__(6113); - // throw away all buffered data, it's never coming out - this.buffer.length = 0 - this[BUFFERLENGTH] = 0 +const [major, minor] = process.version.substring(1).split('.').map((x) => parseInt(x, 10)); +const xofOutputLength = major > 12 || (major === 12 && minor >= 8); +const shake256 = xofOutputLength && crypto.getHashes().includes('shake256'); - if (typeof this.close === 'function' && !this[CLOSED]) - this.close() +module.exports = shake256; - if (er) - this.emit('error', er) - else // if no error to emit, still reject pending promises - this.emit(DESTROYED) - return this +/***/ }), + +/***/ 1223: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var wrappy = __nccwpck_require__(62940) +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 +} - 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 - )) +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 } /***/ }), -/***/ 6769: +/***/ 89082: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Update with any zlib constants that are added or changed in the future. -// Node v6 didn't export this, so we just hard code the version and rely -// on all the other hard-coded values from zlib v4736. When node v6 -// support drops, we can just export the realZlibConstants object. -const realZlibConstants = (__nccwpck_require__(59796).constants) || - /* istanbul ignore next */ { ZLIB_VERNUM: 4736 } +"use strict"; -module.exports = Object.freeze(Object.assign(Object.create(null), { - Z_NO_FLUSH: 0, - Z_PARTIAL_FLUSH: 1, - Z_SYNC_FLUSH: 2, - Z_FULL_FLUSH: 3, - Z_FINISH: 4, - Z_BLOCK: 5, - Z_OK: 0, - Z_STREAM_END: 1, - Z_NEED_DICT: 2, - Z_ERRNO: -1, - Z_STREAM_ERROR: -2, - Z_DATA_ERROR: -3, - Z_MEM_ERROR: -4, - Z_BUF_ERROR: -5, - Z_VERSION_ERROR: -6, - Z_NO_COMPRESSION: 0, - Z_BEST_SPEED: 1, - Z_BEST_COMPRESSION: 9, - Z_DEFAULT_COMPRESSION: -1, - Z_FILTERED: 1, - Z_HUFFMAN_ONLY: 2, - Z_RLE: 3, - Z_FIXED: 4, - Z_DEFAULT_STRATEGY: 0, - DEFLATE: 1, - INFLATE: 2, - GZIP: 3, - GUNZIP: 4, - DEFLATERAW: 5, - INFLATERAW: 6, - UNZIP: 7, - BROTLI_DECODE: 8, - BROTLI_ENCODE: 9, - Z_MIN_WINDOWBITS: 8, - Z_MAX_WINDOWBITS: 15, - Z_DEFAULT_WINDOWBITS: 15, - Z_MIN_CHUNK: 64, - Z_MAX_CHUNK: Infinity, - Z_DEFAULT_CHUNK: 16384, - Z_MIN_MEMLEVEL: 1, - Z_MAX_MEMLEVEL: 9, - Z_DEFAULT_MEMLEVEL: 8, - Z_MIN_LEVEL: -1, - Z_MAX_LEVEL: 9, - Z_DEFAULT_LEVEL: -1, - BROTLI_OPERATION_PROCESS: 0, - BROTLI_OPERATION_FLUSH: 1, - BROTLI_OPERATION_FINISH: 2, - BROTLI_OPERATION_EMIT_METADATA: 3, - BROTLI_MODE_GENERIC: 0, - BROTLI_MODE_TEXT: 1, - BROTLI_MODE_FONT: 2, - BROTLI_DEFAULT_MODE: 0, - BROTLI_MIN_QUALITY: 0, - BROTLI_MAX_QUALITY: 11, - BROTLI_DEFAULT_QUALITY: 11, - BROTLI_MIN_WINDOW_BITS: 10, - BROTLI_MAX_WINDOW_BITS: 24, - BROTLI_LARGE_MAX_WINDOW_BITS: 30, - BROTLI_DEFAULT_WINDOW: 22, - BROTLI_MIN_INPUT_BLOCK_BITS: 16, - BROTLI_MAX_INPUT_BLOCK_BITS: 24, - BROTLI_PARAM_MODE: 0, - BROTLI_PARAM_QUALITY: 1, - BROTLI_PARAM_LGWIN: 2, - BROTLI_PARAM_LGBLOCK: 3, - BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4, - BROTLI_PARAM_SIZE_HINT: 5, - BROTLI_PARAM_LARGE_WINDOW: 6, - BROTLI_PARAM_NPOSTFIX: 7, - BROTLI_PARAM_NDIRECT: 8, - BROTLI_DECODER_RESULT_ERROR: 0, - BROTLI_DECODER_RESULT_SUCCESS: 1, - BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2, - BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3, - BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0, - BROTLI_DECODER_PARAM_LARGE_WINDOW: 1, - BROTLI_DECODER_NO_ERROR: 0, - BROTLI_DECODER_SUCCESS: 1, - BROTLI_DECODER_NEEDS_MORE_INPUT: 2, - BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3, - BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1, - BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2, - BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3, - BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4, - BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5, - BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6, - BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7, - BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8, - BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9, - BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10, - BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11, - BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12, - BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13, - BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14, - BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15, - BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16, - BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19, - BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20, - BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21, - BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22, - BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25, - BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26, - BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27, - BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30, - BROTLI_DECODER_ERROR_UNREACHABLE: -31, -}, realZlibConstants)) +const mimicFn = __nccwpck_require__(76047); + +const calledFunctions = new WeakMap(); + +const onetime = (function_, options = {}) => { + if (typeof function_ !== 'function') { + throw new TypeError('Expected a function'); + } + + let returnValue; + let callCount = 0; + const functionName = function_.displayName || function_.name || ''; + + const onetime = function (...arguments_) { + calledFunctions.set(onetime, ++callCount); + + if (callCount === 1) { + returnValue = function_.apply(this, arguments_); + function_ = null; + } else if (options.throw === true) { + throw new Error(`Function \`${functionName}\` can only be called once`); + } + + return returnValue; + }; + + mimicFn(onetime, function_); + calledFunctions.set(onetime, callCount); + + return onetime; +}; + +module.exports = onetime; +// TODO: Remove this for the next major release +module.exports["default"] = onetime; + +module.exports.callCount = function_ => { + if (!calledFunctions.has(function_)) { + throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`); + } + + return calledFunctions.get(function_); +}; /***/ }), -/***/ 33486: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 28300: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +/* eslint-disable max-classes-per-file */ +const { inspect } = __nccwpck_require__(73837); +const stdhttp = __nccwpck_require__(13685); +const crypto = __nccwpck_require__(6113); +const { strict: assert } = __nccwpck_require__(39491); +const querystring = __nccwpck_require__(63477); +const url = __nccwpck_require__(57310); -const assert = __nccwpck_require__(39491) -const Buffer = (__nccwpck_require__(14300).Buffer) -const realZlib = __nccwpck_require__(59796) +const { ParseError } = __nccwpck_require__(93061); +const jose = __nccwpck_require__(16425); +const tokenHash = __nccwpck_require__(1270); -const constants = exports.constants = __nccwpck_require__(6769) -const Minipass = __nccwpck_require__(41077) +const base64url = __nccwpck_require__(61827); +const defaults = __nccwpck_require__(13098); +const { assertSigningAlgValuesSupport, assertIssuerConfiguration } = __nccwpck_require__(63217); +const pick = __nccwpck_require__(78857); +const isPlainObject = __nccwpck_require__(39862); +const processResponse = __nccwpck_require__(28576); +const TokenSet = __nccwpck_require__(39029); +const { OPError, RPError } = __nccwpck_require__(45061); +const now = __nccwpck_require__(8542); +const { random } = __nccwpck_require__(75421); +const request = __nccwpck_require__(92946); +const { + CALLBACK_PROPERTIES, CLIENT_DEFAULTS, JWT_CONTENT, CLOCK_TOLERANCE, +} = __nccwpck_require__(27556); +const issuerRegistry = __nccwpck_require__(30730); +const instance = __nccwpck_require__(27702); +const { authenticatedPost, resolveResponseType, resolveRedirectUri } = __nccwpck_require__(7619); +const DeviceFlowHandle = __nccwpck_require__(23979); -const OriginalBufferConcat = Buffer.concat +function pickCb(input) { + return pick(input, ...CALLBACK_PROPERTIES); +} -const _superWrite = Symbol('_superWrite') -class ZlibError extends Error { - constructor (err) { - super('zlib: ' + err.message) - this.code = err.code - this.errno = err.errno - /* istanbul ignore if */ - if (!this.code) - this.code = 'ZLIB_ERROR' +function authorizationHeaderValue(token, tokenType = 'Bearer') { + return `${tokenType} ${token}`; +} - this.message = 'zlib: ' + err.message - Error.captureStackTrace(this, this.constructor) +function cleanUpClaims(claims) { + if (Object.keys(claims._claim_names).length === 0) { + delete claims._claim_names; } - - get name () { - return 'ZlibError' + if (Object.keys(claims._claim_sources).length === 0) { + delete claims._claim_sources; } } -// the Zlib class they all inherit from -// This thing manages the queue of requests, and returns -// true or false if there is anything in the queue when -// you call the .write() method. -const _opts = Symbol('opts') -const _flushFlag = Symbol('flushFlag') -const _finishFlushFlag = Symbol('finishFlushFlag') -const _fullFlushFlag = Symbol('fullFlushFlag') -const _handle = Symbol('handle') -const _onError = Symbol('onError') -const _sawError = Symbol('sawError') -const _level = Symbol('level') -const _strategy = Symbol('strategy') -const _ended = Symbol('ended') -const _defaultFullFlush = Symbol('_defaultFullFlush') +function assignClaim(target, source, sourceName, throwOnMissing = true) { + return ([claim, inSource]) => { + if (inSource === sourceName) { + if (throwOnMissing && source[claim] === undefined) { + throw new RPError(`expected claim "${claim}" in "${sourceName}"`); + } else if (source[claim] !== undefined) { + target[claim] = source[claim]; + } + delete target._claim_names[claim]; + } + }; +} -class ZlibBase extends Minipass { - constructor (opts, mode) { - if (!opts || typeof opts !== 'object') - throw new TypeError('invalid options for ZlibBase constructor') +function verifyPresence(payload, jwt, prop) { + if (payload[prop] === undefined) { + throw new RPError({ + message: `missing required JWT property ${prop}`, + jwt, + }); + } +} - super(opts) - this[_sawError] = false - this[_ended] = false - this[_opts] = opts +function authorizationParams(params) { + const authParams = { + client_id: this.client_id, + scope: 'openid', + response_type: resolveResponseType.call(this), + redirect_uri: resolveRedirectUri.call(this), + ...params, + }; - this[_flushFlag] = opts.flush - this[_finishFlushFlag] = opts.finishFlush - // this will throw if any options are invalid for the class selected - try { - this[_handle] = new realZlib[mode](opts) - } catch (er) { - // make sure that all errors get decorated properly - throw new ZlibError(er) + Object.entries(authParams).forEach(([key, value]) => { + if (value === null || value === undefined) { + delete authParams[key]; + } else if (key === 'claims' && typeof value === 'object') { + authParams[key] = JSON.stringify(value); + } else if (key === 'resource' && Array.isArray(value)) { + authParams[key] = value; + } else if (typeof value !== 'string') { + authParams[key] = String(value); } + }); - this[_onError] = (err) => { - // no sense raising multiple errors, since we abort on the first one. - if (this[_sawError]) - return + return authParams; +} - this[_sawError] = true +async function claimJWT(label, jwt) { + try { + const { header, payload } = jose.JWT.decode(jwt, { complete: true }); + const { iss } = payload; - // there is no way to cleanly recover. - // continuing only obscures problems. - this.close() - this.emit('error', err) + if (header.alg === 'none') { + return payload; } - this[_handle].on('error', er => this[_onError](new ZlibError(er))) - this.once('end', () => this.close) + let key; + if (!iss || iss === this.issuer.issuer) { + key = await this.issuer.queryKeyStore(header); + } else if (issuerRegistry.has(iss)) { + key = await issuerRegistry.get(iss).queryKeyStore(header); + } else { + const discovered = await this.issuer.constructor.discover(iss); + key = await discovered.queryKeyStore(header); + } + return jose.JWT.verify(jwt, key); + } catch (err) { + if (err instanceof RPError || err instanceof OPError || err.name === 'AggregateError') { + throw err; + } else { + throw new RPError({ + printf: ['failed to validate the %s JWT (%s: %s)', label, err.name, err.message], + jwt, + }); + } } +} - close () { - if (this[_handle]) { - this[_handle].close() - this[_handle] = null - this.emit('close') - } +function getKeystore(jwks) { + if (!isPlainObject(jwks) || !Array.isArray(jwks.keys) || jwks.keys.some((k) => !isPlainObject(k) || !('kty' in k))) { + throw new TypeError('jwks must be a JSON Web Key Set formatted object'); } - reset () { - if (!this[_sawError]) { - assert(this[_handle], 'zlib binding closed') - return this[_handle].reset() + // eslint-disable-next-line no-restricted-syntax + for (const jwk of jwks.keys) { + if (jwk.kid === undefined) { + jwk.kid = `DONOTUSE.${random()}`; } } - flush (flushFlag) { - if (this.ended) - return + const keystore = jose.JWKS.asKeyStore(jwks); + if (keystore.all().some((key) => key.type !== 'private')) { + throw new TypeError('jwks must only contain private keys'); + } + return keystore; +} - if (typeof flushFlag !== 'number') - flushFlag = this[_fullFlushFlag] - this.write(Object.assign(Buffer.alloc(0), { [_flushFlag]: flushFlag })) +// if an OP doesnt support client_secret_basic but supports client_secret_post, use it instead +// this is in place to take care of most common pitfalls when first using discovered Issuers without +// the support for default values defined by Discovery 1.0 +function checkBasicSupport(client, metadata, properties) { + try { + const supported = client.issuer.token_endpoint_auth_methods_supported; + if (!supported.includes(properties.token_endpoint_auth_method)) { + if (supported.includes('client_secret_post')) { + properties.token_endpoint_auth_method = 'client_secret_post'; + } + } + } catch (err) {} +} + +function handleCommonMistakes(client, metadata, properties) { + if (!metadata.token_endpoint_auth_method) { // if no explicit value was provided + checkBasicSupport(client, metadata, properties); } - end (chunk, encoding, cb) { - if (chunk) - this.write(chunk, encoding) - this.flush(this[_finishFlushFlag]) - this[_ended] = true - return super.end(null, null, cb) + // :fp: c'mon people... RTFM + if (metadata.redirect_uri) { + if (metadata.redirect_uris) { + throw new TypeError('provide a redirect_uri or redirect_uris, not both'); + } + properties.redirect_uris = [metadata.redirect_uri]; + delete properties.redirect_uri; } - get ended () { - return this[_ended] + if (metadata.response_type) { + if (metadata.response_types) { + throw new TypeError('provide a response_type or response_types, not both'); + } + properties.response_types = [metadata.response_type]; + delete properties.response_type; } +} - write (chunk, encoding, cb) { - // process the chunk using the sync process - // then super.write() all the outputted chunks - if (typeof encoding === 'function') - cb = encoding, encoding = 'utf8' +function getDefaultsForEndpoint(endpoint, issuer, properties) { + if (!issuer[`${endpoint}_endpoint`]) return; - if (typeof chunk === 'string') - chunk = Buffer.from(chunk, encoding) + const tokenEndpointAuthMethod = properties.token_endpoint_auth_method; + const tokenEndpointAuthSigningAlg = properties.token_endpoint_auth_signing_alg; - if (this[_sawError]) - return - assert(this[_handle], 'zlib binding closed') + const eam = `${endpoint}_endpoint_auth_method`; + const easa = `${endpoint}_endpoint_auth_signing_alg`; - // _processChunk tries to .close() the native handle after it's done, so we - // intercept that by temporarily making it a no-op. - const nativeHandle = this[_handle]._handle - const originalNativeClose = nativeHandle.close - nativeHandle.close = () => {} - const originalClose = this[_handle].close - this[_handle].close = () => {} - // It also calls `Buffer.concat()` at the end, which may be convenient - // for some, but which we are not interested in as it slows us down. - Buffer.concat = (args) => args - let result - try { - const flushFlag = typeof chunk[_flushFlag] === 'number' - ? chunk[_flushFlag] : this[_flushFlag] - result = this[_handle]._processChunk(chunk, flushFlag) - // if we don't throw, reset it back how it was - Buffer.concat = OriginalBufferConcat - } catch (err) { - // or if we do, put Buffer.concat() back before we emit error - // Error events call into user code, which may call Buffer.concat() - Buffer.concat = OriginalBufferConcat - this[_onError](new ZlibError(err)) - } finally { - if (this[_handle]) { - // Core zlib resets `_handle` to null after attempting to close the - // native handle. Our no-op handler prevented actual closure, but we - // need to restore the `._handle` property. - this[_handle]._handle = nativeHandle - nativeHandle.close = originalNativeClose - this[_handle].close = originalClose - // `_processChunk()` adds an 'error' listener. If we don't remove it - // after each call, these handlers start piling up. - this[_handle].removeAllListeners('error') - // make sure OUR error listener is still attached tho - } + if (properties[eam] === undefined && properties[easa] === undefined) { + if (tokenEndpointAuthMethod !== undefined) { + properties[eam] = tokenEndpointAuthMethod; } - - if (this[_handle]) - this[_handle].on('error', er => this[_onError](new ZlibError(er))) - - let writeReturn - if (result) { - if (Array.isArray(result) && result.length > 0) { - // The first buffer is always `handle._outBuffer`, which would be - // re-used for later invocations; so, we always have to copy that one. - writeReturn = this[_superWrite](Buffer.from(result[0])) - for (let i = 1; i < result.length; i++) { - writeReturn = this[_superWrite](result[i]) - } - } else { - writeReturn = this[_superWrite](Buffer.from(result)) - } + if (tokenEndpointAuthSigningAlg !== undefined) { + properties[easa] = tokenEndpointAuthSigningAlg; } - - if (cb) - cb() - return writeReturn - } - - [_superWrite] (data) { - return super.write(data) } } -class Zlib extends ZlibBase { - constructor (opts, mode) { - opts = opts || {} +class BaseClient {} - opts.flush = opts.flush || constants.Z_NO_FLUSH - opts.finishFlush = opts.finishFlush || constants.Z_FINISH - super(opts, mode) +module.exports = (issuer, aadIssValidation = false) => class Client extends BaseClient { + /** + * @name constructor + * @api public + */ + constructor(metadata = {}, jwks, options) { + super(); - this[_fullFlushFlag] = constants.Z_FULL_FLUSH - this[_level] = opts.level - this[_strategy] = opts.strategy - } + if (typeof metadata.client_id !== 'string' || !metadata.client_id) { + throw new TypeError('client_id is required'); + } - params (level, strategy) { - if (this[_sawError]) - return + const properties = { ...CLIENT_DEFAULTS, ...metadata }; - if (!this[_handle]) - throw new Error('cannot switch params when binding is closed') + handleCommonMistakes(this, metadata, properties); - // no way to test this without also not supporting params at all - /* istanbul ignore if */ - if (!this[_handle].params) - throw new Error('not supported in this implementation') + assertSigningAlgValuesSupport('token', this.issuer, properties); - if (this[_level] !== level || this[_strategy] !== strategy) { - this.flush(constants.Z_SYNC_FLUSH) - assert(this[_handle], 'zlib binding closed') - // .params() calls .flush(), but the latter is always async in the - // core zlib. We override .flush() temporarily to intercept that and - // flush synchronously. - const origFlush = this[_handle].flush - this[_handle].flush = (flushFlag, cb) => { - this.flush(flushFlag) - cb() - } - try { - this[_handle].params(level, strategy) - } finally { - this[_handle].flush = origFlush - } - /* istanbul ignore else */ - if (this[_handle]) { - this[_level] = level - this[_strategy] = strategy + ['introspection', 'revocation'].forEach((endpoint) => { + getDefaultsForEndpoint(endpoint, this.issuer, properties); + assertSigningAlgValuesSupport(endpoint, this.issuer, properties); + }); + + Object.entries(properties).forEach(([key, value]) => { + instance(this).get('metadata').set(key, value); + if (!this[key]) { + Object.defineProperty(this, key, { + get() { return instance(this).get('metadata').get(key); }, + enumerable: true, + }); } + }); + + if (jwks !== undefined) { + const keystore = getKeystore.call(this, jwks); + instance(this).set('keystore', keystore); } - } -} -// minimal 2-byte header -class Deflate extends Zlib { - constructor (opts) { - super(opts, 'Deflate') - } -} + if (options !== undefined) { + instance(this).set('options', options); + } -class Inflate extends Zlib { - constructor (opts) { - super(opts, 'Inflate') + this[CLOCK_TOLERANCE] = 0; } -} -// gzip - bigger header, same deflate compression -const _portable = Symbol('_portable') -class Gzip extends Zlib { - constructor (opts) { - super(opts, 'Gzip') - this[_portable] = opts && !!opts.portable + /** + * @name authorizationUrl + * @api public + */ + authorizationUrl(params = {}) { + if (!isPlainObject(params)) { + throw new TypeError('params must be a plain object'); + } + assertIssuerConfiguration(this.issuer, 'authorization_endpoint'); + const target = url.parse(this.issuer.authorization_endpoint, true); + target.search = null; + target.query = { + ...target.query, + ...authorizationParams.call(this, params), + }; + return url.format(target); } - [_superWrite] (data) { - if (!this[_portable]) - return super[_superWrite](data) - - // we'll always get the header emitted in one first chunk - // overwrite the OS indicator byte with 0xFF - this[_portable] = false - data[9] = 255 - return super[_superWrite](data) - } -} + /** + * @name authorizationPost + * @api public + */ + authorizationPost(params = {}) { + if (!isPlainObject(params)) { + throw new TypeError('params must be a plain object'); + } + const inputs = authorizationParams.call(this, params); + const formInputs = Object.keys(inputs) + .map((name) => ``).join('\n'); -class Gunzip extends Zlib { - constructor (opts) { - super(opts, 'Gunzip') + return ` + + Requesting Authorization + + +
+ ${formInputs} +
+ +`; } -} -// raw - no header -class DeflateRaw extends Zlib { - constructor (opts) { - super(opts, 'DeflateRaw') - } -} + /** + * @name endSessionUrl + * @api public + */ + endSessionUrl(params = {}) { + assertIssuerConfiguration(this.issuer, 'end_session_endpoint'); -class InflateRaw extends Zlib { - constructor (opts) { - super(opts, 'InflateRaw') - } -} + const { + 0: postLogout, + length, + } = this.post_logout_redirect_uris || []; -// auto-detect header. -class Unzip extends Zlib { - constructor (opts) { - super(opts, 'Unzip') - } -} + const { + post_logout_redirect_uri = length === 1 ? postLogout : undefined, + } = params; -class Brotli extends ZlibBase { - constructor (opts, mode) { - opts = opts || {} + let hint = params.id_token_hint; - opts.flush = opts.flush || constants.BROTLI_OPERATION_PROCESS - opts.finishFlush = opts.finishFlush || constants.BROTLI_OPERATION_FINISH + if (hint instanceof TokenSet) { + if (!hint.id_token) { + throw new TypeError('id_token not present in TokenSet'); + } + hint = hint.id_token; + } - super(opts, mode) + const target = url.parse(this.issuer.end_session_endpoint, true); + target.search = null; + target.query = { + ...params, + ...target.query, + ...{ + post_logout_redirect_uri, + id_token_hint: hint, + }, + }; - this[_fullFlushFlag] = constants.BROTLI_OPERATION_FLUSH - } -} + Object.entries(target.query).forEach(([key, value]) => { + if (value === null || value === undefined) { + delete target.query[key]; + } + }); -class BrotliCompress extends Brotli { - constructor (opts) { - super(opts, 'BrotliCompress') + return url.format(target); } -} -class BrotliDecompress extends Brotli { - constructor (opts) { - super(opts, 'BrotliDecompress') - } -} + /** + * @name callbackParams + * @api public + */ + callbackParams(input) { // eslint-disable-line class-methods-use-this + const isIncomingMessage = input instanceof stdhttp.IncomingMessage + || (input && input.method && input.url); + const isString = typeof input === 'string'; -exports.Deflate = Deflate -exports.Inflate = Inflate -exports.Gzip = Gzip -exports.Gunzip = Gunzip -exports.DeflateRaw = DeflateRaw -exports.InflateRaw = InflateRaw -exports.Unzip = Unzip -/* istanbul ignore else */ -if (typeof realZlib.BrotliCompress === 'function') { - exports.BrotliCompress = BrotliCompress - exports.BrotliDecompress = BrotliDecompress -} else { - exports.BrotliCompress = exports.BrotliDecompress = class { - constructor () { - throw new Error('Brotli is not supported in this version of Node.js') + if (!isString && !isIncomingMessage) { + throw new TypeError('#callbackParams only accepts string urls, http.IncomingMessage or a lookalike'); } - } -} + if (isIncomingMessage) { + switch (input.method) { + case 'GET': + return pickCb(url.parse(input.url, true).query); + case 'POST': + if (input.body === undefined) { + throw new TypeError('incoming message body missing, include a body parser prior to this method call'); + } + switch (typeof input.body) { + case 'object': + case 'string': + if (Buffer.isBuffer(input.body)) { + return pickCb(querystring.parse(input.body.toString('utf-8'))); + } + if (typeof input.body === 'string') { + return pickCb(querystring.parse(input.body)); + } -/***/ }), + return pickCb(input.body); + default: + throw new TypeError('invalid IncomingMessage body object'); + } + default: + throw new TypeError('invalid IncomingMessage method'); + } + } else { + return pickCb(url.parse(input, true).query); + } + } -/***/ 66186: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** + * @name callback + * @api public + */ + async callback( + redirectUri, + parameters, + checks = {}, + { exchangeBody, clientAssertionPayload, DPoP } = {}, + ) { + let params = pickCb(parameters); -const optsArg = __nccwpck_require__(42853) -const pathArg = __nccwpck_require__(12930) + if (checks.jarm && !('response' in parameters)) { + throw new RPError({ + message: 'expected a JARM response', + checks, + params, + }); + } else if ('response' in parameters) { + const decrypted = await this.decryptJARM(params.response); + params = await this.validateJARM(decrypted); + } -const {mkdirpNative, mkdirpNativeSync} = __nccwpck_require__(4983) -const {mkdirpManual, mkdirpManualSync} = __nccwpck_require__(40356) -const {useNative, useNativeSync} = __nccwpck_require__(54518) + if (this.default_max_age && !checks.max_age) { + checks.max_age = this.default_max_age; + } + if (params.state && !checks.state) { + throw new TypeError('checks.state argument is missing'); + } -const mkdirp = (path, opts) => { - path = pathArg(path) - opts = optsArg(opts) - return useNative(opts) - ? mkdirpNative(path, opts) - : mkdirpManual(path, opts) -} + if (!params.state && checks.state) { + throw new RPError({ + message: 'state missing from the response', + checks, + params, + }); + } -const mkdirpSync = (path, opts) => { - path = pathArg(path) - opts = optsArg(opts) - return useNativeSync(opts) - ? mkdirpNativeSync(path, opts) - : mkdirpManualSync(path, opts) -} + if (checks.state !== params.state) { + throw new RPError({ + printf: ['state mismatch, expected %s, got: %s', checks.state, params.state], + checks, + params, + }); + } -mkdirp.sync = mkdirpSync -mkdirp.native = (path, opts) => mkdirpNative(pathArg(path), optsArg(opts)) -mkdirp.manual = (path, opts) => mkdirpManual(pathArg(path), optsArg(opts)) -mkdirp.nativeSync = (path, opts) => mkdirpNativeSync(pathArg(path), optsArg(opts)) -mkdirp.manualSync = (path, opts) => mkdirpManualSync(pathArg(path), optsArg(opts)) + if (params.error) { + throw new OPError(params); + } -module.exports = mkdirp + const RESPONSE_TYPE_REQUIRED_PARAMS = { + code: ['code'], + id_token: ['id_token'], + token: ['access_token', 'token_type'], + }; + if (checks.response_type) { + for (const type of checks.response_type.split(' ')) { // eslint-disable-line no-restricted-syntax + if (type === 'none') { + if (params.code || params.id_token || params.access_token) { + throw new RPError({ + message: 'unexpected params encountered for "none" response', + checks, + params, + }); + } + } else { + for (const param of RESPONSE_TYPE_REQUIRED_PARAMS[type]) { // eslint-disable-line no-restricted-syntax, max-len + if (!params[param]) { + throw new RPError({ + message: `${param} missing from response`, + checks, + params, + }); + } + } + } + } + } -/***/ }), + if (params.id_token) { + const tokenset = new TokenSet(params); + await this.decryptIdToken(tokenset); + await this.validateIdToken(tokenset, checks.nonce, 'authorization', checks.max_age, checks.state); -/***/ 44992: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (!params.code) { + return tokenset; + } + } -const {dirname} = __nccwpck_require__(71017) + if (params.code) { + const tokenset = await this.grant({ + ...exchangeBody, + grant_type: 'authorization_code', + code: params.code, + redirect_uri: redirectUri, + code_verifier: checks.code_verifier, + }, { clientAssertionPayload, DPoP }); -const findMade = (opts, parent, path = undefined) => { - // we never want the 'made' return value to be a root directory - if (path === parent) - return Promise.resolve() + await this.decryptIdToken(tokenset); + await this.validateIdToken(tokenset, checks.nonce, 'token', checks.max_age); - return opts.statAsync(parent).then( - st => st.isDirectory() ? path : undefined, // will fail later - er => er.code === 'ENOENT' - ? findMade(opts, dirname(parent), parent) - : undefined - ) -} + if (params.session_state) { + tokenset.session_state = params.session_state; + } -const findMadeSync = (opts, parent, path = undefined) => { - if (path === parent) - return undefined + return tokenset; + } - try { - return opts.statSync(parent).isDirectory() ? path : undefined - } catch (er) { - return er.code === 'ENOENT' - ? findMadeSync(opts, dirname(parent), parent) - : undefined + return new TokenSet(params); } -} -module.exports = {findMade, findMadeSync} + /** + * @name oauthCallback + * @api public + */ + async oauthCallback( + redirectUri, + parameters, + checks = {}, + { exchangeBody, clientAssertionPayload, DPoP } = {}, + ) { + let params = pickCb(parameters); + if (checks.jarm && !('response' in parameters)) { + throw new RPError({ + message: 'expected a JARM response', + checks, + params, + }); + } else if ('response' in parameters) { + const decrypted = await this.decryptJARM(params.response); + params = await this.validateJARM(decrypted); + } -/***/ }), + if (params.state && !checks.state) { + throw new TypeError('checks.state argument is missing'); + } -/***/ 40356: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (!params.state && checks.state) { + throw new RPError({ + message: 'state missing from the response', + checks, + params, + }); + } -const {dirname} = __nccwpck_require__(71017) + if (checks.state !== params.state) { + throw new RPError({ + printf: ['state mismatch, expected %s, got: %s', checks.state, params.state], + checks, + params, + }); + } -const mkdirpManual = (path, opts, made) => { - opts.recursive = false - const parent = dirname(path) - if (parent === path) { - return opts.mkdirAsync(path, opts).catch(er => { - // swallowed by recursive implementation on posix systems - // any other error is a failure - if (er.code !== 'EISDIR') - throw er - }) - } + if (params.error) { + throw new OPError(params); + } - return opts.mkdirAsync(path, opts).then(() => made || path, er => { - if (er.code === 'ENOENT') - return mkdirpManual(parent, opts) - .then(made => mkdirpManual(path, opts, made)) - if (er.code !== 'EEXIST' && er.code !== 'EROFS') - throw er - return opts.statAsync(path).then(st => { - if (st.isDirectory()) - return made - else - throw er - }, () => { throw er }) - }) -} + const RESPONSE_TYPE_REQUIRED_PARAMS = { + code: ['code'], + token: ['access_token', 'token_type'], + }; -const mkdirpManualSync = (path, opts, made) => { - const parent = dirname(path) - opts.recursive = false + if (checks.response_type) { + for (const type of checks.response_type.split(' ')) { // eslint-disable-line no-restricted-syntax + if (type === 'none') { + if (params.code || params.id_token || params.access_token) { + throw new RPError({ + message: 'unexpected params encountered for "none" response', + checks, + params, + }); + } + } - if (parent === path) { - try { - return opts.mkdirSync(path, opts) - } catch (er) { - // swallowed by recursive implementation on posix systems - // any other error is a failure - if (er.code !== 'EISDIR') - throw er - else - return + if (RESPONSE_TYPE_REQUIRED_PARAMS[type]) { + for (const param of RESPONSE_TYPE_REQUIRED_PARAMS[type]) { // eslint-disable-line no-restricted-syntax, max-len + if (!params[param]) { + throw new RPError({ + message: `${param} missing from response`, + checks, + params, + }); + } + } + } + } } - } - try { - opts.mkdirSync(path, opts) - return made || path - } catch (er) { - if (er.code === 'ENOENT') - return mkdirpManualSync(path, opts, mkdirpManualSync(parent, opts, made)) - if (er.code !== 'EEXIST' && er.code !== 'EROFS') - throw er - try { - if (!opts.statSync(path).isDirectory()) - throw er - } catch (_) { - throw er + if (params.code) { + return this.grant({ + ...exchangeBody, + grant_type: 'authorization_code', + code: params.code, + redirect_uri: redirectUri, + code_verifier: checks.code_verifier, + }, { clientAssertionPayload, DPoP }); } + + return new TokenSet(params); } -} -module.exports = {mkdirpManual, mkdirpManualSync} + /** + * @name decryptIdToken + * @api private + */ + async decryptIdToken(token) { + if (!this.id_token_encrypted_response_alg) { + return token; + } + let idToken = token; -/***/ }), + if (idToken instanceof TokenSet) { + if (!idToken.id_token) { + throw new TypeError('id_token not present in TokenSet'); + } + idToken = idToken.id_token; + } -/***/ 4983: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + const expectedAlg = this.id_token_encrypted_response_alg; + const expectedEnc = this.id_token_encrypted_response_enc; -const {dirname} = __nccwpck_require__(71017) -const {findMade, findMadeSync} = __nccwpck_require__(44992) -const {mkdirpManual, mkdirpManualSync} = __nccwpck_require__(40356) + const result = await this.decryptJWE(idToken, expectedAlg, expectedEnc); -const mkdirpNative = (path, opts) => { - opts.recursive = true - const parent = dirname(path) - if (parent === path) - return opts.mkdirAsync(path, opts) + if (token instanceof TokenSet) { + token.id_token = result; + return token; + } - return findMade(opts, path).then(made => - opts.mkdirAsync(path, opts).then(() => made) - .catch(er => { - if (er.code === 'ENOENT') - return mkdirpManual(path, opts) - else - throw er - })) -} + return result; + } -const mkdirpNativeSync = (path, opts) => { - opts.recursive = true - const parent = dirname(path) - if (parent === path) - return opts.mkdirSync(path, opts) + async validateJWTUserinfo(body) { + const expectedAlg = this.userinfo_signed_response_alg; - const made = findMadeSync(opts, path) - try { - opts.mkdirSync(path, opts) - return made - } catch (er) { - if (er.code === 'ENOENT') - return mkdirpManualSync(path, opts) - else - throw er + return this.validateJWT(body, expectedAlg, []); } -} - -module.exports = {mkdirpNative, mkdirpNativeSync} + /** + * @name decryptJARM + * @api private + */ + async decryptJARM(response) { + if (!this.authorization_encrypted_response_alg) { + return response; + } -/***/ }), + const expectedAlg = this.authorization_encrypted_response_alg; + const expectedEnc = this.authorization_encrypted_response_enc; -/***/ 42853: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return this.decryptJWE(response, expectedAlg, expectedEnc); + } -const { promisify } = __nccwpck_require__(73837) -const fs = __nccwpck_require__(57147) -const optsArg = opts => { - if (!opts) - opts = { mode: 0o777, fs } - else if (typeof opts === 'object') - opts = { mode: 0o777, fs, ...opts } - else if (typeof opts === 'number') - opts = { mode: opts, fs } - else if (typeof opts === 'string') - opts = { mode: parseInt(opts, 8), fs } - else - throw new TypeError('invalid options argument') + /** + * @name decryptJWTUserinfo + * @api private + */ + async decryptJWTUserinfo(body) { + if (!this.userinfo_encrypted_response_alg) { + return body; + } - opts.mkdir = opts.mkdir || opts.fs.mkdir || fs.mkdir - opts.mkdirAsync = promisify(opts.mkdir) - opts.stat = opts.stat || opts.fs.stat || fs.stat - opts.statAsync = promisify(opts.stat) - opts.statSync = opts.statSync || opts.fs.statSync || fs.statSync - opts.mkdirSync = opts.mkdirSync || opts.fs.mkdirSync || fs.mkdirSync - return opts -} -module.exports = optsArg + const expectedAlg = this.userinfo_encrypted_response_alg; + const expectedEnc = this.userinfo_encrypted_response_enc; + return this.decryptJWE(body, expectedAlg, expectedEnc); + } -/***/ }), + /** + * @name decryptJWE + * @api private + */ + async decryptJWE(jwe, expectedAlg, expectedEnc = 'A128CBC-HS256') { + const header = JSON.parse(base64url.decode(jwe.split('.')[0])); -/***/ 12930: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (header.alg !== expectedAlg) { + throw new RPError({ + printf: ['unexpected JWE alg received, expected %s, got: %s', expectedAlg, header.alg], + jwt: jwe, + }); + } -const platform = process.env.__TESTING_MKDIRP_PLATFORM__ || process.platform -const { resolve, parse } = __nccwpck_require__(71017) -const pathArg = path => { - if (/\0/.test(path)) { - // simulate same failure that node raises - throw Object.assign( - new TypeError('path must be a string without null bytes'), - { - path, - code: 'ERR_INVALID_ARG_VALUE', - } - ) - } + if (header.enc !== expectedEnc) { + throw new RPError({ + printf: ['unexpected JWE enc received, expected %s, got: %s', expectedEnc, header.enc], + jwt: jwe, + }); + } - path = resolve(path) - if (platform === 'win32') { - const badWinChars = /[*|"<>?:]/ - const {root} = parse(path) - if (badWinChars.test(path.substr(root.length))) { - throw Object.assign(new Error('Illegal characters in path.'), { - path, - code: 'EINVAL', - }) + let keyOrStore; + + if (expectedAlg.match(/^(?:RSA|ECDH)/)) { + keyOrStore = instance(this).get('keystore'); + } else { + keyOrStore = await this.joseSecret(expectedAlg === 'dir' ? expectedEnc : expectedAlg); } + + const payload = jose.JWE.decrypt(jwe, keyOrStore); + return payload.toString('utf8'); } - return path -} -module.exports = pathArg + /** + * @name validateIdToken + * @api private + */ + async validateIdToken(tokenSet, nonce, returnedBy, maxAge, state) { + let idToken = tokenSet; + const expectedAlg = this.id_token_signed_response_alg; -/***/ }), + const isTokenSet = idToken instanceof TokenSet; -/***/ 54518: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (isTokenSet) { + if (!idToken.id_token) { + throw new TypeError('id_token not present in TokenSet'); + } + idToken = idToken.id_token; + } -const fs = __nccwpck_require__(57147) + idToken = String(idToken); -const version = process.env.__TESTING_MKDIRP_NODE_VERSION__ || process.version -const versArr = version.replace(/^v/, '').split('.') -const hasNative = +versArr[0] > 10 || +versArr[0] === 10 && +versArr[1] >= 12 + const timestamp = now(); + const { protected: header, payload, key } = await this.validateJWT(idToken, expectedAlg); -const useNative = !hasNative ? () => false : opts => opts.mkdir === fs.mkdir -const useNativeSync = !hasNative ? () => false : opts => opts.mkdirSync === fs.mkdirSync + if (maxAge || (maxAge !== null && this.require_auth_time)) { + if (!payload.auth_time) { + throw new RPError({ + message: 'missing required JWT property auth_time', + jwt: idToken, + }); + } + if (typeof payload.auth_time !== 'number') { + throw new RPError({ + message: 'JWT auth_time claim must be a JSON numeric value', + jwt: idToken, + }); + } + } -module.exports = {useNative, useNativeSync} + if (maxAge && (payload.auth_time + maxAge < timestamp - this[CLOCK_TOLERANCE])) { + throw new RPError({ + printf: ['too much time has elapsed since the last End-User authentication, max_age %i, auth_time: %i, now %i', maxAge, payload.auth_time, timestamp - this[CLOCK_TOLERANCE]], + now: timestamp, + tolerance: this[CLOCK_TOLERANCE], + auth_time: payload.auth_time, + jwt: idToken, + }); + } + if (nonce !== null && (payload.nonce || nonce !== undefined) && payload.nonce !== nonce) { + throw new RPError({ + printf: ['nonce mismatch, expected %s, got: %s', nonce, payload.nonce], + jwt: idToken, + }); + } -/***/ }), + const fapi = this.constructor.name === 'FAPIClient'; -/***/ 80900: -/***/ ((module) => { + if (returnedBy === 'authorization') { + if (!payload.at_hash && tokenSet.access_token) { + throw new RPError({ + message: 'missing required property at_hash', + jwt: idToken, + }); + } -/** - * Helpers. - */ + if (!payload.c_hash && tokenSet.code) { + throw new RPError({ + message: 'missing required property c_hash', + jwt: idToken, + }); + } -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 (fapi) { + if (!payload.s_hash && (tokenSet.state || state)) { + throw new RPError({ + message: 'missing required property s_hash', + jwt: idToken, + }); + } + } -/** - * 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 (payload.s_hash) { + if (!state) { + throw new TypeError('cannot verify s_hash, "checks.state" property not provided'); + } -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) - ); -}; + try { + tokenHash.validate({ claim: 's_hash', source: 'state' }, payload.s_hash, state, header.alg, key && key.crv); + } catch (err) { + throw new RPError({ message: err.message, jwt: idToken }); + } + } + } -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ + if (fapi && payload.iat < timestamp - 3600) { + throw new RPError({ + printf: ['JWT issued too far in the past, now %i, iat %i', timestamp, payload.iat], + now: timestamp, + tolerance: this[CLOCK_TOLERANCE], + iat: payload.iat, + jwt: idToken, + }); + } -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; - } -} + if (tokenSet.access_token && payload.at_hash !== undefined) { + try { + tokenHash.validate({ claim: 'at_hash', source: 'access_token' }, payload.at_hash, tokenSet.access_token, header.alg, key && key.crv); + } catch (err) { + throw new RPError({ message: err.message, jwt: idToken }); + } + } -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ + if (tokenSet.code && payload.c_hash !== undefined) { + try { + tokenHash.validate({ claim: 'c_hash', source: 'code' }, payload.c_hash, tokenSet.code, header.alg, key && key.crv); + } catch (err) { + throw new RPError({ message: err.message, jwt: idToken }); + } + } -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 tokenSet; } - return ms + 'ms'; -} -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ + /** + * @name validateJWT + * @api private + */ + async validateJWT(jwt, expectedAlg, required = ['iss', 'sub', 'aud', 'exp', 'iat']) { + const isSelfIssued = this.issuer.issuer === 'https://self-issued.me'; + const timestamp = now(); + let header; + let payload; + try { + ({ header, payload } = jose.JWT.decode(jwt, { complete: true })); + } catch (err) { + throw new RPError({ + printf: ['failed to decode JWT (%s: %s)', err.name, err.message], + jwt, + }); + } -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'; -} + if (header.alg !== expectedAlg) { + throw new RPError({ + printf: ['unexpected JWT alg received, expected %s, got: %s', expectedAlg, header.alg], + jwt, + }); + } -/** - * Pluralization helper. - */ + if (isSelfIssued) { + required = [...required, 'sub_jwk']; // eslint-disable-line no-param-reassign + } -function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); -} + required.forEach(verifyPresence.bind(undefined, payload, jwt)); + if (payload.iss !== undefined) { + let expectedIss = this.issuer.issuer; -/***/ }), + if (aadIssValidation) { + expectedIss = this.issuer.issuer.replace('{tenantid}', payload.tid); + } -/***/ 80467: -/***/ ((module, exports, __nccwpck_require__) => { + if (payload.iss !== expectedIss) { + throw new RPError({ + printf: ['unexpected iss value, expected %s, got: %s', expectedIss, payload.iss], + jwt, + }); + } + } -"use strict"; + if (payload.iat !== undefined) { + if (typeof payload.iat !== 'number') { + throw new RPError({ + message: 'JWT iat claim must be a JSON numeric value', + jwt, + }); + } + } + if (payload.nbf !== undefined) { + if (typeof payload.nbf !== 'number') { + throw new RPError({ + message: 'JWT nbf claim must be a JSON numeric value', + jwt, + }); + } + if (payload.nbf > timestamp + this[CLOCK_TOLERANCE]) { + throw new RPError({ + printf: ['JWT not active yet, now %i, nbf %i', timestamp + this[CLOCK_TOLERANCE], payload.nbf], + now: timestamp, + tolerance: this[CLOCK_TOLERANCE], + nbf: payload.nbf, + jwt, + }); + } + } -Object.defineProperty(exports, "__esModule", ({ value: true })); + if (payload.exp !== undefined) { + if (typeof payload.exp !== 'number') { + throw new RPError({ + message: 'JWT exp claim must be a JSON numeric value', + jwt, + }); + } + if (timestamp - this[CLOCK_TOLERANCE] >= payload.exp) { + throw new RPError({ + printf: ['JWT expired, now %i, exp %i', timestamp - this[CLOCK_TOLERANCE], payload.exp], + now: timestamp, + tolerance: this[CLOCK_TOLERANCE], + exp: payload.exp, + jwt, + }); + } + } -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + if (payload.aud !== undefined) { + if (Array.isArray(payload.aud)) { + if (payload.aud.length > 1 && !payload.azp) { + throw new RPError({ + message: 'missing required JWT property azp', + jwt, + }); + } -var Stream = _interopDefault(__nccwpck_require__(12781)); -var http = _interopDefault(__nccwpck_require__(13685)); -var Url = _interopDefault(__nccwpck_require__(57310)); -var whatwgUrl = _interopDefault(__nccwpck_require__(28665)); -var https = _interopDefault(__nccwpck_require__(95687)); -var zlib = _interopDefault(__nccwpck_require__(59796)); + if (!payload.aud.includes(this.client_id)) { + throw new RPError({ + printf: ['aud is missing the client_id, expected %s to be included in %j', this.client_id, payload.aud], + jwt, + }); + } + } else if (payload.aud !== this.client_id) { + throw new RPError({ + printf: ['aud mismatch, expected %s, got: %s', this.client_id, payload.aud], + jwt, + }); + } + } -// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + if (payload.azp !== undefined) { + let { additionalAuthorizedParties } = instance(this).get('options') || {}; -// fix for "Readable" isn't a named export issue -const Readable = Stream.Readable; + if (typeof additionalAuthorizedParties === 'string') { + additionalAuthorizedParties = [this.client_id, additionalAuthorizedParties]; + } else if (Array.isArray(additionalAuthorizedParties)) { + additionalAuthorizedParties = [this.client_id, ...additionalAuthorizedParties]; + } else { + additionalAuthorizedParties = [this.client_id]; + } -const BUFFER = Symbol('buffer'); -const TYPE = Symbol('type'); + if (!additionalAuthorizedParties.includes(payload.azp)) { + throw new RPError({ + printf: ['azp mismatch, got: %s', payload.azp], + jwt, + }); + } + } -class Blob { - constructor() { - this[TYPE] = ''; + let key; - const blobParts = arguments[0]; - const options = arguments[1]; + if (isSelfIssued) { + try { + assert(isPlainObject(payload.sub_jwk)); + key = jose.JWK.asKey(payload.sub_jwk); + assert.equal(key.type, 'public'); + } catch (err) { + throw new RPError({ + message: 'failed to use sub_jwk claim as an asymmetric JSON Web Key', + jwt, + }); + } + if (key.thumbprint !== payload.sub) { + throw new RPError({ + message: 'failed to match the subject with sub_jwk', + jwt, + }); + } + } else if (header.alg.startsWith('HS')) { + key = await this.joseSecret(); + } else if (header.alg !== 'none') { + key = await this.issuer.queryKeyStore(header); + } - const buffers = []; - let size = 0; + if (!key && header.alg === 'none') { + return { protected: header, payload }; + } - if (blobParts) { - const a = blobParts; - const length = Number(a.length); - for (let i = 0; i < length; i++) { - const element = a[i]; - let buffer; - if (element instanceof Buffer) { - buffer = element; - } else if (ArrayBuffer.isView(element)) { - buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); - } else if (element instanceof ArrayBuffer) { - buffer = Buffer.from(element); - } else if (element instanceof Blob) { - buffer = element[BUFFER]; - } else { - buffer = Buffer.from(typeof element === 'string' ? element : String(element)); - } - size += buffer.length; - buffers.push(buffer); - } - } + try { + return { + ...jose.JWS.verify(jwt, key, { complete: true }), + payload, + }; + } catch (err) { + throw new RPError({ + message: 'failed to validate JWT signature', + jwt, + }); + } + } - this[BUFFER] = Buffer.concat(buffers); + /** + * @name refresh + * @api public + */ + async refresh(refreshToken, { exchangeBody, clientAssertionPayload, DPoP } = {}) { + let token = refreshToken; - let type = options && options.type !== undefined && String(options.type).toLowerCase(); - if (type && !/[^\u0020-\u007E]/.test(type)) { - this[TYPE] = type; - } - } - get size() { - return this[BUFFER].length; - } - get type() { - return this[TYPE]; - } - text() { - return Promise.resolve(this[BUFFER].toString()); - } - arrayBuffer() { - const buf = this[BUFFER]; - const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); - return Promise.resolve(ab); - } - stream() { - const readable = new Readable(); - readable._read = function () {}; - readable.push(this[BUFFER]); - readable.push(null); - return readable; - } - toString() { - return '[object Blob]'; - } - slice() { - const size = this.size; + if (token instanceof TokenSet) { + if (!token.refresh_token) { + throw new TypeError('refresh_token not present in TokenSet'); + } + token = token.refresh_token; + } - const start = arguments[0]; - const end = arguments[1]; - let relativeStart, relativeEnd; - if (start === undefined) { - relativeStart = 0; - } else if (start < 0) { - relativeStart = Math.max(size + start, 0); - } else { - relativeStart = Math.min(start, size); - } - if (end === undefined) { - relativeEnd = size; - } else if (end < 0) { - relativeEnd = Math.max(size + end, 0); - } else { - relativeEnd = Math.min(end, size); - } - const span = Math.max(relativeEnd - relativeStart, 0); + const tokenset = await this.grant({ + ...exchangeBody, + grant_type: 'refresh_token', + refresh_token: String(token), + }, { clientAssertionPayload, DPoP }); - const buffer = this[BUFFER]; - const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); - const blob = new Blob([], { type: arguments[2] }); - blob[BUFFER] = slicedBuffer; - return blob; - } -} + if (tokenset.id_token) { + await this.decryptIdToken(tokenset); + await this.validateIdToken(tokenset, null, 'token', null); -Object.defineProperties(Blob.prototype, { - size: { enumerable: true }, - type: { enumerable: true }, - slice: { enumerable: true } -}); + if (refreshToken instanceof TokenSet && refreshToken.id_token) { + const expectedSub = refreshToken.claims().sub; + const actualSub = tokenset.claims().sub; + if (actualSub !== expectedSub) { + throw new RPError({ + printf: ['sub mismatch, expected %s, got: %s', expectedSub, actualSub], + jwt: tokenset.id_token, + }); + } + } + } -Object.defineProperty(Blob.prototype, Symbol.toStringTag, { - value: 'Blob', - writable: false, - enumerable: false, - configurable: true -}); + return tokenset; + } -/** - * fetch-error.js - * - * FetchError interface for operational errors - */ + async requestResource( + resourceUrl, + accessToken, + { + method, + headers, + body, + DPoP, + // eslint-disable-next-line no-nested-ternary + tokenType = DPoP ? 'DPoP' : accessToken instanceof TokenSet ? accessToken.token_type : 'Bearer', + } = {}, + ) { + if (accessToken instanceof TokenSet) { + if (!accessToken.access_token) { + throw new TypeError('access_token not present in TokenSet'); + } + accessToken = accessToken.access_token; // eslint-disable-line no-param-reassign + } -/** - * Create FetchError instance - * - * @param String message Error message for human - * @param String type Error type for machine - * @param String systemError For Node.js system error - * @return FetchError - */ -function FetchError(message, type, systemError) { - Error.call(this, message); + const requestOpts = { + headers: { + Authorization: authorizationHeaderValue(accessToken, tokenType), + ...headers, + }, + body, + }; - this.message = message; - this.type = type; + const mTLS = !!this.tls_client_certificate_bound_access_tokens; - // when err.type is `system`, err.code contains system error code - if (systemError) { - this.code = this.errno = systemError.code; + return request.call(this, { + ...requestOpts, + responseType: 'buffer', + method, + url: resourceUrl, + }, { accessToken, mTLS, DPoP }); } - // hide custom error implementation details from end-users - Error.captureStackTrace(this, this.constructor); -} + /** + * @name userinfo + * @api public + */ + async userinfo(accessToken, { + method = 'GET', via = 'header', tokenType, params, DPoP, + } = {}) { + assertIssuerConfiguration(this.issuer, 'userinfo_endpoint'); + const options = { + tokenType, + method: String(method).toUpperCase(), + DPoP, + }; -FetchError.prototype = Object.create(Error.prototype); -FetchError.prototype.constructor = FetchError; -FetchError.prototype.name = 'FetchError'; + if (options.method !== 'GET' && options.method !== 'POST') { + throw new TypeError('#userinfo() method can only be POST or a GET'); + } -let convert; -try { - convert = (__nccwpck_require__(22877).convert); -} catch (e) {} + if (via === 'query' && options.method !== 'GET') { + throw new TypeError('userinfo endpoints will only parse query strings for GET requests'); + } else if (via === 'body' && options.method !== 'POST') { + throw new TypeError('can only send body on POST'); + } -const INTERNALS = Symbol('Body internals'); + const jwt = !!(this.userinfo_signed_response_alg || this.userinfo_encrypted_response_alg); -// fix an issue where "PassThrough" isn't a named export for node <10 -const PassThrough = Stream.PassThrough; + if (jwt) { + options.headers = { Accept: 'application/jwt' }; + } else { + options.headers = { Accept: 'application/json' }; + } -/** - * Body mixin - * - * Ref: https://fetch.spec.whatwg.org/#body - * - * @param Stream body Readable stream - * @param Object opts Response options - * @return Void - */ -function Body(body) { - var _this = this; + const mTLS = !!this.tls_client_certificate_bound_access_tokens; - var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref$size = _ref.size; + let targetUrl; + if (mTLS && this.issuer.mtls_endpoint_aliases) { + targetUrl = this.issuer.mtls_endpoint_aliases.userinfo_endpoint; + } - let size = _ref$size === undefined ? 0 : _ref$size; - var _ref$timeout = _ref.timeout; - let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + targetUrl = new url.URL(targetUrl || this.issuer.userinfo_endpoint); - if (body == null) { - // body is undefined or null - body = null; - } else if (isURLSearchParams(body)) { - // body is a URLSearchParams - body = Buffer.from(body.toString()); - } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { - // body is ArrayBuffer - body = Buffer.from(body); - } else if (ArrayBuffer.isView(body)) { - // body is ArrayBufferView - body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); - } else if (body instanceof Stream) ; else { - // none of the above - // coerce to string then buffer - body = Buffer.from(String(body)); - } - this[INTERNALS] = { - body, - disturbed: false, - error: null - }; - this.size = size; - this.timeout = timeout; + // when via is not header we clear the Authorization header and add either + // query string parameters or urlencoded body access_token parameter + if (via === 'query') { + options.headers.Authorization = undefined; + targetUrl.searchParams.append('access_token', accessToken instanceof TokenSet ? accessToken.access_token : accessToken); + } else if (via === 'body') { + options.headers.Authorization = undefined; + options.headers['Content-Type'] = 'application/x-www-form-urlencoded'; + options.body = new url.URLSearchParams(); + options.body.append('access_token', accessToken instanceof TokenSet ? accessToken.access_token : accessToken); + } - if (body instanceof Stream) { - body.on('error', function (err) { - const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); - _this[INTERNALS].error = error; - }); - } -} + // handle additional parameters, GET via querystring, POST via urlencoded body + if (params) { + if (options.method === 'GET') { + Object.entries(params).forEach(([key, value]) => { + targetUrl.searchParams.append(key, value); + }); + } else if (options.body) { // POST && via body + Object.entries(params).forEach(([key, value]) => { + options.body.append(key, value); + }); + } else { // POST && via header + options.body = new url.URLSearchParams(); + options.headers['Content-Type'] = 'application/x-www-form-urlencoded'; + Object.entries(params).forEach(([key, value]) => { + options.body.append(key, value); + }); + } + } -Body.prototype = { - get body() { - return this[INTERNALS].body; - }, + if (options.body) { + options.body = options.body.toString(); + } - get bodyUsed() { - return this[INTERNALS].disturbed; - }, + const response = await this.requestResource(targetUrl, accessToken, options); - /** - * Decode response as ArrayBuffer - * - * @return Promise - */ - arrayBuffer() { - return consumeBody.call(this).then(function (buf) { - return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); - }); - }, + let parsed = processResponse(response, { bearer: true }); - /** - * Return raw response as Blob - * - * @return Promise - */ - blob() { - let ct = this.headers && this.headers.get('content-type') || ''; - return consumeBody.call(this).then(function (buf) { - return Object.assign( - // Prevent copying - new Blob([], { - type: ct.toLowerCase() - }), { - [BUFFER]: buf - }); - }); - }, + if (jwt) { + if (!JWT_CONTENT.test(response.headers['content-type'])) { + throw new RPError({ + message: 'expected application/jwt response from the userinfo_endpoint', + response, + }); + } - /** - * Decode response as json - * - * @return Promise - */ - json() { - var _this2 = this; + const body = response.body.toString(); + const userinfo = await this.decryptJWTUserinfo(body); + if (!this.userinfo_signed_response_alg) { + try { + parsed = JSON.parse(userinfo); + assert(isPlainObject(parsed)); + } catch (err) { + throw new RPError({ + message: 'failed to parse userinfo JWE payload as JSON', + jwt: userinfo, + }); + } + } else { + ({ payload: parsed } = await this.validateJWTUserinfo(userinfo)); + } + } else { + try { + parsed = JSON.parse(response.body); + } catch (error) { + throw new ParseError(error, response); + } + } - return consumeBody.call(this).then(function (buffer) { - try { - return JSON.parse(buffer.toString()); - } catch (err) { - return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); - } - }); - }, + if (accessToken instanceof TokenSet && accessToken.id_token) { + const expectedSub = accessToken.claims().sub; + if (parsed.sub !== expectedSub) { + throw new RPError({ + printf: ['userinfo sub mismatch, expected %s, got: %s', expectedSub, parsed.sub], + body: parsed, + jwt: accessToken.id_token, + }); + } + } - /** - * Decode response as text - * - * @return Promise - */ - text() { - return consumeBody.call(this).then(function (buffer) { - return buffer.toString(); - }); - }, + return parsed; + } - /** - * Decode response as buffer (non-spec api) - * - * @return Promise - */ - buffer() { - return consumeBody.call(this); - }, + /** + * @name derivedKey + * @api private + */ + async derivedKey(len) { + const cacheKey = `${len}_key`; + if (instance(this).has(cacheKey)) { + return instance(this).get(cacheKey); + } - /** - * Decode response as text, while automatically detecting the encoding and - * trying to decode to UTF-8 (non-spec api) - * - * @return Promise - */ - textConverted() { - var _this3 = this; + const hash = len <= 256 ? 'sha256' : len <= 384 ? 'sha384' : len <= 512 ? 'sha512' : false; // eslint-disable-line no-nested-ternary + if (!hash) { + throw new Error('unsupported symmetric encryption key derivation'); + } - return consumeBody.call(this).then(function (buffer) { - return convertBody(buffer, _this3.headers); - }); - } -}; + const derivedBuffer = crypto.createHash(hash) + .update(this.client_secret) + .digest() + .slice(0, len / 8); -// In browsers, all properties are enumerable. -Object.defineProperties(Body.prototype, { - body: { enumerable: true }, - bodyUsed: { enumerable: true }, - arrayBuffer: { enumerable: true }, - blob: { enumerable: true }, - json: { enumerable: true }, - text: { enumerable: true } -}); + const key = jose.JWK.asKey({ k: base64url.encode(derivedBuffer), kty: 'oct' }); + instance(this).set(cacheKey, key); -Body.mixIn = function (proto) { - for (const name of Object.getOwnPropertyNames(Body.prototype)) { - // istanbul ignore else: future proof - if (!(name in proto)) { - const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); - Object.defineProperty(proto, name, desc); - } - } -}; + return key; + } -/** - * Consume and convert an entire Body to a Buffer. - * - * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body - * - * @return Promise - */ -function consumeBody() { - var _this4 = this; + /** + * @name joseSecret + * @api private + */ + async joseSecret(alg) { + if (!this.client_secret) { + throw new TypeError('client_secret is required'); + } + if (/^A(\d{3})(?:GCM)?KW$/.test(alg)) { + return this.derivedKey(parseInt(RegExp.$1, 10)); + } - if (this[INTERNALS].disturbed) { - return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); - } + if (/^A(\d{3})(?:GCM|CBC-HS(\d{3}))$/.test(alg)) { + return this.derivedKey(parseInt(RegExp.$2 || RegExp.$1, 10)); + } - this[INTERNALS].disturbed = true; + if (instance(this).has('jose_secret')) { + return instance(this).get('jose_secret'); + } - if (this[INTERNALS].error) { - return Body.Promise.reject(this[INTERNALS].error); - } + const key = jose.JWK.asKey({ k: base64url.encode(this.client_secret), kty: 'oct' }); + instance(this).set('jose_secret', key); - let body = this.body; + return key; + } - // body is null - if (body === null) { - return Body.Promise.resolve(Buffer.alloc(0)); - } + /** + * @name grant + * @api public + */ + async grant(body, { clientAssertionPayload, DPoP } = {}) { + assertIssuerConfiguration(this.issuer, 'token_endpoint'); + const response = await authenticatedPost.call( + this, + 'token', + { + form: body, + responseType: 'json', + }, + { clientAssertionPayload, DPoP }, + ); + const responseBody = processResponse(response); - // body is blob - if (isBlob(body)) { - body = body.stream(); - } + return new TokenSet(responseBody); + } - // body is buffer - if (Buffer.isBuffer(body)) { - return Body.Promise.resolve(body); - } + /** + * @name deviceAuthorization + * @api public + */ + async deviceAuthorization(params = {}, { exchangeBody, clientAssertionPayload, DPoP } = {}) { + assertIssuerConfiguration(this.issuer, 'device_authorization_endpoint'); + assertIssuerConfiguration(this.issuer, 'token_endpoint'); - // istanbul ignore if: should never happen - if (!(body instanceof Stream)) { - return Body.Promise.resolve(Buffer.alloc(0)); - } + const body = authorizationParams.call(this, { + client_id: this.client_id, + redirect_uri: null, + response_type: null, + ...params, + }); + + const response = await authenticatedPost.call( + this, + 'device_authorization', + { + responseType: 'json', + form: body, + }, + { clientAssertionPayload, endpointAuthMethod: 'token' }, + ); + const responseBody = processResponse(response); - // body is stream - // get ready to actually consume the body - let accum = []; - let accumBytes = 0; - let abort = false; + return new DeviceFlowHandle({ + client: this, + exchangeBody, + clientAssertionPayload, + response: responseBody, + maxAge: params.max_age, + DPoP, + }); + } - return new Body.Promise(function (resolve, reject) { - let resTimeout; + /** + * @name revoke + * @api public + */ + async revoke(token, hint, { revokeBody, clientAssertionPayload } = {}) { + assertIssuerConfiguration(this.issuer, 'revocation_endpoint'); + if (hint !== undefined && typeof hint !== 'string') { + throw new TypeError('hint must be a string'); + } - // allow timeout on slow response body - if (_this4.timeout) { - resTimeout = setTimeout(function () { - abort = true; - reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); - }, _this4.timeout); - } + const form = { ...revokeBody, token }; - // handle stream errors - body.on('error', function (err) { - if (err.name === 'AbortError') { - // if the request was aborted, reject with this Error - abort = true; - reject(err); - } else { - // other errors, such as incorrect content-encoding - reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); - } - }); + if (hint) { + form.token_type_hint = hint; + } - body.on('data', function (chunk) { - if (abort || chunk === null) { - return; - } + const response = await authenticatedPost.call( + this, + 'revocation', { + form, + }, { clientAssertionPayload }, + ); + processResponse(response, { body: false }); + } - if (_this4.size && accumBytes + chunk.length > _this4.size) { - abort = true; - reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); - return; - } + /** + * @name introspect + * @api public + */ + async introspect(token, hint, { introspectBody, clientAssertionPayload } = {}) { + assertIssuerConfiguration(this.issuer, 'introspection_endpoint'); + if (hint !== undefined && typeof hint !== 'string') { + throw new TypeError('hint must be a string'); + } - accumBytes += chunk.length; - accum.push(chunk); - }); + const form = { ...introspectBody, token }; + if (hint) { + form.token_type_hint = hint; + } - body.on('end', function () { - if (abort) { - return; - } + const response = await authenticatedPost.call( + this, + 'introspection', + { form, responseType: 'json' }, + { clientAssertionPayload }, + ); - clearTimeout(resTimeout); + const responseBody = processResponse(response); - try { - resolve(Buffer.concat(accum, accumBytes)); - } catch (err) { - // handle streams that have accumulated too much data (issue #414) - reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); - } - }); - }); -} + return responseBody; + } -/** - * Detect buffer encoding and convert to target encoding - * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding - * - * @param Buffer buffer Incoming buffer - * @param String encoding Target encoding - * @return String - */ -function convertBody(buffer, headers) { - if (typeof convert !== 'function') { - throw new Error('The package `encoding` must be installed to use the textConverted() function'); - } + /** + * @name fetchDistributedClaims + * @api public + */ + async fetchDistributedClaims(claims, tokens = {}) { + if (!isPlainObject(claims)) { + throw new TypeError('claims argument must be a plain object'); + } - const ct = headers.get('content-type'); - let charset = 'utf-8'; - let res, str; + if (!isPlainObject(claims._claim_sources)) { + return claims; + } - // header - if (ct) { - res = /charset=([^;]*)/i.exec(ct); - } + if (!isPlainObject(claims._claim_names)) { + return claims; + } - // no charset in content type, peek at response body for at most 1024 bytes - str = buffer.slice(0, 1024).toString(); + const distributedSources = Object.entries(claims._claim_sources) + .filter(([, value]) => value && value.endpoint); - // html5 - if (!res && str) { - res = / { + try { + const requestOpts = { + headers: { + Accept: 'application/jwt', + Authorization: authorizationHeaderValue(def.access_token || tokens[sourceName]), + }, + }; - // html4 - if (!res && str) { - res = / value && value.JWT); - // Brand-checking and more duck-typing as optional condition. - return obj.constructor.name === 'URLSearchParams' || Object.prototype.toString.call(obj) === '[object URLSearchParams]' || typeof obj.sort === 'function'; -} + await Promise.all(aggregatedSources.map(async ([sourceName, def]) => { + try { + const decoded = await claimJWT.call(this, 'aggregated', def.JWT); + delete claims._claim_sources[sourceName]; + Object.entries(claims._claim_names).forEach(assignClaim(claims, decoded, sourceName)); + } catch (err) { + err.src = sourceName; + throw err; + } + })); -/** - * Check if `obj` is a W3C `Blob` object (which `File` inherits from) - * @param {*} obj - * @return {boolean} - */ -function isBlob(obj) { - return 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]); -} + cleanUpClaims(claims); + return claims; + } -/** - * Clone body given Res/Req instance - * - * @param Mixed instance Response or Request instance - * @return Mixed - */ -function clone(instance) { - let p1, p2; - let body = instance.body; + /** + * @name register + * @api public + */ + static async register(metadata, options = {}) { + const { initialAccessToken, jwks, ...clientOptions } = options; - // don't allow cloning a used body - if (instance.bodyUsed) { - throw new Error('cannot clone body after it is used'); - } + assertIssuerConfiguration(this.issuer, 'registration_endpoint'); - // check that body is a stream and not form-data object - // note: we can't clone the form-data object without having it as a dependency - if (body instanceof Stream && typeof body.getBoundary !== 'function') { - // tee instance body - p1 = new PassThrough(); - p2 = new PassThrough(); - body.pipe(p1); - body.pipe(p2); - // set instance body to teed body and return the other teed body - instance[INTERNALS].body = p1; - body = p2; - } + if (jwks !== undefined && !(metadata.jwks || metadata.jwks_uri)) { + const keystore = getKeystore.call(this, jwks); + metadata.jwks = keystore.toJWKS(false); + // eslint-disable-next-line no-restricted-syntax + for (const jwk of metadata.jwks.keys) { + if (jwk.kid.startsWith('DONOTUSE.')) { + delete jwk.kid; + } + } + } - return body; -} + const response = await request.call(this, { + headers: initialAccessToken ? { + Authorization: authorizationHeaderValue(initialAccessToken), + } : undefined, + responseType: 'json', + json: metadata, + url: this.issuer.registration_endpoint, + method: 'POST', + }); + const responseBody = processResponse(response, { statusCode: 201, bearer: true }); -/** - * Performs the operation "extract a `Content-Type` value from |object|" as - * specified in the specification: - * https://fetch.spec.whatwg.org/#concept-bodyinit-extract - * - * This function assumes that instance.body is present. - * - * @param Mixed instance Any options.body input - */ -function extractContentType(body) { - if (body === null) { - // body is null - return null; - } else if (typeof body === 'string') { - // body is string - return 'text/plain;charset=UTF-8'; - } else if (isURLSearchParams(body)) { - // body is a URLSearchParams - return 'application/x-www-form-urlencoded;charset=UTF-8'; - } else if (isBlob(body)) { - // body is blob - return body.type || null; - } else if (Buffer.isBuffer(body)) { - // body is buffer - return null; - } else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { - // body is ArrayBuffer - return null; - } else if (ArrayBuffer.isView(body)) { - // body is ArrayBufferView - return null; - } else if (typeof body.getBoundary === 'function') { - // detect form data input from form-data module - return `multipart/form-data;boundary=${body.getBoundary()}`; - } else if (body instanceof Stream) { - // body is stream - // can't really do much about this - return null; - } else { - // Body constructor defaults other things to string - return 'text/plain;charset=UTF-8'; - } -} + return new this(responseBody, jwks, clientOptions); + } -/** - * The Fetch Standard treats this as if "total bytes" is a property on the body. - * For us, we have to explicitly get it with a function. - * - * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes - * - * @param Body instance Instance of Body - * @return Number? Number of bytes, or null if not possible - */ -function getTotalBytes(instance) { - const body = instance.body; + /** + * @name metadata + * @api public + */ + get metadata() { + const copy = {}; + instance(this).get('metadata').forEach((value, key) => { + copy[key] = value; + }); + return copy; + } + /** + * @name fromUri + * @api public + */ + static async fromUri(registrationClientUri, registrationAccessToken, jwks, clientOptions) { + const response = await request.call(this, { + method: 'GET', + url: registrationClientUri, + responseType: 'json', + headers: { Authorization: authorizationHeaderValue(registrationAccessToken) }, + }); + const responseBody = processResponse(response, { bearer: true }); - if (body === null) { - // body is null - return 0; - } else if (isBlob(body)) { - return body.size; - } else if (Buffer.isBuffer(body)) { - // body is buffer - return body.length; - } else if (body && typeof body.getLengthSync === 'function') { - // detect form data input from form-data module - if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x - body.hasKnownLength && body.hasKnownLength()) { - // 2.x - return body.getLengthSync(); - } - return null; - } else { - // body is stream - return null; - } -} + return new this(responseBody, jwks, clientOptions); + } -/** - * Write a Body to a Node.js WritableStream (e.g. http.Request) object. - * - * @param Body instance Instance of Body - * @return Void - */ -function writeToStream(dest, instance) { - const body = instance.body; + /** + * @name requestObject + * @api public + */ + async requestObject(requestObject = {}, { + sign: signingAlgorithm = this.request_object_signing_alg || 'none', + encrypt: { + alg: eKeyManagement = this.request_object_encryption_alg, + enc: eContentEncryption = this.request_object_encryption_enc || 'A128CBC-HS256', + } = {}, + } = {}) { + if (!isPlainObject(requestObject)) { + throw new TypeError('requestObject must be a plain object'); + } + let signed; + let key; - if (body === null) { - // body is null - dest.end(); - } else if (isBlob(body)) { - body.stream().pipe(dest); - } else if (Buffer.isBuffer(body)) { - // body is buffer - dest.write(body); - dest.end(); - } else { - // body is stream - body.pipe(dest); - } -} + const fapi = this.constructor.name === 'FAPIClient'; + const unix = now(); + const header = { alg: signingAlgorithm, typ: 'oauth-authz-req+jwt' }; + const payload = JSON.stringify(defaults({}, requestObject, { + iss: this.client_id, + aud: this.issuer.issuer, + client_id: this.client_id, + jti: random(), + iat: unix, + exp: unix + 300, + ...(fapi ? { nbf: unix } : undefined), + })); -// expose Promise -Body.Promise = global.Promise; + if (signingAlgorithm === 'none') { + signed = [ + base64url.encode(JSON.stringify(header)), + base64url.encode(payload), + '', + ].join('.'); + } else { + const symmetric = signingAlgorithm.startsWith('HS'); + if (symmetric) { + key = await this.joseSecret(); + } else { + const keystore = instance(this).get('keystore'); -/** - * headers.js - * - * Headers class offers convenient helpers - */ + if (!keystore) { + throw new TypeError(`no keystore present for client, cannot sign using alg ${signingAlgorithm}`); + } + key = keystore.get({ alg: signingAlgorithm, use: 'sig' }); + if (!key) { + throw new TypeError(`no key to sign with found for alg ${signingAlgorithm}`); + } + } -const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/; -const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/; + signed = jose.JWS.sign(payload, key, { + ...header, + kid: symmetric || key.kid.startsWith('DONOTUSE.') ? undefined : key.kid, + }); + } -function validateName(name) { - name = `${name}`; - if (invalidTokenRegex.test(name) || name === '') { - throw new TypeError(`${name} is not a legal HTTP header name`); - } -} + if (!eKeyManagement) { + return signed; + } -function validateValue(value) { - value = `${value}`; - if (invalidHeaderCharRegex.test(value)) { - throw new TypeError(`${value} is not a legal HTTP header value`); - } -} + const fields = { alg: eKeyManagement, enc: eContentEncryption, cty: 'oauth-authz-req+jwt' }; -/** - * Find the key in the map object given a header name. - * - * Returns undefined if not found. - * - * @param String name Header name - * @return String|Undefined - */ -function find(map, name) { - name = name.toLowerCase(); - for (const key in map) { - if (key.toLowerCase() === name) { - return key; - } - } - return undefined; -} + if (fields.alg.match(/^(RSA|ECDH)/)) { + [key] = await this.issuer.queryKeyStore({ + alg: fields.alg, + enc: fields.enc, + use: 'enc', + }, { allowMulti: true }); + } else { + key = await this.joseSecret(fields.alg === 'dir' ? fields.enc : fields.alg); + } -const MAP = Symbol('map'); -class Headers { - /** - * Headers class - * - * @param Object headers Response headers - * @return Void - */ - constructor() { - let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined; + return jose.JWE.encrypt(signed, key, { + ...fields, + kid: key.kty === 'oct' ? undefined : key.kid, + }); + } - this[MAP] = Object.create(null); + /** + * @name pushedAuthorizationRequest + * @api public + */ + async pushedAuthorizationRequest(params = {}, { clientAssertionPayload } = {}) { + assertIssuerConfiguration(this.issuer, 'pushed_authorization_request_endpoint'); - if (init instanceof Headers) { - const rawHeaders = init.raw(); - const headerNames = Object.keys(rawHeaders); + const body = { + ...('request' in params ? params : authorizationParams.call(this, params)), + client_id: this.client_id, + }; - for (const headerName of headerNames) { - for (const value of rawHeaders[headerName]) { - this.append(headerName, value); - } - } + const response = await authenticatedPost.call( + this, + 'pushed_authorization_request', + { + responseType: 'json', + form: body, + }, + { clientAssertionPayload, endpointAuthMethod: 'token' }, + ); + const responseBody = processResponse(response, { statusCode: 201 }); - return; - } + if (!('expires_in' in responseBody)) { + throw new RPError({ + message: 'expected expires_in in Pushed Authorization Successful Response', + response, + }); + } + if (typeof responseBody.expires_in !== 'number') { + throw new RPError({ + message: 'invalid expires_in value in Pushed Authorization Successful Response', + response, + }); + } + if (!('request_uri' in responseBody)) { + throw new RPError({ + message: 'expected request_uri in Pushed Authorization Successful Response', + response, + }); + } + if (typeof responseBody.request_uri !== 'string') { + throw new RPError({ + message: 'invalid request_uri value in Pushed Authorization Successful Response', + response, + }); + } - // We don't worry about converting prop to ByteString here as append() - // will handle it. - if (init == null) ; else if (typeof init === 'object') { - const method = init[Symbol.iterator]; - if (method != null) { - if (typeof method !== 'function') { - throw new TypeError('Header pairs must be iterable'); - } + return responseBody; + } - // 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'); - } - pairs.push(Array.from(pair)); - } + /** + * @name issuer + * @api public + */ + static get issuer() { + return issuer; + } - for (const pair of pairs) { - if (pair.length !== 2) { - throw new TypeError('Each header pair must be a name/value tuple'); - } - this.append(pair[0], pair[1]); - } - } else { - // record - for (const key of Object.keys(init)) { - const value = init[key]; - this.append(key, value); - } - } - } else { - throw new TypeError('Provided initializer must be an object'); - } - } + /** + * @name issuer + * @api public + */ + get issuer() { // eslint-disable-line class-methods-use-this + return issuer; + } - /** - * Return combined header value given name - * - * @param String name Header name - * @return Mixed - */ - get(name) { - name = `${name}`; - validateName(name); - const key = find(this[MAP], name); - if (key === undefined) { - return null; - } + /* istanbul ignore next */ + [inspect.custom]() { + return `${this.constructor.name} ${inspect(this.metadata, { + depth: Infinity, + colors: process.stdout.isTTY, + compact: false, + sorted: true, + })}`; + } +}; - return this[MAP][key].join(', '); - } +/** + * @name validateJARM + * @api private + */ +async function validateJARM(response) { + const expectedAlg = this.authorization_signed_response_alg; + const { payload } = await this.validateJWT(response, expectedAlg, ['iss', 'exp', 'aud']); + return pickCb(payload); +} - /** - * Iterate over all headers - * - * @param Function callback Executed for each item with parameters (value, name, thisArg) - * @param Boolean thisArg `this` context for callback function - * @return Void - */ - forEach(callback) { - let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; +Object.defineProperty(BaseClient.prototype, 'validateJARM', { + enumerable: true, + configurable: true, + value(...args) { + process.emitWarning( + "The JARM API implements an OIDF implementer's draft. Breaking draft implementations are included as minor versions of the openid-client library, therefore, the ~ semver operator should be used and close attention be payed to library changelog as well as the drafts themselves.", + 'DraftWarning', + ); + Object.defineProperty(BaseClient.prototype, 'validateJARM', { + enumerable: true, + configurable: true, + value: validateJARM, + }); + return this.validateJARM(...args); + }, +}); - let pairs = getHeaders(this); - let i = 0; - while (i < pairs.length) { - var _pairs$i = pairs[i]; - const name = _pairs$i[0], - value = _pairs$i[1]; +/** + * @name dpopProof + * @api private + */ +function dpopProof(payload, jwk, accessToken) { + if (!isPlainObject(payload)) { + throw new TypeError('payload must be a plain object'); + } - callback.call(thisArg, value, name, this); - pairs = getHeaders(this); - i++; - } - } + let key; + try { + key = jose.JWK.asKey(jwk); + assert(key.type === 'private'); + } catch (err) { + throw new TypeError('"DPoP" option must be an asymmetric private key to sign the DPoP Proof JWT with'); + } - /** - * Overwrite header values given name - * - * @param String name Header name - * @param String value Header value - * @return Void - */ - set(name, value) { - name = `${name}`; - value = `${value}`; - validateName(name); - validateValue(value); - const key = find(this[MAP], name); - this[MAP][key !== undefined ? key : name] = [value]; - } + let { alg } = key; - /** - * Append a value onto existing header - * - * @param String name Header name - * @param String value Header value - * @return Void - */ - 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]; - } - } + if (!alg && this.issuer.dpop_signing_alg_values_supported) { + const algs = key.algorithms('sign'); + alg = this.issuer.dpop_signing_alg_values_supported.find((a) => algs.has(a)); + } - /** - * Check for header name existence - * - * @param String name Header name - * @return Boolean - */ - has(name) { - name = `${name}`; - validateName(name); - return find(this[MAP], name) !== undefined; - } + if (!alg) { + [alg] = key.algorithms('sign'); + } - /** - * Delete all header values given name - * - * @param String name Header name - * @return Void - */ - delete(name) { - name = `${name}`; - validateName(name); - const key = find(this[MAP], name); - if (key !== undefined) { - delete this[MAP][key]; - } - } + return jose.JWS.sign({ + iat: now(), + jti: random(), + ath: accessToken ? base64url.encode(crypto.createHash('sha256').update(accessToken).digest()) : undefined, + ...payload, + }, jwk, { + alg, + typ: 'dpop+jwt', + jwk: pick(key, 'kty', 'crv', 'x', 'y', 'e', 'n'), + }); +} - /** - * Return raw headers (non-spec api) - * - * @return Object - */ - raw() { - return this[MAP]; - } +Object.defineProperty(BaseClient.prototype, 'dpopProof', { + enumerable: true, + configurable: true, + value(...args) { + process.emitWarning( + 'The DPoP APIs implements an IETF draft (https://www.ietf.org/archive/id/draft-ietf-oauth-dpop-03.html). Breaking draft implementations are included as minor versions of the openid-client library, therefore, the ~ semver operator should be used and close attention be payed to library changelog as well as the drafts themselves.', + 'DraftWarning', + ); + Object.defineProperty(BaseClient.prototype, 'dpopProof', { + enumerable: true, + configurable: true, + value: dpopProof, + }); + return this.dpopProof(...args); + }, +}); - /** - * Get an iterator on keys. - * - * @return Iterator - */ - keys() { - return createHeadersIterator(this, 'key'); - } +module.exports.BaseClient = BaseClient; - /** - * Get an iterator on values. - * - * @return Iterator - */ - values() { - return createHeadersIterator(this, 'value'); - } - /** - * Get an iterator on entries. - * - * This is the default iterator of the Headers object. - * - * @return Iterator - */ - [Symbol.iterator]() { - return createHeadersIterator(this, 'key+value'); - } -} -Headers.prototype.entries = Headers.prototype[Symbol.iterator]; +/***/ }), -Object.defineProperty(Headers.prototype, Symbol.toStringTag, { - value: 'Headers', - writable: false, - enumerable: false, - configurable: true -}); +/***/ 23979: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -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 } -}); +/* eslint-disable camelcase */ +const { inspect } = __nccwpck_require__(73837); -function getHeaders(headers) { - let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; +const { RPError, OPError } = __nccwpck_require__(45061); +const instance = __nccwpck_require__(27702); +const now = __nccwpck_require__(8542); +const { authenticatedPost } = __nccwpck_require__(7619); +const processResponse = __nccwpck_require__(28576); +const TokenSet = __nccwpck_require__(39029); - const keys = Object.keys(headers[MAP]).sort(); - return keys.map(kind === 'key' ? function (k) { - return k.toLowerCase(); - } : kind === 'value' ? function (k) { - return headers[MAP][k].join(', '); - } : function (k) { - return [k.toLowerCase(), headers[MAP][k].join(', ')]; - }); -} +class DeviceFlowHandle { + constructor({ + client, exchangeBody, clientAssertionPayload, response, maxAge, DPoP, + }) { + ['verification_uri', 'user_code', 'device_code'].forEach((prop) => { + if (typeof response[prop] !== 'string' || !response[prop]) { + throw new RPError(`expected ${prop} string to be returned by Device Authorization Response, got %j`, response[prop]); + } + }); -const INTERNAL = Symbol('internal'); + if (!Number.isSafeInteger(response.expires_in)) { + throw new RPError('expected expires_in number to be returned by Device Authorization Response, got %j', response.expires_in); + } -function createHeadersIterator(target, kind) { - const iterator = Object.create(HeadersIteratorPrototype); - iterator[INTERNAL] = { - target, - kind, - index: 0 - }; - return iterator; -} + instance(this).expires_at = now() + response.expires_in; + instance(this).client = client; + instance(this).DPoP = DPoP; + instance(this).maxAge = maxAge; + instance(this).exchangeBody = exchangeBody; + instance(this).clientAssertionPayload = clientAssertionPayload; + instance(this).response = response; + instance(this).interval = response.interval * 1000 || 5000; + } -const HeadersIteratorPrototype = Object.setPrototypeOf({ - next() { - // istanbul ignore if - if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { - throw new TypeError('Value of `this` is not a HeadersIterator'); - } + abort() { + instance(this).aborted = true; + } - var _INTERNAL = this[INTERNAL]; - const target = _INTERNAL.target, - kind = _INTERNAL.kind, - index = _INTERNAL.index; + async poll({ signal } = {}) { + if ((signal && signal.aborted) || instance(this).aborted) { + throw new RPError('polling aborted'); + } - const values = getHeaders(target, kind); - const len = values.length; - if (index >= len) { - return { - value: undefined, - done: true - }; - } + if (this.expired()) { + throw new RPError('the device code %j has expired and the device authorization session has concluded', this.device_code); + } - this[INTERNAL].index = index + 1; + await new Promise((resolve) => setTimeout(resolve, instance(this).interval)); - return { - value: values[index], - done: false - }; - } -}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + const response = await authenticatedPost.call( + instance(this).client, + 'token', + { + form: { + ...instance(this).exchangeBody, + grant_type: 'urn:ietf:params:oauth:grant-type:device_code', + device_code: this.device_code, + }, + responseType: 'json', + }, + { clientAssertionPayload: instance(this).clientAssertionPayload, DPoP: instance(this).DPoP }, + ); -Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { - value: 'HeadersIterator', - writable: false, - enumerable: false, - configurable: true -}); + let responseBody; + try { + responseBody = processResponse(response); + } catch (err) { + switch (err instanceof OPError && err.error) { + case 'slow_down': + instance(this).interval += 5000; + case 'authorization_pending': // eslint-disable-line no-fallthrough + return this.poll({ signal }); + default: + throw err; + } + } -/** - * Export the Headers object in a form that Node.js can consume. - * - * @param Headers headers - * @return Object - */ -function exportNodeCompatibleHeaders(headers) { - const obj = Object.assign({ __proto__: null }, headers[MAP]); + const tokenset = new TokenSet(responseBody); - // 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]; - } + if ('id_token' in tokenset) { + await instance(this).client.decryptIdToken(tokenset); + await instance(this).client.validateIdToken(tokenset, undefined, 'token', instance(this).maxAge); + } + + return tokenset; + } - return obj; -} + get device_code() { + return instance(this).response.device_code; + } -/** - * Create a Headers object from an object of headers, ignoring those that do - * not conform to HTTP grammar productions. - * - * @param Object obj Object of headers - * @return Headers - */ -function createHeadersLenient(obj) { - const headers = new Headers(); - for (const name of Object.keys(obj)) { - if (invalidTokenRegex.test(name)) { - continue; - } - if (Array.isArray(obj[name])) { - for (const val of obj[name]) { - if (invalidHeaderCharRegex.test(val)) { - continue; - } - 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; -} + get user_code() { + return instance(this).response.user_code; + } -const INTERNALS$1 = Symbol('Response internals'); + get verification_uri() { + return instance(this).response.verification_uri; + } -// fix an issue where "STATUS_CODES" aren't a named export for node <10 -const STATUS_CODES = http.STATUS_CODES; + get verification_uri_complete() { + return instance(this).response.verification_uri_complete; + } -/** - * Response class - * - * @param Stream body Readable stream - * @param Object opts Response options - * @return Void - */ -class Response { - constructor() { - let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; - let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + get expires_in() { + return Math.max.apply(null, [instance(this).expires_at - now(), 0]); + } - Body.call(this, body, opts); + expired() { + return this.expires_in === 0; + } - const status = opts.status || 200; - const headers = new Headers(opts.headers); + /* istanbul ignore next */ + [inspect.custom]() { + return `${this.constructor.name} ${inspect(instance(this).response, { + depth: Infinity, + colors: process.stdout.isTTY, + compact: false, + sorted: true, + })}`; + } +} - if (body != null && !headers.has('Content-Type')) { - const contentType = extractContentType(body); - if (contentType) { - headers.append('Content-Type', contentType); - } - } +module.exports = DeviceFlowHandle; - this[INTERNALS$1] = { - url: opts.url, - status, - statusText: opts.statusText || STATUS_CODES[status], - headers, - counter: opts.counter - }; - } - get url() { - return this[INTERNALS$1].url || ''; - } +/***/ }), - get status() { - return this[INTERNALS$1].status; - } +/***/ 45061: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * Convenience property representing if the request ended normally - */ - get ok() { - return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; - } +/* eslint-disable camelcase */ +const { format } = __nccwpck_require__(73837); - get redirected() { - return this[INTERNALS$1].counter > 0; - } +const makeError = __nccwpck_require__(21381); - get statusText() { - return this[INTERNALS$1].statusText; - } +function OPError({ + error_description, + error, + error_uri, + session_state, + state, + scope, +}, response) { + OPError.super.call(this, !error_description ? error : `${error} (${error_description})`); - get headers() { - return this[INTERNALS$1].headers; - } + Object.assign( + this, + { error }, + (error_description && { error_description }), + (error_uri && { error_uri }), + (state && { state }), + (scope && { scope }), + (session_state && { session_state }), + ); - /** - * Clone this response - * - * @return Response - */ - clone() { - return new Response(clone(this), { - url: this.url, - status: this.status, - statusText: this.statusText, - headers: this.headers, - ok: this.ok, - redirected: this.redirected - }); - } + if (response) { + Object.defineProperty(this, 'response', { + value: response, + }); + } } -Body.mixIn(Response.prototype); +makeError(OPError); -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 } -}); +function RPError(...args) { + if (typeof args[0] === 'string') { + RPError.super.call(this, format(...args)); + } else { + const { + message, printf, response, ...rest + } = args[0]; + if (printf) { + RPError.super.call(this, format(...printf)); + } else { + RPError.super.call(this, message); + } + Object.assign(this, rest); + if (response) { + Object.defineProperty(this, 'response', { + value: response, + }); + } + } +} -Object.defineProperty(Response.prototype, Symbol.toStringTag, { - value: 'Response', - writable: false, - enumerable: false, - configurable: true -}); +makeError(RPError); -const INTERNALS$2 = Symbol('Request internals'); -const URL = Url.URL || whatwgUrl.URL; +module.exports = { + OPError, + RPError, +}; -// fix an issue where "format", "parse" aren't a named export for node <10 -const parse_url = Url.parse; -const format_url = Url.format; -/** - * Wrapper around `new URL` to handle arbitrary URLs - * - * @param {string} urlStr - * @return {void} - */ -function parseURL(urlStr) { - /* - Check whether the URL is absolute or not - Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 - Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 - */ - if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { - urlStr = new URL(urlStr).toString(); - } +/***/ }), - // Fallback to old implementation for arbitrary URLs - return parse_url(urlStr); -} +/***/ 63217: +/***/ ((module) => { -const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; +function assertSigningAlgValuesSupport(endpoint, issuer, properties) { + if (!issuer[`${endpoint}_endpoint`]) return; -/** - * Check if a value is an instance of Request. - * - * @param Mixed input - * @return Boolean - */ -function isRequest(input) { - return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; + const eam = `${endpoint}_endpoint_auth_method`; + const easa = `${endpoint}_endpoint_auth_signing_alg`; + const easavs = `${endpoint}_endpoint_auth_signing_alg_values_supported`; + + if (properties[eam] && properties[eam].endsWith('_jwt') && !properties[easa] && !issuer[easavs]) { + throw new TypeError(`${easavs} must be configured on the issuer if ${easa} is not defined on a client`); + } } -function isAbortSignal(signal) { - const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); - return !!(proto && proto.constructor.name === 'AbortSignal'); +function assertIssuerConfiguration(issuer, endpoint) { + if (!issuer[endpoint]) { + throw new TypeError(`${endpoint} must be configured on the issuer`); + } } -/** - * Request class - * - * @param Mixed input Url or Request instance - * @param Object init Custom options - * @return Void - */ -class Request { - constructor(input) { - let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; +module.exports = { + assertSigningAlgValuesSupport, + assertIssuerConfiguration, +}; - let parsedURL; - // normalize input - if (!isRequest(input)) { - if (input && input.href) { - // in order to support Node.js' Url objects; though WHATWG's URL objects - // will fall into this branch also (since their `toString()` will return - // `href` property anyway) - parsedURL = parseURL(input.href); - } else { - // coerce input to a string before attempting to parse - parsedURL = parseURL(`${input}`); - } - input = {}; - } else { - parsedURL = parseURL(input.url); - } +/***/ }), - let method = init.method || input.method || 'GET'; - method = method.toUpperCase(); +/***/ 61827: +/***/ ((module) => { - if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { - throw new TypeError('Request with GET/HEAD method cannot have body'); - } +let encode; +if (Buffer.isEncoding('base64url')) { + encode = (input, encoding = 'utf8') => Buffer.from(input, encoding).toString('base64url'); +} else { + const fromBase64 = (base64) => base64.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); + encode = (input, encoding = 'utf8') => fromBase64(Buffer.from(input, encoding).toString('base64')); +} - let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; +const decode = (input) => Buffer.from(input, 'base64'); - Body.call(this, inputBody, { - timeout: init.timeout || input.timeout || 0, - size: init.size || input.size || 0 - }); +module.exports.decode = decode; +module.exports.encode = encode; - const headers = new Headers(init.headers || input.headers || {}); - if (inputBody != null && !headers.has('Content-Type')) { - const contentType = extractContentType(inputBody); - if (contentType) { - headers.append('Content-Type', contentType); - } - } +/***/ }), - let signal = isRequest(input) ? input.signal : null; - if ('signal' in init) signal = init.signal; +/***/ 7619: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (signal != null && !isAbortSignal(signal)) { - throw new TypeError('Expected signal to be an instanceof AbortSignal'); - } +const jose = __nccwpck_require__(16425); - this[INTERNALS$2] = { - method, - redirect: init.redirect || input.redirect || 'follow', - headers, - parsedURL, - signal - }; +const { assertIssuerConfiguration } = __nccwpck_require__(63217); +const { random } = __nccwpck_require__(75421); +const now = __nccwpck_require__(8542); +const request = __nccwpck_require__(92946); +const instance = __nccwpck_require__(27702); +const merge = __nccwpck_require__(2494); - // 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; - } +const formUrlEncode = (value) => encodeURIComponent(value).replace(/%20/g, '+'); - get method() { - return this[INTERNALS$2].method; - } +async function clientAssertion(endpoint, payload) { + let alg = this[`${endpoint}_endpoint_auth_signing_alg`]; + if (!alg) { + assertIssuerConfiguration(this.issuer, `${endpoint}_endpoint_auth_signing_alg_values_supported`); + } - get url() { - return format_url(this[INTERNALS$2].parsedURL); - } + if (this[`${endpoint}_endpoint_auth_method`] === 'client_secret_jwt') { + const key = await this.joseSecret(); - get headers() { - return this[INTERNALS$2].headers; - } + if (!alg) { + const supported = this.issuer[`${endpoint}_endpoint_auth_signing_alg_values_supported`]; + alg = Array.isArray(supported) && supported.find((signAlg) => key.algorithms('sign').has(signAlg)); + } - get redirect() { - return this[INTERNALS$2].redirect; - } + return jose.JWS.sign(payload, key, { alg, typ: 'JWT' }); + } - get signal() { - return this[INTERNALS$2].signal; - } + const keystore = instance(this).get('keystore'); - /** - * Clone this request - * - * @return Request - */ - clone() { - return new Request(this); - } -} + if (!keystore) { + throw new TypeError('no client jwks provided for signing a client assertion with'); + } -Body.mixIn(Request.prototype); + if (!alg) { + const algs = new Set(); -Object.defineProperty(Request.prototype, Symbol.toStringTag, { - value: 'Request', - writable: false, - enumerable: false, - configurable: true -}); + keystore.all().forEach((key) => { + key.algorithms('sign').forEach(Set.prototype.add.bind(algs)); + }); -Object.defineProperties(Request.prototype, { - method: { enumerable: true }, - url: { enumerable: true }, - headers: { enumerable: true }, - redirect: { enumerable: true }, - clone: { enumerable: true }, - signal: { enumerable: true } -}); + const supported = this.issuer[`${endpoint}_endpoint_auth_signing_alg_values_supported`]; + alg = Array.isArray(supported) && supported.find((signAlg) => algs.has(signAlg)); + } -/** - * Convert a Request to Node.js http request options. - * - * @param Request A Request instance - * @return Object The options object to be passed to http.request - */ -function getNodeRequestOptions(request) { - const parsedURL = request[INTERNALS$2].parsedURL; - const headers = new Headers(request[INTERNALS$2].headers); + const key = keystore.get({ alg, use: 'sig' }); + if (!key) { + throw new TypeError(`no key found in client jwks to sign a client assertion with using alg ${alg}`); + } + return jose.JWS.sign(payload, key, { alg, typ: 'JWT', kid: key.kid.startsWith('DONOTUSE.') ? undefined : key.kid }); +} - // fetch step 1.3 - if (!headers.has('Accept')) { - headers.set('Accept', '*/*'); - } +async function authFor(endpoint, { clientAssertionPayload } = {}) { + const authMethod = this[`${endpoint}_endpoint_auth_method`]; + switch (authMethod) { + case 'self_signed_tls_client_auth': + case 'tls_client_auth': + case 'none': + return { form: { client_id: this.client_id } }; + case 'client_secret_post': + if (!this.client_secret) { + throw new TypeError('client_secret_post client authentication method requires a client_secret'); + } + return { form: { client_id: this.client_id, client_secret: this.client_secret } }; + case 'private_key_jwt': + case 'client_secret_jwt': { + const timestamp = now(); - // Basic fetch - if (!parsedURL.protocol || !parsedURL.hostname) { - throw new TypeError('Only absolute URLs are supported'); - } + const mTLS = endpoint === 'token' && this.tls_client_certificate_bound_access_tokens; + const audience = [...new Set([ + this.issuer.issuer, + this.issuer.token_endpoint, + this.issuer[`${endpoint}_endpoint`], + mTLS && this.issuer.mtls_endpoint_aliases + ? this.issuer.mtls_endpoint_aliases.token_endpoint : undefined, + ].filter(Boolean))]; - if (!/^https?:$/.test(parsedURL.protocol)) { - throw new TypeError('Only HTTP(S) protocols are supported'); - } + const assertion = await clientAssertion.call(this, endpoint, { + iat: timestamp, + exp: timestamp + 60, + jti: random(), + iss: this.client_id, + sub: this.client_id, + aud: audience, + ...clientAssertionPayload, + }); - if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { - throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); - } + return { + form: { + client_id: this.client_id, + client_assertion: assertion, + client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer', + }, + }; + } + default: { // client_secret_basic + // This is correct behaviour, see https://tools.ietf.org/html/rfc6749#section-2.3.1 and the + // related appendix. (also https://github.com/panva/node-openid-client/pull/91) + // > The client identifier is encoded using the + // > "application/x-www-form-urlencoded" encoding algorithm per + // > Appendix B, and the encoded value is used as the username; the client + // > password is encoded using the same algorithm and used as the + // > password. + if (!this.client_secret) { + throw new TypeError('client_secret_basic client authentication method requires a client_secret'); + } + const encoded = `${formUrlEncode(this.client_id)}:${formUrlEncode(this.client_secret)}`; + const value = Buffer.from(encoded).toString('base64'); + return { headers: { Authorization: `Basic ${value}` } }; + } + } +} - // HTTP-network-or-cache fetch steps 2.4-2.7 - let contentLengthValue = null; - if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { - contentLengthValue = '0'; - } - if (request.body != null) { - const totalBytes = getTotalBytes(request); - if (typeof totalBytes === 'number') { - contentLengthValue = String(totalBytes); - } - } - if (contentLengthValue) { - headers.set('Content-Length', contentLengthValue); - } +function resolveResponseType() { + const { length, 0: value } = this.response_types; - // HTTP-network-or-cache fetch step 2.11 - if (!headers.has('User-Agent')) { - headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); - } + if (length === 1) { + return value; + } - // HTTP-network-or-cache fetch step 2.15 - if (request.compress && !headers.has('Accept-Encoding')) { - headers.set('Accept-Encoding', 'gzip,deflate'); - } + return undefined; +} - let agent = request.agent; - if (typeof agent === 'function') { - agent = agent(parsedURL); - } +function resolveRedirectUri() { + const { length, 0: value } = this.redirect_uris || []; - // HTTP-network fetch step 4.2 - // chunked encoding is handled by Node.js + if (length === 1) { + return value; + } - return Object.assign({}, parsedURL, { - method: request.method, - headers: exportNodeCompatibleHeaders(headers), - agent - }); + return undefined; } -/** - * abort-error.js - * - * AbortError interface for cancelled requests - */ +async function authenticatedPost(endpoint, opts, { + clientAssertionPayload, endpointAuthMethod = endpoint, DPoP, +} = {}) { + const auth = await authFor.call(this, endpointAuthMethod, { clientAssertionPayload }); + const requestOpts = merge(opts, auth); -/** - * Create AbortError instance - * - * @param String message Error message for human - * @return AbortError - */ -function AbortError(message) { - Error.call(this, message); + const mTLS = this[`${endpointAuthMethod}_endpoint_auth_method`].includes('tls_client_auth') + || (endpoint === 'token' && this.tls_client_certificate_bound_access_tokens); - this.type = 'aborted'; - this.message = message; + let targetUrl; + if (mTLS && this.issuer.mtls_endpoint_aliases) { + targetUrl = this.issuer.mtls_endpoint_aliases[`${endpoint}_endpoint`]; + } - // hide custom error implementation details from end-users - Error.captureStackTrace(this, this.constructor); + targetUrl = targetUrl || this.issuer[`${endpoint}_endpoint`]; + + if ('form' in requestOpts) { + for (const [key, value] of Object.entries(requestOpts.form)) { // eslint-disable-line no-restricted-syntax, max-len + if (typeof value === 'undefined') { + delete requestOpts.form[key]; + } + } + } + + return request.call(this, { + ...requestOpts, + method: 'POST', + url: targetUrl, + }, { mTLS, DPoP }); } -AbortError.prototype = Object.create(Error.prototype); -AbortError.prototype.constructor = AbortError; -AbortError.prototype.name = 'AbortError'; +module.exports = { + resolveResponseType, + resolveRedirectUri, + authFor, + authenticatedPost, +}; -const URL$1 = Url.URL || whatwgUrl.URL; -// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 -const PassThrough$1 = Stream.PassThrough; +/***/ }), -const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { - const orig = new URL$1(original).hostname; - const dest = new URL$1(destination).hostname; +/***/ 27556: +/***/ ((module) => { - return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); +const OIDC_DISCOVERY = '/.well-known/openid-configuration'; +const OAUTH2_DISCOVERY = '/.well-known/oauth-authorization-server'; +const WEBFINGER = '/.well-known/webfinger'; +const REL = 'http://openid.net/specs/connect/1.0/issuer'; +const AAD_MULTITENANT_DISCOVERY = [ + `https://login.microsoftonline.com/common${OIDC_DISCOVERY}`, + `https://login.microsoftonline.com/common/v2.0${OIDC_DISCOVERY}`, + `https://login.microsoftonline.com/organizations/v2.0${OIDC_DISCOVERY}`, + `https://login.microsoftonline.com/consumers/v2.0${OIDC_DISCOVERY}`, +]; + +const CLIENT_DEFAULTS = { + grant_types: ['authorization_code'], + id_token_signed_response_alg: 'RS256', + authorization_signed_response_alg: 'RS256', + response_types: ['code'], + token_endpoint_auth_method: 'client_secret_basic', }; -/** - * isSameProtocol reports whether the two provided URLs use the same protocol. - * - * Both domains must already be in canonical form. - * @param {string|URL} original - * @param {string|URL} destination - */ -const isSameProtocol = function isSameProtocol(destination, original) { - const orig = new URL$1(original).protocol; - const dest = new URL$1(destination).protocol; +const ISSUER_DEFAULTS = { + claim_types_supported: ['normal'], + claims_parameter_supported: false, + grant_types_supported: ['authorization_code', 'implicit'], + request_parameter_supported: false, + request_uri_parameter_supported: true, + require_request_uri_registration: false, + response_modes_supported: ['query', 'fragment'], + token_endpoint_auth_methods_supported: ['client_secret_basic'], +}; - return orig === dest; +const CALLBACK_PROPERTIES = [ + 'access_token', // 6749 + 'code', // 6749 + 'error', // 6749 + 'error_description', // 6749 + 'error_uri', // 6749 + 'expires_in', // 6749 + 'id_token', // Core 1.0 + 'state', // 6749 + 'token_type', // 6749 + 'session_state', // Session Management + 'response', // JARM +]; + +const JWT_CONTENT = /^application\/jwt/; + +const HTTP_OPTIONS = Symbol('openid-client.custom.http-options'); +const CLOCK_TOLERANCE = Symbol('openid-client.custom.clock-tolerance'); + +module.exports = { + AAD_MULTITENANT_DISCOVERY, + CALLBACK_PROPERTIES, + CLIENT_DEFAULTS, + CLOCK_TOLERANCE, + HTTP_OPTIONS, + ISSUER_DEFAULTS, + JWT_CONTENT, + OAUTH2_DISCOVERY, + OIDC_DISCOVERY, + REL, + WEBFINGER, }; -/** - * Fetch function - * - * @param Mixed url Absolute url or Request instance - * @param Object opts Fetch options - * @return Promise - */ -function fetch(url, opts) { - // allow custom promise - if (!fetch.Promise) { - throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); - } +/***/ }), - Body.Promise = fetch.Promise; +/***/ 21004: +/***/ ((module) => { - // wrap http.request into fetch - return new fetch.Promise(function (resolve, reject) { - // build request object - const request = new Request(url, opts); - const options = getNodeRequestOptions(request); +module.exports = (obj) => JSON.parse(JSON.stringify(obj)); - const send = (options.protocol === 'https:' ? https : http).request; - const signal = request.signal; - let response = null; +/***/ }), - const abort = function abort() { - let error = new AbortError('The user aborted a request.'); - reject(error); - if (request.body && request.body instanceof Stream.Readable) { - destroyStream(request.body, error); - } - if (!response || !response.body) return; - response.body.emit('error', error); - }; +/***/ 13098: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (signal && signal.aborted) { - abort(); - return; - } +/* eslint-disable no-restricted-syntax, no-continue */ - const abortAndFinalize = function abortAndFinalize() { - abort(); - finalize(); - }; +const isPlainObject = __nccwpck_require__(39862); - // send request - const req = send(options); - let reqTimeout; +function defaults(deep, target, ...sources) { + for (const source of sources) { + if (!isPlainObject(source)) { + continue; + } + for (const [key, value] of Object.entries(source)) { + /* istanbul ignore if */ + if (key === '__proto__' || key === 'constructor') { + continue; + } + if (typeof target[key] === 'undefined' && typeof value !== 'undefined') { + target[key] = value; + } - if (signal) { - signal.addEventListener('abort', abortAndFinalize); - } + if (deep && isPlainObject(target[key]) && isPlainObject(value)) { + defaults(true, target[key], value); + } + } + } - function finalize() { - req.abort(); - if (signal) signal.removeEventListener('abort', abortAndFinalize); - clearTimeout(reqTimeout); - } + return target; +} - if (request.timeout) { - req.once('socket', function (socket) { - reqTimeout = setTimeout(function () { - reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); - finalize(); - }, request.timeout); - }); - } +module.exports = defaults.bind(undefined, false); +module.exports.deep = defaults.bind(undefined, true); - req.on('error', function (err) { - reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); - if (response && response.body) { - destroyStream(response.body, err); - } +/***/ }), - finalize(); - }); +/***/ 75421: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - fixResponseChunkedTransferBadEnding(req, function (err) { - if (signal && signal.aborted) { - return; - } +const { createHash, randomBytes } = __nccwpck_require__(6113); - if (response && response.body) { - destroyStream(response.body, err); - } - }); +const base64url = __nccwpck_require__(61827); - /* c8 ignore next 18 */ - if (parseInt(process.version.substring(1)) < 14) { - // Before Node.js 14, pipeline() does not fully support async iterators and does not always - // properly handle when the socket close/end events are out of order. - req.on('socket', function (s) { - s.addListener('close', function (hadError) { - // if a data listener is still present we didn't end cleanly - const hasDataListener = s.listenerCount('data') > 0; +const random = (bytes = 32) => base64url.encode(randomBytes(bytes)); - // if end happened before close but the socket didn't emit an error, do it now - if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { - const err = new Error('Premature close'); - err.code = 'ERR_STREAM_PREMATURE_CLOSE'; - response.body.emit('error', err); - } - }); - }); - } +module.exports = { + random, + state: random, + nonce: random, + codeVerifier: random, + codeChallenge: (codeVerifier) => base64url.encode(createHash('sha256').update(codeVerifier).digest()), +}; - req.on('response', function (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'); +/***/ 61797: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // HTTP fetch step 5.3 - let locationURL = null; - try { - locationURL = location === null ? null : new URL$1(location, request.url).toString(); - } catch (err) { - // 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') { - reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); - finalize(); - return; - } - } +const url = __nccwpck_require__(57310); +const { strict: assert } = __nccwpck_require__(39491); - // HTTP fetch step 5.5 - switch (request.redirect) { - case 'error': - reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); - finalize(); - return; - case '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); - } - } - break; - case 'follow': - // HTTP-redirect fetch step 2 - if (locationURL === null) { - break; - } +module.exports = (target) => { + try { + const { protocol } = new url.URL(target); + assert(protocol.match(/^(https?:)$/)); + return true; + } catch (err) { + throw new TypeError('only valid absolute URLs can be requested'); + } +}; - // HTTP-redirect fetch step 5 - if (request.counter >= request.follow) { - reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); - finalize(); - return; - } - // 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, - size: request.size - }; +/***/ }), - if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { - for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { - requestOpts.headers.delete(name); - } - } +/***/ 39862: +/***/ ((module) => { - // 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; - } +module.exports = (a) => !!a && a.constructor === Object; - // 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'); - } - // HTTP-redirect fetch step 15 - resolve(fetch(new Request(locationURL, requestOpts))); - finalize(); - return; - } - } +/***/ }), - // prepare response - res.once('end', function () { - if (signal) signal.removeEventListener('abort', abortAndFinalize); - }); - let body = res.pipe(new PassThrough$1()); +/***/ 2494: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const response_options = { - url: request.url, - status: res.statusCode, - statusText: res.statusMessage, - headers: headers, - size: request.size, - timeout: request.timeout, - counter: request.counter - }; +/* eslint-disable no-restricted-syntax, no-param-reassign, no-continue */ - // HTTP-network fetch step 12.1.1.3 - const codings = headers.get('Content-Encoding'); +const isPlainObject = __nccwpck_require__(39862); - // HTTP-network fetch step 12.1.1.4: handle content codings +function merge(target, ...sources) { + for (const source of sources) { + if (!isPlainObject(source)) { + continue; + } + for (const [key, value] of Object.entries(source)) { + /* istanbul ignore if */ + if (key === '__proto__' || key === 'constructor') { + continue; + } + if (isPlainObject(target[key]) && isPlainObject(value)) { + target[key] = merge(target[key], value); + } else if (typeof value !== 'undefined') { + target[key] = value; + } + } + } - // 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, response_options); - resolve(response); - return; - } + return target; +} - // For Node v6+ - // 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.Z_SYNC_FLUSH, - finishFlush: zlib.Z_SYNC_FLUSH - }; +module.exports = merge; - // for gzip - if (codings == 'gzip' || codings == 'x-gzip') { - body = body.pipe(zlib.createGunzip(zlibOptions)); - response = new Response(body, response_options); - 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 PassThrough$1()); - raw.once('data', function (chunk) { - // see http://stackoverflow.com/questions/37519828 - if ((chunk[0] & 0x0F) === 0x08) { - body = body.pipe(zlib.createInflate()); - } else { - body = body.pipe(zlib.createInflateRaw()); - } - response = new Response(body, response_options); - resolve(response); - }); - raw.on('end', function () { - // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. - if (!response) { - response = new Response(body, response_options); - resolve(response); - } - }); - return; - } +/***/ }), - // for br - if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { - body = body.pipe(zlib.createBrotliDecompress()); - response = new Response(body, response_options); - resolve(response); - return; - } +/***/ 78857: +/***/ ((module) => { - // otherwise, use response as-is - response = new Response(body, response_options); - resolve(response); - }); +module.exports = function pick(object, ...paths) { + const obj = {}; + for (const path of paths) { // eslint-disable-line no-restricted-syntax + if (object[path]) { + obj[path] = object[path]; + } + } + return obj; +}; - writeToStream(req, request); - }); -} -function fixResponseChunkedTransferBadEnding(request, errorCallback) { - let socket; - request.on('socket', function (s) { - socket = s; - }); +/***/ }), + +/***/ 28576: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const { STATUS_CODES } = __nccwpck_require__(13685); +const { format } = __nccwpck_require__(73837); + +const { OPError } = __nccwpck_require__(45061); + +const REGEXP = /(\w+)=("[^"]*")/g; +const throwAuthenticateErrors = (response) => { + const params = {}; + try { + while ((REGEXP.exec(response.headers['www-authenticate'])) !== null) { + if (RegExp.$1 && RegExp.$2) { + params[RegExp.$1] = RegExp.$2.slice(1, -1); + } + } + } catch (err) {} + + if (params.error) { + throw new OPError(params, response); + } +}; + +const isStandardBodyError = (response) => { + let result = false; + try { + let jsonbody; + if (typeof response.body !== 'object' || Buffer.isBuffer(response.body)) { + jsonbody = JSON.parse(response.body); + } else { + jsonbody = response.body; + } + result = typeof jsonbody.error === 'string' && jsonbody.error.length; + if (result) response.body = jsonbody; + } catch (err) {} - request.on('response', function (response) { - const headers = response.headers; + return result; +}; - if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { - response.once('close', function (hadError) { - // tests for socket presence, as in some situations the - // the 'socket' event is not triggered for the request - // (happens in deno), avoids `TypeError` - // if a data listener is still present we didn't end cleanly - const hasDataListener = socket && socket.listenerCount('data') > 0; +function processResponse(response, { statusCode = 200, body = true, bearer = false } = {}) { + if (response.statusCode !== statusCode) { + if (bearer) { + throwAuthenticateErrors(response); + } - if (hasDataListener && !hadError) { - const err = new Error('Premature close'); - err.code = 'ERR_STREAM_PREMATURE_CLOSE'; - errorCallback(err); - } - }); - } - }); -} + if (isStandardBodyError(response)) { + throw new OPError(response.body, response); + } -function destroyStream(stream, err) { - if (stream.destroy) { - stream.destroy(err); - } else { - // node < 8 - stream.emit('error', err); - stream.end(); - } -} + throw new OPError({ + error: format('expected %i %s, got: %i %s', statusCode, STATUS_CODES[statusCode], response.statusCode, STATUS_CODES[response.statusCode]), + }, response); + } -/** - * Redirect code matching - * - * @param Number code Status code - * @return Boolean - */ -fetch.isRedirect = function (code) { - return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; -}; + if (body && !response.body) { + throw new OPError({ + error: format('expected %i %s with body but no body was returned', statusCode, STATUS_CODES[statusCode]), + }, response); + } -// expose Promise -fetch.Promise = global.Promise; + return response.body; +} -module.exports = exports = fetch; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = exports; -exports.Headers = Headers; -exports.Request = Request; -exports.Response = Response; -exports.FetchError = FetchError; -exports.AbortError = AbortError; +module.exports = processResponse; /***/ }), -/***/ 20502: +/***/ 92946: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - -const path = __nccwpck_require__(71017); -const pathKey = __nccwpck_require__(20539); - -const npmRunPath = options => { - options = { - cwd: process.cwd(), - path: process.env[pathKey()], - execPath: process.execPath, - ...options - }; +const Got = __nccwpck_require__(93061); - let previous; - let cwdPath = path.resolve(options.cwd); - const result = []; +const pkg = __nccwpck_require__(82696); - while (previous !== cwdPath) { - result.push(path.join(cwdPath, 'node_modules/.bin')); - previous = cwdPath; - cwdPath = path.resolve(cwdPath, '..'); - } +const { deep: defaultsDeep } = __nccwpck_require__(13098); +const isAbsoluteUrl = __nccwpck_require__(61797); +const { HTTP_OPTIONS } = __nccwpck_require__(27556); - // Ensure the running `node` binary is used - const execPathDir = path.resolve(options.cwd, options.execPath, '..'); - result.push(execPathDir); +let DEFAULT_HTTP_OPTIONS; +let got; - return result.concat(options.path).join(path.delimiter); +const setDefaults = (options) => { + DEFAULT_HTTP_OPTIONS = defaultsDeep({}, options, DEFAULT_HTTP_OPTIONS); + got = Got.extend(DEFAULT_HTTP_OPTIONS); }; -module.exports = npmRunPath; -// TODO: Remove this for the next major release -module.exports["default"] = npmRunPath; +setDefaults({ + followRedirect: false, + headers: { 'User-Agent': `${pkg.name}/${pkg.version} (${pkg.homepage})` }, + retry: 0, + timeout: 3500, + throwHttpErrors: false, +}); -module.exports.env = options => { - options = { - env: process.env, - ...options - }; +module.exports = async function request(options, { accessToken, mTLS = false, DPoP } = {}) { + const { url } = options; + isAbsoluteUrl(url); + const optsFn = this[HTTP_OPTIONS]; + let opts = options; - const env = {...options.env}; - const path = pathKey({env}); + if (DPoP && 'dpopProof' in this) { + opts.headers = opts.headers || {}; + opts.headers.DPoP = this.dpopProof({ + htu: url, + htm: options.method, + }, DPoP, accessToken); + } - options.path = env[path]; - env[path] = module.exports(options); + if (optsFn) { + opts = optsFn.call(this, defaultsDeep({}, opts, DEFAULT_HTTP_OPTIONS)); + } - return env; + if ( + mTLS + && ( + (!opts.key || !opts.cert) + && (!opts.https || !((opts.https.key && opts.https.certificate) || opts.https.pfx)) + ) + ) { + throw new TypeError('mutual-TLS certificate and key not set'); + } + + return got(opts); }; +module.exports.setDefaults = setDefaults; -/***/ }), -/***/ 43248: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ }), -var crypto = __nccwpck_require__(6113) +/***/ 8542: +/***/ ((module) => { -function sha (key, body, algorithm) { - return crypto.createHmac(algorithm, key).update(body).digest('base64') -} +module.exports = () => Math.floor(Date.now() / 1000); -function rsa (key, body) { - return crypto.createSign('RSA-SHA1').update(body).sign(key, 'base64') -} -function rfc3986 (str) { - return encodeURIComponent(str) - .replace(/!/g,'%21') - .replace(/\*/g,'%2A') - .replace(/\(/g,'%28') - .replace(/\)/g,'%29') - .replace(/'/g,'%27') -} +/***/ }), -// Maps object to bi-dimensional array -// Converts { foo: 'A', bar: [ 'b', 'B' ]} to -// [ ['foo', 'A'], ['bar', 'b'], ['bar', 'B'] ] -function map (obj) { - var key, val, arr = [] - for (key in obj) { - val = obj[key] - if (Array.isArray(val)) - for (var i = 0; i < val.length; i++) - arr.push([key, val[i]]) - else if (typeof val === 'object') - for (var prop in val) - arr.push([key + '[' + prop + ']', val[prop]]) - else - arr.push([key, val]) - } - return arr -} +/***/ 27702: +/***/ ((module) => { -// Compare function for sort -function compare (a, b) { - return a > b ? 1 : a < b ? -1 : 0 -} +const privateProps = new WeakMap(); -function generateBase (httpMethod, base_uri, params) { - // adapted from https://dev.twitter.com/docs/auth/oauth and - // https://dev.twitter.com/docs/auth/creating-signature +module.exports = (ctx) => { + if (!privateProps.has(ctx)) { + privateProps.set(ctx, new Map([['metadata', new Map()]])); + } + return privateProps.get(ctx); +}; - // Parameter normalization - // http://tools.ietf.org/html/rfc5849#section-3.4.1.3.2 - var normalized = map(params) - // 1. First, the name and value of each parameter are encoded - .map(function (p) { - return [ rfc3986(p[0]), rfc3986(p[1] || '') ] - }) - // 2. The parameters are sorted by name, using ascending byte value - // ordering. If two or more parameters share the same name, they - // are sorted by their value. - .sort(function (a, b) { - return compare(a[0], b[0]) || compare(a[1], b[1]) - }) - // 3. The name of each parameter is concatenated to its corresponding - // value using an "=" character (ASCII code 61) as a separator, even - // if the value is empty. - .map(function (p) { return p.join('=') }) - // 4. The sorted name/value pairs are concatenated together into a - // single string by using an "&" character (ASCII code 38) as - // separator. - .join('&') - var base = [ - rfc3986(httpMethod ? httpMethod.toUpperCase() : 'GET'), - rfc3986(base_uri), - rfc3986(normalized) - ].join('&') +/***/ }), - return base -} +/***/ 27416: +/***/ ((module) => { -function hmacsign (httpMethod, base_uri, params, consumer_secret, token_secret) { - var base = generateBase(httpMethod, base_uri, params) - var key = [ - consumer_secret || '', - token_secret || '' - ].map(rfc3986).join('&') +// Credit: https://github.com/rohe/pyoidc/blob/master/src/oic/utils/webfinger.py - return sha(key, base, 'sha1') -} +// -- Normalization -- +// A string of any other type is interpreted as a URI either the form of scheme +// "://" authority path-abempty [ "?" query ] [ "#" fragment ] or authority +// path-abempty [ "?" query ] [ "#" fragment ] per RFC 3986 [RFC3986] and is +// normalized according to the following rules: +// +// If the user input Identifier does not have an RFC 3986 [RFC3986] scheme +// portion, the string is interpreted as [userinfo "@"] host [":" port] +// path-abempty [ "?" query ] [ "#" fragment ] per RFC 3986 [RFC3986]. +// If the userinfo component is present and all of the path component, query +// component, and port component are empty, the acct scheme is assumed. In this +// case, the normalized URI is formed by prefixing acct: to the string as the +// scheme. Per the 'acct' URI Scheme [I‑D.ietf‑appsawg‑acct‑uri], if there is an +// at-sign character ('@') in the userinfo component, it needs to be +// percent-encoded as described in RFC 3986 [RFC3986]. +// For all other inputs without a scheme portion, the https scheme is assumed, +// and the normalized URI is formed by prefixing https:// to the string as the +// scheme. +// If the resulting URI contains a fragment portion, it MUST be stripped off +// together with the fragment delimiter character "#". +// The WebFinger [I‑D.ietf‑appsawg‑webfinger] Resource in this case is the +// resulting URI, and the WebFinger Host is the authority component. +// +// Note: Since the definition of authority in RFC 3986 [RFC3986] is +// [ userinfo "@" ] host [ ":" port ], it is legal to have a user input +// identifier like userinfo@host:port, e.g., alice@example.com:8080. -function hmacsign256 (httpMethod, base_uri, params, consumer_secret, token_secret) { - var base = generateBase(httpMethod, base_uri, params) - var key = [ - consumer_secret || '', - token_secret || '' - ].map(rfc3986).join('&') +const PORT = /^\d+$/; - return sha(key, base, 'sha256') -} +function hasScheme(input) { + if (input.includes('://')) return true; -function rsasign (httpMethod, base_uri, params, private_key, token_secret) { - var base = generateBase(httpMethod, base_uri, params) - var key = private_key || '' + const authority = input.replace(/(\/|\?)/g, '#').split('#')[0]; + if (authority.includes(':')) { + const index = authority.indexOf(':'); + const hostOrPort = authority.slice(index + 1); + if (!PORT.test(hostOrPort)) { + return true; + } + } - return rsa(key, base) + return false; } -function plaintext (consumer_secret, token_secret) { - var key = [ - consumer_secret || '', - token_secret || '' - ].map(rfc3986).join('&') - - return key +function acctSchemeAssumed(input) { + if (!input.includes('@')) return false; + const parts = input.split('@'); + const host = parts[parts.length - 1]; + return !(host.includes(':') || host.includes('/') || host.includes('?')); } -function sign (signMethod, httpMethod, base_uri, params, consumer_secret, token_secret) { - var method - var skipArgs = 1 +function normalize(input) { + if (typeof input !== 'string') { + throw new TypeError('input must be a string'); + } - switch (signMethod) { - case 'RSA-SHA1': - method = rsasign - break - case 'HMAC-SHA1': - method = hmacsign - break - case 'HMAC-SHA256': - method = hmacsign256 - break - case 'PLAINTEXT': - method = plaintext - skipArgs = 4 - break - default: - throw new Error('Signature method not supported: ' + signMethod) + let output; + if (hasScheme(input)) { + output = input; + } else if (acctSchemeAssumed(input)) { + output = `acct:${input}`; + } else { + output = `https://${input}`; } - return method.apply(null, [].slice.call(arguments, skipArgs)) + return output.split('#')[0]; } -exports.hmacsign = hmacsign -exports.hmacsign256 = hmacsign256 -exports.rsasign = rsasign -exports.plaintext = plaintext -exports.sign = sign -exports.rfc3986 = rfc3986 -exports.generateBase = generateBase +module.exports = normalize; + /***/ }), -/***/ 24856: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 53140: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const Issuer = __nccwpck_require__(27213); +const { OPError, RPError } = __nccwpck_require__(45061); +const Registry = __nccwpck_require__(30730); +const Strategy = __nccwpck_require__(22134); +const TokenSet = __nccwpck_require__(39029); +const { CLOCK_TOLERANCE, HTTP_OPTIONS } = __nccwpck_require__(27556); +const generators = __nccwpck_require__(75421); +const { setDefaults } = __nccwpck_require__(92946); +module.exports = { + Issuer, + Registry, + Strategy, + TokenSet, + errors: { + OPError, + RPError, + }, + custom: { + setHttpOptionsDefaults: setDefaults, + http_options: HTTP_OPTIONS, + clock_tolerance: CLOCK_TOLERANCE, + }, + generators, +}; -var crypto = __nccwpck_require__(6113); -/** - * Exported function - * - * Options: - * - * - `algorithm` hash algo to be used by this instance: *'sha1', 'md5' - * - `excludeValues` {true|*false} hash object keys, values ignored - * - `encoding` hash encoding, supports 'buffer', '*hex', 'binary', 'base64' - * - `ignoreUnknown` {true|*false} ignore unknown object types - * - `replacer` optional function that replaces values before hashing - * - `respectFunctionProperties` {*true|false} consider function properties when hashing - * - `respectFunctionNames` {*true|false} consider 'name' property of functions for hashing - * - `respectType` {*true|false} Respect special properties (prototype, constructor) - * when hashing to distinguish between types - * - `unorderedArrays` {true|*false} Sort all arrays before hashing - * - `unorderedSets` {*true|false} Sort `Set` and `Map` instances before hashing - * * = default - * - * @param {object} object value to hash - * @param {object} options hashing options - * @return {string} hash value - * @api public - */ -exports = module.exports = objectHash; +/***/ }), -function objectHash(object, options){ - options = applyDefaults(object, options); +/***/ 27213: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return hash(object, options); -} +/* eslint-disable max-classes-per-file */ -/** - * Exported sugar methods - * - * @param {object} object value to hash - * @return {string} hash value - * @api public - */ -exports.sha1 = function(object){ - return objectHash(object); -}; -exports.keys = function(object){ - return objectHash(object, {excludeValues: true, algorithm: 'sha1', encoding: 'hex'}); -}; -exports.MD5 = function(object){ - return objectHash(object, {algorithm: 'md5', encoding: 'hex'}); -}; -exports.keysMD5 = function(object){ - return objectHash(object, {algorithm: 'md5', encoding: 'hex', excludeValues: true}); -}; +const { inspect } = __nccwpck_require__(73837); +const url = __nccwpck_require__(57310); -// Internals -var hashes = crypto.getHashes ? crypto.getHashes().slice() : ['sha1', 'md5']; -hashes.push('passthrough'); -var encodings = ['buffer', 'hex', 'binary', 'base64']; +const AggregateError = __nccwpck_require__(61231); +const jose = __nccwpck_require__(16425); +const LRU = __nccwpck_require__(7129); +const objectHash = __nccwpck_require__(24856); -function applyDefaults(object, sourceOptions){ - sourceOptions = sourceOptions || {}; +const { RPError } = __nccwpck_require__(45061); +const getClient = __nccwpck_require__(28300); +const registry = __nccwpck_require__(30730); +const processResponse = __nccwpck_require__(28576); +const webfingerNormalize = __nccwpck_require__(27416); +const instance = __nccwpck_require__(27702); +const request = __nccwpck_require__(92946); +const { assertIssuerConfiguration } = __nccwpck_require__(63217); +const { + ISSUER_DEFAULTS, OIDC_DISCOVERY, OAUTH2_DISCOVERY, WEBFINGER, REL, AAD_MULTITENANT_DISCOVERY, +} = __nccwpck_require__(27556); - // create a copy rather than mutating - var options = {}; - options.algorithm = sourceOptions.algorithm || 'sha1'; - options.encoding = sourceOptions.encoding || 'hex'; - options.excludeValues = sourceOptions.excludeValues ? true : false; - options.algorithm = options.algorithm.toLowerCase(); - options.encoding = options.encoding.toLowerCase(); - options.ignoreUnknown = sourceOptions.ignoreUnknown !== true ? false : true; // default to false - options.respectType = sourceOptions.respectType === false ? false : true; // default to true - options.respectFunctionNames = sourceOptions.respectFunctionNames === false ? false : true; - options.respectFunctionProperties = sourceOptions.respectFunctionProperties === false ? false : true; - options.unorderedArrays = sourceOptions.unorderedArrays !== true ? false : true; // default to false - options.unorderedSets = sourceOptions.unorderedSets === false ? false : true; // default to false - options.unorderedObjects = sourceOptions.unorderedObjects === false ? false : true; // default to true - options.replacer = sourceOptions.replacer || undefined; - options.excludeKeys = sourceOptions.excludeKeys || undefined; +const AAD_MULTITENANT = Symbol('AAD_MULTITENANT'); - if(typeof object === 'undefined') { - throw new Error('Object argument required.'); - } +class Issuer { + /** + * @name constructor + * @api public + */ + constructor(meta = {}) { + const aadIssValidation = meta[AAD_MULTITENANT]; + delete meta[AAD_MULTITENANT]; - // if there is a case-insensitive match in the hashes list, accept it - // (i.e. SHA256 for sha256) - for (var i = 0; i < hashes.length; ++i) { - if (hashes[i].toLowerCase() === options.algorithm.toLowerCase()) { - options.algorithm = hashes[i]; - } - } + ['introspection', 'revocation'].forEach((endpoint) => { + // if intro/revocation endpoint auth specific meta is missing use the token ones if they + // are defined + if ( + meta[`${endpoint}_endpoint`] + && meta[`${endpoint}_endpoint_auth_methods_supported`] === undefined + && meta[`${endpoint}_endpoint_auth_signing_alg_values_supported`] === undefined + ) { + if (meta.token_endpoint_auth_methods_supported) { + meta[`${endpoint}_endpoint_auth_methods_supported`] = meta.token_endpoint_auth_methods_supported; + } + if (meta.token_endpoint_auth_signing_alg_values_supported) { + meta[`${endpoint}_endpoint_auth_signing_alg_values_supported`] = meta.token_endpoint_auth_signing_alg_values_supported; + } + } + }); - if(hashes.indexOf(options.algorithm) === -1){ - throw new Error('Algorithm "' + options.algorithm + '" not supported. ' + - 'supported values: ' + hashes.join(', ')); - } + Object.entries(meta).forEach(([key, value]) => { + instance(this).get('metadata').set(key, value); + if (!this[key]) { + Object.defineProperty(this, key, { + get() { return instance(this).get('metadata').get(key); }, + enumerable: true, + }); + } + }); - if(encodings.indexOf(options.encoding) === -1 && - options.algorithm !== 'passthrough'){ - throw new Error('Encoding "' + options.encoding + '" not supported. ' + - 'supported values: ' + encodings.join(', ')); - } + instance(this).set('cache', new LRU({ max: 100 })); - return options; -} + registry.set(this.issuer, this); -/** Check if the given function is a native function */ -function isNativeFunction(f) { - if ((typeof f) !== 'function') { - return false; + const Client = getClient(this, aadIssValidation); + + Object.defineProperties(this, { + Client: { value: Client }, + FAPIClient: { value: class FAPIClient extends Client {} }, + }); } - var exp = /^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i; - return exp.exec(Function.prototype.toString.call(f)) != null; -} -function hash(object, options) { - var hashingStream; + /** + * @name keystore + * @api public + */ + async keystore(reload = false) { + assertIssuerConfiguration(this, 'jwks_uri'); - if (options.algorithm !== 'passthrough') { - hashingStream = crypto.createHash(options.algorithm); - } else { - hashingStream = new PassThrough(); - } + const keystore = instance(this).get('keystore'); + const cache = instance(this).get('cache'); - if (typeof hashingStream.write === 'undefined') { - hashingStream.write = hashingStream.update; - hashingStream.end = hashingStream.update; - } + if (reload || !keystore) { + cache.reset(); + const response = await request.call(this, { + method: 'GET', + responseType: 'json', + url: this.jwks_uri, + }); + const jwks = processResponse(response); - var hasher = typeHasher(options, hashingStream); - hasher.dispatch(object); - if (!hashingStream.update) { - hashingStream.end(''); - } + const joseKeyStore = jose.JWKS.asKeyStore(jwks, { ignoreErrors: true }); + cache.set('throttle', true, 60 * 1000); + instance(this).set('keystore', joseKeyStore); + return joseKeyStore; + } - if (hashingStream.digest) { - return hashingStream.digest(options.encoding === 'buffer' ? undefined : options.encoding); + return keystore; } - var buf = hashingStream.read(); - if (options.encoding === 'buffer') { - return buf; - } + /** + * @name queryKeyStore + * @api private + */ + async queryKeyStore({ + kid, kty, alg, use, key_ops: ops, + }, { allowMulti = false } = {}) { + const cache = instance(this).get('cache'); - return buf.toString(options.encoding); -} + const def = { + kid, kty, alg, use, key_ops: ops, + }; -/** - * Expose streaming API - * - * @param {object} object Value to serialize - * @param {object} options Options, as for hash() - * @param {object} stream A stream to write the serializiation to - * @api public - */ -exports.writeToStream = function(object, options, stream) { - if (typeof stream === 'undefined') { - stream = options; - options = {}; - } + const defHash = objectHash(def, { + algorithm: 'sha256', + ignoreUnknown: true, + unorderedArrays: true, + unorderedSets: true, + }); - options = applyDefaults(object, options); + // refresh keystore on every unknown key but also only upto once every minute + const freshJwksUri = cache.get(defHash) || cache.get('throttle'); - return typeHasher(options, stream).dispatch(object); -}; + const keystore = await this.keystore(!freshJwksUri); + const keys = keystore.all(def); -function typeHasher(options, writeTo, context){ - context = context || []; - var write = function(str) { - if (writeTo.update) { - return writeTo.update(str, 'utf8'); - } else { - return writeTo.write(str, 'utf8'); + if (keys.length === 0) { + throw new RPError({ + printf: ["no valid key found in issuer's jwks_uri for key parameters %j", def], + jwks: keystore, + }); } - }; - return { - dispatch: function(value){ - if (options.replacer) { - value = options.replacer(value); - } + if (!allowMulti && keys.length > 1 && !kid) { + throw new RPError({ + printf: ["multiple matching keys found in issuer's jwks_uri for key parameters %j, kid must be provided in this case", def], + jwks: keystore, + }); + } - var type = typeof value; - if (value === null) { - type = 'null'; - } + cache.set(defHash, true); - //console.log("[DEBUG] Dispatch: ", value, "->", type, " -> ", "_" + type); + return new jose.JWKS.KeyStore(keys); + } - return this['_' + type](value); - }, - _object: function(object) { - var pattern = (/\[object (.*)\]/i); - var objString = Object.prototype.toString.call(object); - var objType = pattern.exec(objString); - if (!objType) { // object type did not match [object ...] - objType = 'unknown:[' + objString + ']'; - } else { - objType = objType[1]; // take only the class name - } + /** + * @name metadata + * @api public + */ + get metadata() { + const copy = {}; + instance(this).get('metadata').forEach((value, key) => { + copy[key] = value; + }); + return copy; + } - objType = objType.toLowerCase(); + /** + * @name webfinger + * @api public + */ + static async webfinger(input) { + const resource = webfingerNormalize(input); + const { host } = url.parse(resource); + const webfingerUrl = `https://${host}${WEBFINGER}`; - var objectNumber = null; + const response = await request.call(this, { + method: 'GET', + url: webfingerUrl, + responseType: 'json', + searchParams: { resource, rel: REL }, + followRedirect: true, + }); + const body = processResponse(response); - if ((objectNumber = context.indexOf(object)) >= 0) { - return this.dispatch('[CIRCULAR:' + objectNumber + ']'); - } else { - context.push(object); - } + const location = Array.isArray(body.links) && body.links.find((link) => typeof link === 'object' && link.rel === REL && link.href); - if (typeof Buffer !== 'undefined' && Buffer.isBuffer && Buffer.isBuffer(object)) { - write('buffer:'); - return write(object); - } + if (!location) { + throw new RPError({ + message: 'no issuer found in webfinger response', + body, + }); + } - if(objType !== 'object' && objType !== 'function' && objType !== 'asyncfunction') { - if(this['_' + objType]) { - this['_' + objType](object); - } else if (options.ignoreUnknown) { - return write('[' + objType + ']'); - } else { - throw new Error('Unknown object type "' + objType + '"'); - } - }else{ - var keys = Object.keys(object); - if (options.unorderedObjects) { - keys = keys.sort(); - } - // Make sure to incorporate special properties, so - // Types with different prototypes will produce - // a different hash and objects derived from - // different functions (`new Foo`, `new Bar`) will - // produce different hashes. - // We never do this for native functions since some - // seem to break because of that. - if (options.respectType !== false && !isNativeFunction(object)) { - keys.splice(0, 0, 'prototype', '__proto__', 'constructor'); - } + if (typeof location.href !== 'string' || !location.href.startsWith('https://')) { + throw new RPError({ + printf: ['invalid issuer location %s', location.href], + body, + }); + } - if (options.excludeKeys) { - keys = keys.filter(function(key) { return !options.excludeKeys(key); }); - } + const expectedIssuer = location.href; + if (registry.has(expectedIssuer)) { + return registry.get(expectedIssuer); + } - write('object:' + keys.length + ':'); - var self = this; - return keys.forEach(function(key){ - self.dispatch(key); - write(':'); - if(!options.excludeValues) { - self.dispatch(object[key]); - } - write(','); - }); - } - }, - _array: function(arr, unordered){ - unordered = typeof unordered !== 'undefined' ? unordered : - options.unorderedArrays !== false; // default to options.unorderedArrays + const issuer = await this.discover(expectedIssuer); - var self = this; - write('array:' + arr.length + ':'); - if (!unordered || arr.length <= 1) { - return arr.forEach(function(entry) { - return self.dispatch(entry); - }); - } + if (issuer.issuer !== expectedIssuer) { + registry.delete(issuer.issuer); + throw new RPError('discovered issuer mismatch, expected %s, got: %s', expectedIssuer, issuer.issuer); + } + return issuer; + } - // the unordered case is a little more complicated: - // since there is no canonical ordering on objects, - // i.e. {a:1} < {a:2} and {a:1} > {a:2} are both false, - // we first serialize each entry using a PassThrough stream - // before sorting. - // also: we can’t use the same context array for all entries - // since the order of hashing should *not* matter. instead, - // we keep track of the additions to a copy of the context array - // and add all of them to the global context array when we’re done - var contextAdditions = []; - var entries = arr.map(function(entry) { - var strm = new PassThrough(); - var localContext = context.slice(); // make copy - var hasher = typeHasher(options, strm, localContext); - hasher.dispatch(entry); - // take only what was added to localContext and append it to contextAdditions - contextAdditions = contextAdditions.concat(localContext.slice(context.length)); - return strm.read().toString(); + /** + * @name discover + * @api public + */ + static async discover(uri) { + const parsed = url.parse(uri); + + if (parsed.pathname.includes('/.well-known/')) { + const response = await request.call(this, { + method: 'GET', + responseType: 'json', + url: uri, }); - context = context.concat(contextAdditions); - entries.sort(); - return this._array(entries, false); - }, - _date: function(date){ - return write('date:' + date.toJSON()); - }, - _symbol: function(sym){ - return write('symbol:' + sym.toString()); - }, - _error: function(err){ - return write('error:' + err.toString()); - }, - _boolean: function(bool){ - return write('bool:' + bool.toString()); - }, - _string: function(string){ - write('string:' + string.length + ':'); - write(string.toString()); - }, - _function: function(fn){ - write('fn:'); - if (isNativeFunction(fn)) { - this.dispatch('[native]'); - } else { - this.dispatch(fn.toString()); - } + const body = processResponse(response); + return new Issuer({ + ...ISSUER_DEFAULTS, + ...body, + [AAD_MULTITENANT]: !!AAD_MULTITENANT_DISCOVERY.find( + (discoveryURL) => uri.startsWith(discoveryURL), + ), + }); + } - if (options.respectFunctionNames !== false) { - // Make sure we can still distinguish native functions - // by their name, otherwise String and Function will - // have the same hash - this.dispatch("function-name:" + String(fn.name)); - } + const pathnames = []; + if (parsed.pathname.endsWith('/')) { + pathnames.push(`${parsed.pathname}${OIDC_DISCOVERY.substring(1)}`); + } else { + pathnames.push(`${parsed.pathname}${OIDC_DISCOVERY}`); + } + if (parsed.pathname === '/') { + pathnames.push(`${OAUTH2_DISCOVERY}`); + } else { + pathnames.push(`${OAUTH2_DISCOVERY}${parsed.pathname}`); + } - if (options.respectFunctionProperties) { - this._object(fn); - } - }, - _number: function(number){ - return write('number:' + number.toString()); - }, - _xml: function(xml){ - return write('xml:' + xml.toString()); - }, - _null: function() { - return write('Null'); - }, - _undefined: function() { - return write('Undefined'); - }, - _regexp: function(regex){ - return write('regex:' + regex.toString()); - }, - _uint8array: function(arr){ - write('uint8array:'); - return this.dispatch(Array.prototype.slice.call(arr)); - }, - _uint8clampedarray: function(arr){ - write('uint8clampedarray:'); - return this.dispatch(Array.prototype.slice.call(arr)); - }, - _int8array: function(arr){ - write('uint8array:'); - return this.dispatch(Array.prototype.slice.call(arr)); - }, - _uint16array: function(arr){ - write('uint16array:'); - return this.dispatch(Array.prototype.slice.call(arr)); - }, - _int16array: function(arr){ - write('uint16array:'); - return this.dispatch(Array.prototype.slice.call(arr)); - }, - _uint32array: function(arr){ - write('uint32array:'); - return this.dispatch(Array.prototype.slice.call(arr)); - }, - _int32array: function(arr){ - write('uint32array:'); - return this.dispatch(Array.prototype.slice.call(arr)); - }, - _float32array: function(arr){ - write('float32array:'); - return this.dispatch(Array.prototype.slice.call(arr)); - }, - _float64array: function(arr){ - write('float64array:'); - return this.dispatch(Array.prototype.slice.call(arr)); - }, - _arraybuffer: function(arr){ - write('arraybuffer:'); - return this.dispatch(new Uint8Array(arr)); - }, - _url: function(url) { - return write('url:' + url.toString(), 'utf8'); - }, - _map: function(map) { - write('map:'); - var arr = Array.from(map); - return this._array(arr, options.unorderedSets !== false); - }, - _set: function(set) { - write('set:'); - var arr = Array.from(set); - return this._array(arr, options.unorderedSets !== false); - }, - _file: function(file) { - write('file:'); - return this.dispatch([file.name, file.size, file.type, file.lastModfied]); - }, - _blob: function() { - if (options.ignoreUnknown) { - return write('[blob]'); + const errors = []; + // eslint-disable-next-line no-restricted-syntax + for (const pathname of pathnames) { + try { + const wellKnownUri = url.format({ ...parsed, pathname }); + // eslint-disable-next-line no-await-in-loop + const response = await request.call(this, { + method: 'GET', + responseType: 'json', + url: wellKnownUri, + }); + const body = processResponse(response); + return new Issuer({ + ...ISSUER_DEFAULTS, + ...body, + [AAD_MULTITENANT]: !!AAD_MULTITENANT_DISCOVERY.find( + (discoveryURL) => wellKnownUri.startsWith(discoveryURL), + ), + }); + } catch (err) { + errors.push(err); } + } - throw Error('Hashing Blob objects is currently not supported\n' + - '(see https://github.com/puleos/object-hash/issues/26)\n' + - 'Use "options.replacer" or "options.ignoreUnknown"\n'); - }, - _domwindow: function() { return write('domwindow'); }, - _bigint: function(number){ - return write('bigint:' + number.toString()); - }, - /* Node.js standard native objects */ - _process: function() { return write('process'); }, - _timer: function() { return write('timer'); }, - _pipe: function() { return write('pipe'); }, - _tcp: function() { return write('tcp'); }, - _udp: function() { return write('udp'); }, - _tty: function() { return write('tty'); }, - _statwatcher: function() { return write('statwatcher'); }, - _securecontext: function() { return write('securecontext'); }, - _connection: function() { return write('connection'); }, - _zlib: function() { return write('zlib'); }, - _context: function() { return write('context'); }, - _nodescript: function() { return write('nodescript'); }, - _httpparser: function() { return write('httpparser'); }, - _dataview: function() { return write('dataview'); }, - _signal: function() { return write('signal'); }, - _fsevent: function() { return write('fsevent'); }, - _tlswrap: function() { return write('tlswrap'); }, - }; -} - -// Mini-implementation of stream.PassThrough -// We are far from having need for the full implementation, and we can -// make assumptions like "many writes, then only one final read" -// and we can ignore encoding specifics -function PassThrough() { - return { - buf: '', - - write: function(b) { - this.buf += b; - }, - - end: function(b) { - this.buf += b; - }, + const err = new AggregateError(errors); + err.message = `Issuer.discover() failed.${err.message.split('\n') + .filter((line) => !line.startsWith(' at')).join('\n')}`; + throw err; + } - read: function() { - return this.buf; - } - }; + /* istanbul ignore next */ + [inspect.custom]() { + return `${this.constructor.name} ${inspect(this.metadata, { + depth: Infinity, + colors: process.stdout.isTTY, + compact: false, + sorted: true, + })}`; + } } +module.exports = Issuer; -/***/ }), -/***/ 1270: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ }), -const { strict: assert } = __nccwpck_require__(39491); -const { createHash } = __nccwpck_require__(6113); -const { format } = __nccwpck_require__(73837); +/***/ 30730: +/***/ ((module) => { -const shake256 = __nccwpck_require__(19811); +const REGISTRY = new Map(); -let encode; -if (Buffer.isEncoding('base64url')) { - encode = (input) => input.toString('base64url'); -} else { - const fromBase64 = (base64) => base64.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); - encode = (input) => fromBase64(input.toString('base64')); -} +module.exports = REGISTRY; -/** SPECIFICATION - * Its (_hash) value is the base64url encoding of the left-most half of the hash of the octets of - * the ASCII representation of the token value, where the hash algorithm used is the hash algorithm - * used in the alg Header Parameter of the ID Token's JOSE Header. For instance, if the alg is - * RS256, hash the token value with SHA-256, then take the left-most 128 bits and base64url encode - * them. The _hash value is a case sensitive string. - */ -/** - * @name getHash - * @api private - * - * returns the sha length based off the JOSE alg heade value, defaults to sha256 - * - * @param token {String} token value to generate the hash from - * @param alg {String} ID Token JOSE header alg value (i.e. RS256, HS384, ES512, PS256) - * @param [crv] {String} For EdDSA the curve decides what hash algorithm is used. Required for EdDSA - */ -function getHash(alg, crv) { - switch (alg) { - case 'HS256': - case 'RS256': - case 'PS256': - case 'ES256': - case 'ES256K': - return createHash('sha256'); +/***/ }), - case 'HS384': - case 'RS384': - case 'PS384': - case 'ES384': - return createHash('sha384'); +/***/ 22134: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - case 'HS512': - case 'RS512': - case 'PS512': - case 'ES512': - return createHash('sha512'); +/* eslint-disable no-underscore-dangle */ - case 'EdDSA': - switch (crv) { - case 'Ed25519': - return createHash('sha512'); - case 'Ed448': - if (!shake256) { - throw new TypeError('Ed448 *_hash calculation is not supported in your Node.js runtime version'); - } +const url = __nccwpck_require__(57310); +const { format } = __nccwpck_require__(73837); - return createHash('shake256', { outputLength: 114 }); - default: - throw new TypeError('unrecognized or invalid EdDSA curve provided'); - } +const cloneDeep = __nccwpck_require__(21004); +const { RPError, OPError } = __nccwpck_require__(45061); +const { BaseClient } = __nccwpck_require__(28300); +const { random, codeChallenge } = __nccwpck_require__(75421); +const pick = __nccwpck_require__(78857); +const { resolveResponseType, resolveRedirectUri } = __nccwpck_require__(7619); - default: - throw new TypeError('unrecognized or invalid JWS algorithm provided'); +function verified(err, user, info = {}) { + if (err) { + this.error(err); + } else if (!user) { + this.fail(info); + } else { + this.success(user, info); } } -function generate(token, alg, crv) { - const digest = getHash(alg, crv).update(token).digest(); - return encode(digest.slice(0, digest.length / 2)); -} +/** + * @name constructor + * @api public + */ +function OpenIDConnectStrategy({ + client, + params = {}, + passReqToCallback = false, + sessionKey, + usePKCE = true, + extras = {}, +} = {}, verify) { + if (!(client instanceof BaseClient)) { + throw new TypeError('client must be an instance of openid-client Client'); + } -function validate(names, actual, source, alg, crv) { - if (typeof names.claim !== 'string' || !names.claim) { - throw new TypeError('names.claim must be a non-empty string'); + if (typeof verify !== 'function') { + throw new TypeError('verify callback must be a function'); } - if (typeof names.source !== 'string' || !names.source) { - throw new TypeError('names.source must be a non-empty string'); + if (!client.issuer || !client.issuer.issuer) { + throw new TypeError('client must have an issuer with an identifier'); } - assert(typeof actual === 'string' && actual, `${names.claim} must be a non-empty string`); - assert(typeof source === 'string' && source, `${names.source} must be a non-empty string`); + this._client = client; + this._issuer = client.issuer; + this._verify = verify; + this._passReqToCallback = passReqToCallback; + this._usePKCE = usePKCE; + this._key = sessionKey || `oidc:${url.parse(this._issuer.issuer).hostname}`; + this._params = cloneDeep(params); + this._extras = cloneDeep(extras); - let expected; - let msg; - try { - expected = generate(source, alg, crv); - } catch (err) { - msg = format('%s could not be validated (%s)', names.claim, err.message); - } + if (!this._params.response_type) this._params.response_type = resolveResponseType.call(client); + if (!this._params.redirect_uri) this._params.redirect_uri = resolveRedirectUri.call(client); + if (!this._params.scope) this._params.scope = 'openid'; - msg = msg || format('%s mismatch, expected %s, got: %s', names.claim, expected, actual); + if (this._usePKCE === true) { + const supportedMethods = Array.isArray(this._issuer.code_challenge_methods_supported) + ? this._issuer.code_challenge_methods_supported : false; - assert.equal(expected, actual, msg); + if (supportedMethods && supportedMethods.includes('S256')) { + this._usePKCE = 'S256'; + } else if (supportedMethods && supportedMethods.includes('plain')) { + this._usePKCE = 'plain'; + } else if (supportedMethods) { + throw new TypeError('neither code_challenge_method supported by the client is supported by the issuer'); + } else { + this._usePKCE = 'S256'; + } + } else if (typeof this._usePKCE === 'string' && !['plain', 'S256'].includes(this._usePKCE)) { + throw new TypeError(`${this._usePKCE} is not valid/implemented PKCE code_challenge_method`); + } + + this.name = url.parse(client.issuer.issuer).hostname; } -module.exports = { - validate, - generate, -}; +OpenIDConnectStrategy.prototype.authenticate = function authenticate(req, options) { + (async () => { + const client = this._client; + if (!req.session) { + throw new TypeError('authentication requires session support'); + } + const reqParams = client.callbackParams(req); + const sessionKey = this._key; + /* start authentication request */ + if (Object.keys(reqParams).length === 0) { + // provide options object with extra authentication parameters + const params = { + state: random(), + ...this._params, + ...options, + }; -/***/ }), + if (!params.nonce && params.response_type.includes('id_token')) { + params.nonce = random(); + } -/***/ 19811: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + req.session[sessionKey] = pick(params, 'nonce', 'state', 'max_age', 'response_type'); -const crypto = __nccwpck_require__(6113); + if (this._usePKCE && params.response_type.includes('code')) { + const verifier = random(); + req.session[sessionKey].code_verifier = verifier; -const [major, minor] = process.version.substring(1).split('.').map((x) => parseInt(x, 10)); -const xofOutputLength = major > 12 || (major === 12 && minor >= 8); -const shake256 = xofOutputLength && crypto.getHashes().includes('shake256'); + switch (this._usePKCE) { // eslint-disable-line default-case + case 'S256': + params.code_challenge = codeChallenge(verifier); + params.code_challenge_method = 'S256'; + break; + case 'plain': + params.code_challenge = verifier; + break; + } + } -module.exports = shake256; + this.redirect(client.authorizationUrl(params)); + return; + } + /* end authentication request */ + /* start authentication response */ -/***/ }), + const session = req.session[sessionKey]; + if (Object.keys(session || {}).length === 0) { + throw new Error(format('did not find expected authorization request details in session, req.session["%s"] is %j', sessionKey, session)); + } -/***/ 1223: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + const { + state, nonce, max_age: maxAge, code_verifier: codeVerifier, response_type: responseType, + } = session; -var wrappy = __nccwpck_require__(62940) -module.exports = wrappy(once) -module.exports.strict = wrappy(onceStrict) + try { + delete req.session[sessionKey]; + } catch (err) {} -once.proto = once(function () { - Object.defineProperty(Function.prototype, 'once', { - value: function () { - return once(this) - }, - configurable: true - }) + const opts = { + redirect_uri: this._params.redirect_uri, + ...options, + }; - Object.defineProperty(Function.prototype, 'onceStrict', { - value: function () { - return onceStrict(this) - }, - configurable: true - }) -}) + const checks = { + state, + nonce, + max_age: maxAge, + code_verifier: codeVerifier, + response_type: responseType, + }; -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 tokenset = await client.callback(opts.redirect_uri, reqParams, checks, this._extras); -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 -} + const passReq = this._passReqToCallback; + const loadUserinfo = this._verify.length > (passReq ? 3 : 2) && client.issuer.userinfo_endpoint; + const args = [tokenset, verified.bind(this)]; -/***/ }), + if (loadUserinfo) { + if (!tokenset.access_token) { + throw new RPError({ + message: 'expected access_token to be returned when asking for userinfo in verify callback', + tokenset, + }); + } + const userinfo = await client.userinfo(tokenset); + args.splice(1, 0, userinfo); + } -/***/ 89082: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (passReq) { + args.unshift(req); + } -"use strict"; + this._verify(...args); + /* end authentication response */ + })().catch((error) => { + if ( + (error instanceof OPError && error.error !== 'server_error' && !error.error.startsWith('invalid')) + || error instanceof RPError + ) { + this.fail(error); + } else { + this.error(error); + } + }); +}; -const mimicFn = __nccwpck_require__(76047); +module.exports = OpenIDConnectStrategy; -const calledFunctions = new WeakMap(); -const onetime = (function_, options = {}) => { - if (typeof function_ !== 'function') { - throw new TypeError('Expected a function'); - } +/***/ }), - let returnValue; - let callCount = 0; - const functionName = function_.displayName || function_.name || ''; +/***/ 39029: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const onetime = function (...arguments_) { - calledFunctions.set(onetime, ++callCount); +const base64url = __nccwpck_require__(61827); +const now = __nccwpck_require__(8542); - if (callCount === 1) { - returnValue = function_.apply(this, arguments_); - function_ = null; - } else if (options.throw === true) { - throw new Error(`Function \`${functionName}\` can only be called once`); - } +class TokenSet { + /** + * @name constructor + * @api public + */ + constructor(values) { + Object.assign(this, values); + } - return returnValue; - }; + /** + * @name expires_in= + * @api public + */ + set expires_in(value) { // eslint-disable-line camelcase + this.expires_at = now() + Number(value); + } - mimicFn(onetime, function_); - calledFunctions.set(onetime, callCount); + /** + * @name expires_in + * @api public + */ + get expires_in() { // eslint-disable-line camelcase + return Math.max.apply(null, [this.expires_at - now(), 0]); + } - return onetime; -}; + /** + * @name expired + * @api public + */ + expired() { + return this.expires_in === 0; + } -module.exports = onetime; -// TODO: Remove this for the next major release -module.exports["default"] = onetime; + /** + * @name claims + * @api public + */ + claims() { + if (!this.id_token) { + throw new TypeError('id_token not present in TokenSet'); + } -module.exports.callCount = function_ => { - if (!calledFunctions.has(function_)) { - throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`); - } + return JSON.parse(base64url.decode(this.id_token.split('.')[1])); + } +} - return calledFunctions.get(function_); -}; +module.exports = TokenSet; /***/ }), @@ -318280,6 +318977,682 @@ var pump = function () { module.exports = pump +/***/ }), + +/***/ 74907: +/***/ ((module) => { + +"use strict"; + + +var replace = String.prototype.replace; +var percentTwenties = /%20/g; + +module.exports = { + 'default': 'RFC3986', + formatters: { + RFC1738: function (value) { + return replace.call(value, percentTwenties, '+'); + }, + RFC3986: function (value) { + return String(value); + } + }, + RFC1738: 'RFC1738', + RFC3986: 'RFC3986' +}; + + +/***/ }), + +/***/ 22760: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var stringify = __nccwpck_require__(79954); +var parse = __nccwpck_require__(33912); +var formats = __nccwpck_require__(74907); + +module.exports = { + formats: formats, + parse: parse, + stringify: stringify +}; + + +/***/ }), + +/***/ 33912: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var utils = __nccwpck_require__(72360); + +var has = Object.prototype.hasOwnProperty; + +var defaults = { + allowDots: false, + allowPrototypes: false, + arrayLimit: 20, + decoder: utils.decode, + delimiter: '&', + depth: 5, + parameterLimit: 1000, + plainObjects: false, + strictNullHandling: false +}; + +var parseValues = function parseQueryStringValues(str, options) { + var obj = {}; + var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; + var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; + var parts = cleanStr.split(options.delimiter, limit); + + for (var i = 0; i < parts.length; ++i) { + var part = parts[i]; + + var bracketEqualsPos = part.indexOf(']='); + var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; + + var key, val; + if (pos === -1) { + key = options.decoder(part, defaults.decoder); + val = options.strictNullHandling ? null : ''; + } else { + key = options.decoder(part.slice(0, pos), defaults.decoder); + val = options.decoder(part.slice(pos + 1), defaults.decoder); + } + if (has.call(obj, key)) { + obj[key] = [].concat(obj[key]).concat(val); + } else { + obj[key] = val; + } + } + + return obj; +}; + +var parseObject = function (chain, val, options) { + var leaf = val; + + for (var i = chain.length - 1; i >= 0; --i) { + var obj; + var root = chain[i]; + + if (root === '[]' && options.parseArrays) { + obj = [].concat(leaf); + } else { + obj = options.plainObjects ? Object.create(null) : {}; + var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; + var index = parseInt(cleanRoot, 10); + if (!options.parseArrays && cleanRoot === '') { + obj = { 0: leaf }; + } else if ( + !isNaN(index) + && root !== cleanRoot + && String(index) === cleanRoot + && index >= 0 + && (options.parseArrays && index <= options.arrayLimit) + ) { + obj = []; + obj[index] = leaf; + } else if (cleanRoot !== '__proto__') { + obj[cleanRoot] = leaf; + } + } + + leaf = obj; + } + + return leaf; +}; + +var parseKeys = function parseQueryStringKeys(givenKey, val, options) { + if (!givenKey) { + return; + } + + // Transform dot notation to bracket notation + var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; + + // The regex chunks + + var brackets = /(\[[^[\]]*])/; + var child = /(\[[^[\]]*])/g; + + // Get the parent + + var segment = brackets.exec(key); + var parent = segment ? key.slice(0, segment.index) : key; + + // Stash the parent if it exists + + var keys = []; + if (parent) { + // If we aren't using plain objects, optionally prefix keys + // that would overwrite object prototype properties + if (!options.plainObjects && has.call(Object.prototype, parent)) { + if (!options.allowPrototypes) { + return; + } + } + + keys.push(parent); + } + + // Loop through children appending to the array until we hit depth + + var i = 0; + while ((segment = child.exec(key)) !== null && i < options.depth) { + i += 1; + if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { + if (!options.allowPrototypes) { + return; + } + } + keys.push(segment[1]); + } + + // If there's a remainder, just add whatever is left + + if (segment) { + keys.push('[' + key.slice(segment.index) + ']'); + } + + return parseObject(keys, val, options); +}; + +module.exports = function (str, opts) { + var options = opts ? utils.assign({}, opts) : {}; + + if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') { + throw new TypeError('Decoder has to be a function.'); + } + + options.ignoreQueryPrefix = options.ignoreQueryPrefix === true; + options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults.delimiter; + options.depth = typeof options.depth === 'number' ? options.depth : defaults.depth; + options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit; + options.parseArrays = options.parseArrays !== false; + options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults.decoder; + options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults.allowDots; + options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults.plainObjects; + options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults.allowPrototypes; + options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults.parameterLimit; + options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling; + + if (str === '' || str === null || typeof str === 'undefined') { + return options.plainObjects ? Object.create(null) : {}; + } + + var tempObj = typeof str === 'string' ? parseValues(str, options) : str; + var obj = options.plainObjects ? Object.create(null) : {}; + + // Iterate over the keys and setup the new object + + var keys = Object.keys(tempObj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var newObj = parseKeys(key, tempObj[key], options); + obj = utils.merge(obj, newObj, options); + } + + return utils.compact(obj); +}; + + +/***/ }), + +/***/ 79954: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var utils = __nccwpck_require__(72360); +var formats = __nccwpck_require__(74907); + +var arrayPrefixGenerators = { + brackets: function brackets(prefix) { + return prefix + '[]'; + }, + indices: function indices(prefix, key) { + return prefix + '[' + key + ']'; + }, + repeat: function repeat(prefix) { + return prefix; + } +}; + +var isArray = Array.isArray; +var push = Array.prototype.push; +var pushToArray = function (arr, valueOrArray) { + push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); +}; + +var toISO = Date.prototype.toISOString; + +var defaults = { + delimiter: '&', + encode: true, + encoder: utils.encode, + encodeValuesOnly: false, + serializeDate: function serializeDate(date) { + return toISO.call(date); + }, + skipNulls: false, + strictNullHandling: false +}; + +var stringify = function stringify( + object, + prefix, + generateArrayPrefix, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + formatter, + encodeValuesOnly +) { + var obj = object; + if (typeof filter === 'function') { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate(obj); + } + + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder) : prefix; + } + + obj = ''; + } + + if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) { + if (encoder) { + var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder); + return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder))]; + } + return [formatter(prefix) + '=' + formatter(String(obj))]; + } + + var values = []; + + if (typeof obj === 'undefined') { + return values; + } + + var objKeys; + if (isArray(filter)) { + objKeys = filter; + } else { + var keys = Object.keys(obj); + objKeys = sort ? keys.sort(sort) : keys; + } + + for (var i = 0; i < objKeys.length; ++i) { + var key = objKeys[i]; + + if (skipNulls && obj[key] === null) { + continue; + } + + if (isArray(obj)) { + pushToArray(values, stringify( + obj[key], + generateArrayPrefix(prefix, key), + generateArrayPrefix, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + formatter, + encodeValuesOnly + )); + } else { + pushToArray(values, stringify( + obj[key], + prefix + (allowDots ? '.' + key : '[' + key + ']'), + generateArrayPrefix, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + formatter, + encodeValuesOnly + )); + } + } + + return values; +}; + +module.exports = function (object, opts) { + var obj = object; + var options = opts ? utils.assign({}, opts) : {}; + + if (options.encoder !== null && typeof options.encoder !== 'undefined' && typeof options.encoder !== 'function') { + throw new TypeError('Encoder has to be a function.'); + } + + var delimiter = typeof options.delimiter === 'undefined' ? defaults.delimiter : options.delimiter; + var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling; + var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults.skipNulls; + var encode = typeof options.encode === 'boolean' ? options.encode : defaults.encode; + var encoder = typeof options.encoder === 'function' ? options.encoder : defaults.encoder; + var sort = typeof options.sort === 'function' ? options.sort : null; + var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots; + var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults.serializeDate; + var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults.encodeValuesOnly; + if (typeof options.format === 'undefined') { + options.format = formats['default']; + } else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) { + throw new TypeError('Unknown format option provided.'); + } + var formatter = formats.formatters[options.format]; + var objKeys; + var filter; + + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); + } else if (isArray(options.filter)) { + filter = options.filter; + objKeys = filter; + } + + var keys = []; + + if (typeof obj !== 'object' || obj === null) { + return ''; + } + + var arrayFormat; + if (options.arrayFormat in arrayPrefixGenerators) { + arrayFormat = options.arrayFormat; + } else if ('indices' in options) { + arrayFormat = options.indices ? 'indices' : 'repeat'; + } else { + arrayFormat = 'indices'; + } + + var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; + + if (!objKeys) { + objKeys = Object.keys(obj); + } + + if (sort) { + objKeys.sort(sort); + } + + for (var i = 0; i < objKeys.length; ++i) { + var key = objKeys[i]; + + if (skipNulls && obj[key] === null) { + continue; + } + pushToArray(keys, stringify( + obj[key], + key, + generateArrayPrefix, + strictNullHandling, + skipNulls, + encode ? encoder : null, + filter, + sort, + allowDots, + serializeDate, + formatter, + encodeValuesOnly + )); + } + + var joined = keys.join(delimiter); + var prefix = options.addQueryPrefix === true ? '?' : ''; + + return joined.length > 0 ? prefix + joined : ''; +}; + + +/***/ }), + +/***/ 72360: +/***/ ((module) => { + +"use strict"; + + +var has = Object.prototype.hasOwnProperty; + +var hexTable = (function () { + var array = []; + for (var i = 0; i < 256; ++i) { + array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); + } + + return array; +}()); + +var compactQueue = function compactQueue(queue) { + var obj; + + while (queue.length) { + var item = queue.pop(); + obj = item.obj[item.prop]; + + if (Array.isArray(obj)) { + var compacted = []; + + for (var j = 0; j < obj.length; ++j) { + if (typeof obj[j] !== 'undefined') { + compacted.push(obj[j]); + } + } + + item.obj[item.prop] = compacted; + } + } + + return obj; +}; + +var arrayToObject = function arrayToObject(source, options) { + var obj = options && options.plainObjects ? Object.create(null) : {}; + for (var i = 0; i < source.length; ++i) { + if (typeof source[i] !== 'undefined') { + obj[i] = source[i]; + } + } + + return obj; +}; + +var merge = function merge(target, source, options) { + if (!source) { + return target; + } + + if (typeof source !== 'object') { + if (Array.isArray(target)) { + target.push(source); + } else if (target && typeof target === 'object') { + if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) { + target[source] = true; + } + } else { + return [target, source]; + } + + return target; + } + + if (!target || typeof target !== 'object') { + return [target].concat(source); + } + + var mergeTarget = target; + if (Array.isArray(target) && !Array.isArray(source)) { + mergeTarget = arrayToObject(target, options); + } + + if (Array.isArray(target) && Array.isArray(source)) { + source.forEach(function (item, i) { + if (has.call(target, i)) { + var targetItem = target[i]; + if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { + target[i] = merge(targetItem, item, options); + } else { + target.push(item); + } + } else { + target[i] = item; + } + }); + return target; + } + + return Object.keys(source).reduce(function (acc, key) { + var value = source[key]; + + if (has.call(acc, key)) { + acc[key] = merge(acc[key], value, options); + } else { + acc[key] = value; + } + return acc; + }, mergeTarget); +}; + +var assign = function assignSingleSource(target, source) { + return Object.keys(source).reduce(function (acc, key) { + acc[key] = source[key]; + return acc; + }, target); +}; + +var decode = function (str) { + try { + return decodeURIComponent(str.replace(/\+/g, ' ')); + } catch (e) { + return str; + } +}; + +var encode = function encode(str) { + // This code was originally written by Brian White (mscdex) for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } + + var string = typeof str === 'string' ? str : String(str); + + var out = ''; + for (var i = 0; i < string.length; ++i) { + var c = string.charCodeAt(i); + + if ( + c === 0x2D // - + || c === 0x2E // . + || c === 0x5F // _ + || c === 0x7E // ~ + || (c >= 0x30 && c <= 0x39) // 0-9 + || (c >= 0x41 && c <= 0x5A) // a-z + || (c >= 0x61 && c <= 0x7A) // A-Z + ) { + out += string.charAt(i); + continue; + } + + if (c < 0x80) { + out = out + hexTable[c]; + continue; + } + + if (c < 0x800) { + out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } + + if (c < 0xD800 || c >= 0xE000) { + out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } + + i += 1; + c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); + /* eslint operator-linebreak: [2, "before"] */ + out += hexTable[0xF0 | (c >> 18)] + + hexTable[0x80 | ((c >> 12) & 0x3F)] + + hexTable[0x80 | ((c >> 6) & 0x3F)] + + hexTable[0x80 | (c & 0x3F)]; + } + + return out; +}; + +var compact = function compact(value) { + var queue = [{ obj: { o: value }, prop: 'o' }]; + var refs = []; + + for (var i = 0; i < queue.length; ++i) { + var item = queue[i]; + var obj = item.obj[item.prop]; + + var keys = Object.keys(obj); + for (var j = 0; j < keys.length; ++j) { + var key = keys[j]; + var val = obj[key]; + if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { + queue.push({ obj: obj, prop: key }); + refs.push(val); + } + } + } + + return compactQueue(queue); +}; + +var isRegExp = function isRegExp(obj) { + return Object.prototype.toString.call(obj) === '[object RegExp]'; +}; + +var isBuffer = function isBuffer(obj) { + if (obj === null || typeof obj === 'undefined') { + return false; + } + + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +}; + +module.exports = { + arrayToObject: arrayToObject, + assign: assign, + compact: compact, + decode: decode, + encode: encode, + isBuffer: isBuffer, + isRegExp: isRegExp, + merge: merge +}; + + /***/ }), /***/ 49273: @@ -320533,7 +321906,7 @@ exports.$ = Multipart var url = __nccwpck_require__(57310) -var qs = __nccwpck_require__(47457) +var qs = __nccwpck_require__(22760) var caseless = __nccwpck_require__(35684) var uuid = __nccwpck_require__(71435) var oauth = __nccwpck_require__(43248) @@ -320688,7 +322061,7 @@ exports.f = OAuth "use strict"; -var qs = __nccwpck_require__(47457) +var qs = __nccwpck_require__(22760) var querystring = __nccwpck_require__(63477) function Querystring (request) { @@ -321564,682 +322937,6 @@ module.exports = function(dst, src) { }; -/***/ }), - -/***/ 28321: -/***/ ((module) => { - -"use strict"; - - -var replace = String.prototype.replace; -var percentTwenties = /%20/g; - -module.exports = { - 'default': 'RFC3986', - formatters: { - RFC1738: function (value) { - return replace.call(value, percentTwenties, '+'); - }, - RFC3986: function (value) { - return String(value); - } - }, - RFC1738: 'RFC1738', - RFC3986: 'RFC3986' -}; - - -/***/ }), - -/***/ 47457: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var stringify = __nccwpck_require__(64021); -var parse = __nccwpck_require__(90693); -var formats = __nccwpck_require__(28321); - -module.exports = { - formats: formats, - parse: parse, - stringify: stringify -}; - - -/***/ }), - -/***/ 90693: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var utils = __nccwpck_require__(17409); - -var has = Object.prototype.hasOwnProperty; - -var defaults = { - allowDots: false, - allowPrototypes: false, - arrayLimit: 20, - decoder: utils.decode, - delimiter: '&', - depth: 5, - parameterLimit: 1000, - plainObjects: false, - strictNullHandling: false -}; - -var parseValues = function parseQueryStringValues(str, options) { - var obj = {}; - var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; - var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; - var parts = cleanStr.split(options.delimiter, limit); - - for (var i = 0; i < parts.length; ++i) { - var part = parts[i]; - - var bracketEqualsPos = part.indexOf(']='); - var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; - - var key, val; - if (pos === -1) { - key = options.decoder(part, defaults.decoder); - val = options.strictNullHandling ? null : ''; - } else { - key = options.decoder(part.slice(0, pos), defaults.decoder); - val = options.decoder(part.slice(pos + 1), defaults.decoder); - } - if (has.call(obj, key)) { - obj[key] = [].concat(obj[key]).concat(val); - } else { - obj[key] = val; - } - } - - return obj; -}; - -var parseObject = function (chain, val, options) { - var leaf = val; - - for (var i = chain.length - 1; i >= 0; --i) { - var obj; - var root = chain[i]; - - if (root === '[]' && options.parseArrays) { - obj = [].concat(leaf); - } else { - obj = options.plainObjects ? Object.create(null) : {}; - var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; - var index = parseInt(cleanRoot, 10); - if (!options.parseArrays && cleanRoot === '') { - obj = { 0: leaf }; - } else if ( - !isNaN(index) - && root !== cleanRoot - && String(index) === cleanRoot - && index >= 0 - && (options.parseArrays && index <= options.arrayLimit) - ) { - obj = []; - obj[index] = leaf; - } else if (cleanRoot !== '__proto__') { - obj[cleanRoot] = leaf; - } - } - - leaf = obj; - } - - return leaf; -}; - -var parseKeys = function parseQueryStringKeys(givenKey, val, options) { - if (!givenKey) { - return; - } - - // Transform dot notation to bracket notation - var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; - - // The regex chunks - - var brackets = /(\[[^[\]]*])/; - var child = /(\[[^[\]]*])/g; - - // Get the parent - - var segment = brackets.exec(key); - var parent = segment ? key.slice(0, segment.index) : key; - - // Stash the parent if it exists - - var keys = []; - if (parent) { - // If we aren't using plain objects, optionally prefix keys - // that would overwrite object prototype properties - if (!options.plainObjects && has.call(Object.prototype, parent)) { - if (!options.allowPrototypes) { - return; - } - } - - keys.push(parent); - } - - // Loop through children appending to the array until we hit depth - - var i = 0; - while ((segment = child.exec(key)) !== null && i < options.depth) { - i += 1; - if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { - if (!options.allowPrototypes) { - return; - } - } - keys.push(segment[1]); - } - - // If there's a remainder, just add whatever is left - - if (segment) { - keys.push('[' + key.slice(segment.index) + ']'); - } - - return parseObject(keys, val, options); -}; - -module.exports = function (str, opts) { - var options = opts ? utils.assign({}, opts) : {}; - - if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') { - throw new TypeError('Decoder has to be a function.'); - } - - options.ignoreQueryPrefix = options.ignoreQueryPrefix === true; - options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults.delimiter; - options.depth = typeof options.depth === 'number' ? options.depth : defaults.depth; - options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit; - options.parseArrays = options.parseArrays !== false; - options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults.decoder; - options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults.allowDots; - options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults.plainObjects; - options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults.allowPrototypes; - options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults.parameterLimit; - options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling; - - if (str === '' || str === null || typeof str === 'undefined') { - return options.plainObjects ? Object.create(null) : {}; - } - - var tempObj = typeof str === 'string' ? parseValues(str, options) : str; - var obj = options.plainObjects ? Object.create(null) : {}; - - // Iterate over the keys and setup the new object - - var keys = Object.keys(tempObj); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - var newObj = parseKeys(key, tempObj[key], options); - obj = utils.merge(obj, newObj, options); - } - - return utils.compact(obj); -}; - - -/***/ }), - -/***/ 64021: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var utils = __nccwpck_require__(17409); -var formats = __nccwpck_require__(28321); - -var arrayPrefixGenerators = { - brackets: function brackets(prefix) { - return prefix + '[]'; - }, - indices: function indices(prefix, key) { - return prefix + '[' + key + ']'; - }, - repeat: function repeat(prefix) { - return prefix; - } -}; - -var isArray = Array.isArray; -var push = Array.prototype.push; -var pushToArray = function (arr, valueOrArray) { - push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); -}; - -var toISO = Date.prototype.toISOString; - -var defaults = { - delimiter: '&', - encode: true, - encoder: utils.encode, - encodeValuesOnly: false, - serializeDate: function serializeDate(date) { - return toISO.call(date); - }, - skipNulls: false, - strictNullHandling: false -}; - -var stringify = function stringify( - object, - prefix, - generateArrayPrefix, - strictNullHandling, - skipNulls, - encoder, - filter, - sort, - allowDots, - serializeDate, - formatter, - encodeValuesOnly -) { - var obj = object; - if (typeof filter === 'function') { - obj = filter(prefix, obj); - } else if (obj instanceof Date) { - obj = serializeDate(obj); - } - - if (obj === null) { - if (strictNullHandling) { - return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder) : prefix; - } - - obj = ''; - } - - if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) { - if (encoder) { - var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder); - return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder))]; - } - return [formatter(prefix) + '=' + formatter(String(obj))]; - } - - var values = []; - - if (typeof obj === 'undefined') { - return values; - } - - var objKeys; - if (isArray(filter)) { - objKeys = filter; - } else { - var keys = Object.keys(obj); - objKeys = sort ? keys.sort(sort) : keys; - } - - for (var i = 0; i < objKeys.length; ++i) { - var key = objKeys[i]; - - if (skipNulls && obj[key] === null) { - continue; - } - - if (isArray(obj)) { - pushToArray(values, stringify( - obj[key], - generateArrayPrefix(prefix, key), - generateArrayPrefix, - strictNullHandling, - skipNulls, - encoder, - filter, - sort, - allowDots, - serializeDate, - formatter, - encodeValuesOnly - )); - } else { - pushToArray(values, stringify( - obj[key], - prefix + (allowDots ? '.' + key : '[' + key + ']'), - generateArrayPrefix, - strictNullHandling, - skipNulls, - encoder, - filter, - sort, - allowDots, - serializeDate, - formatter, - encodeValuesOnly - )); - } - } - - return values; -}; - -module.exports = function (object, opts) { - var obj = object; - var options = opts ? utils.assign({}, opts) : {}; - - if (options.encoder !== null && typeof options.encoder !== 'undefined' && typeof options.encoder !== 'function') { - throw new TypeError('Encoder has to be a function.'); - } - - var delimiter = typeof options.delimiter === 'undefined' ? defaults.delimiter : options.delimiter; - var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling; - var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults.skipNulls; - var encode = typeof options.encode === 'boolean' ? options.encode : defaults.encode; - var encoder = typeof options.encoder === 'function' ? options.encoder : defaults.encoder; - var sort = typeof options.sort === 'function' ? options.sort : null; - var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots; - var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults.serializeDate; - var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults.encodeValuesOnly; - if (typeof options.format === 'undefined') { - options.format = formats['default']; - } else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) { - throw new TypeError('Unknown format option provided.'); - } - var formatter = formats.formatters[options.format]; - var objKeys; - var filter; - - if (typeof options.filter === 'function') { - filter = options.filter; - obj = filter('', obj); - } else if (isArray(options.filter)) { - filter = options.filter; - objKeys = filter; - } - - var keys = []; - - if (typeof obj !== 'object' || obj === null) { - return ''; - } - - var arrayFormat; - if (options.arrayFormat in arrayPrefixGenerators) { - arrayFormat = options.arrayFormat; - } else if ('indices' in options) { - arrayFormat = options.indices ? 'indices' : 'repeat'; - } else { - arrayFormat = 'indices'; - } - - var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; - - if (!objKeys) { - objKeys = Object.keys(obj); - } - - if (sort) { - objKeys.sort(sort); - } - - for (var i = 0; i < objKeys.length; ++i) { - var key = objKeys[i]; - - if (skipNulls && obj[key] === null) { - continue; - } - pushToArray(keys, stringify( - obj[key], - key, - generateArrayPrefix, - strictNullHandling, - skipNulls, - encode ? encoder : null, - filter, - sort, - allowDots, - serializeDate, - formatter, - encodeValuesOnly - )); - } - - var joined = keys.join(delimiter); - var prefix = options.addQueryPrefix === true ? '?' : ''; - - return joined.length > 0 ? prefix + joined : ''; -}; - - -/***/ }), - -/***/ 17409: -/***/ ((module) => { - -"use strict"; - - -var has = Object.prototype.hasOwnProperty; - -var hexTable = (function () { - var array = []; - for (var i = 0; i < 256; ++i) { - array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); - } - - return array; -}()); - -var compactQueue = function compactQueue(queue) { - var obj; - - while (queue.length) { - var item = queue.pop(); - obj = item.obj[item.prop]; - - if (Array.isArray(obj)) { - var compacted = []; - - for (var j = 0; j < obj.length; ++j) { - if (typeof obj[j] !== 'undefined') { - compacted.push(obj[j]); - } - } - - item.obj[item.prop] = compacted; - } - } - - return obj; -}; - -var arrayToObject = function arrayToObject(source, options) { - var obj = options && options.plainObjects ? Object.create(null) : {}; - for (var i = 0; i < source.length; ++i) { - if (typeof source[i] !== 'undefined') { - obj[i] = source[i]; - } - } - - return obj; -}; - -var merge = function merge(target, source, options) { - if (!source) { - return target; - } - - if (typeof source !== 'object') { - if (Array.isArray(target)) { - target.push(source); - } else if (target && typeof target === 'object') { - if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) { - target[source] = true; - } - } else { - return [target, source]; - } - - return target; - } - - if (!target || typeof target !== 'object') { - return [target].concat(source); - } - - var mergeTarget = target; - if (Array.isArray(target) && !Array.isArray(source)) { - mergeTarget = arrayToObject(target, options); - } - - if (Array.isArray(target) && Array.isArray(source)) { - source.forEach(function (item, i) { - if (has.call(target, i)) { - var targetItem = target[i]; - if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { - target[i] = merge(targetItem, item, options); - } else { - target.push(item); - } - } else { - target[i] = item; - } - }); - return target; - } - - return Object.keys(source).reduce(function (acc, key) { - var value = source[key]; - - if (has.call(acc, key)) { - acc[key] = merge(acc[key], value, options); - } else { - acc[key] = value; - } - return acc; - }, mergeTarget); -}; - -var assign = function assignSingleSource(target, source) { - return Object.keys(source).reduce(function (acc, key) { - acc[key] = source[key]; - return acc; - }, target); -}; - -var decode = function (str) { - try { - return decodeURIComponent(str.replace(/\+/g, ' ')); - } catch (e) { - return str; - } -}; - -var encode = function encode(str) { - // This code was originally written by Brian White (mscdex) for the io.js core querystring library. - // It has been adapted here for stricter adherence to RFC 3986 - if (str.length === 0) { - return str; - } - - var string = typeof str === 'string' ? str : String(str); - - var out = ''; - for (var i = 0; i < string.length; ++i) { - var c = string.charCodeAt(i); - - if ( - c === 0x2D // - - || c === 0x2E // . - || c === 0x5F // _ - || c === 0x7E // ~ - || (c >= 0x30 && c <= 0x39) // 0-9 - || (c >= 0x41 && c <= 0x5A) // a-z - || (c >= 0x61 && c <= 0x7A) // A-Z - ) { - out += string.charAt(i); - continue; - } - - if (c < 0x80) { - out = out + hexTable[c]; - continue; - } - - if (c < 0x800) { - out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); - continue; - } - - if (c < 0xD800 || c >= 0xE000) { - out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); - continue; - } - - i += 1; - c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); - /* eslint operator-linebreak: [2, "before"] */ - out += hexTable[0xF0 | (c >> 18)] - + hexTable[0x80 | ((c >> 12) & 0x3F)] - + hexTable[0x80 | ((c >> 6) & 0x3F)] - + hexTable[0x80 | (c & 0x3F)]; - } - - return out; -}; - -var compact = function compact(value) { - var queue = [{ obj: { o: value }, prop: 'o' }]; - var refs = []; - - for (var i = 0; i < queue.length; ++i) { - var item = queue[i]; - var obj = item.obj[item.prop]; - - var keys = Object.keys(obj); - for (var j = 0; j < keys.length; ++j) { - var key = keys[j]; - var val = obj[key]; - if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { - queue.push({ obj: obj, prop: key }); - refs.push(val); - } - } - } - - return compactQueue(queue); -}; - -var isRegExp = function isRegExp(obj) { - return Object.prototype.toString.call(obj) === '[object RegExp]'; -}; - -var isBuffer = function isBuffer(obj) { - if (obj === null || typeof obj === 'undefined') { - return false; - } - - return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); -}; - -module.exports = { - arrayToObject: arrayToObject, - assign: assign, - compact: compact, - decode: decode, - encode: encode, - isBuffer: isBuffer, - isRegExp: isRegExp, - merge: merge -}; - - /***/ }), /***/ 67087: @@ -324175,526 +324872,1731 @@ exports.codec = codec; /***/ }), -/***/ 14959: +/***/ 21867: +/***/ ((module, exports, __nccwpck_require__) => { + +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = __nccwpck_require__(14300) +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.prototype = Object.create(Buffer.prototype) + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} + + +/***/ }), + +/***/ 15118: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const assert = __nccwpck_require__(39491) -const path = __nccwpck_require__(71017) -const fs = __nccwpck_require__(57147) -let glob = undefined -try { - glob = __nccwpck_require__(91957) -} catch (_err) { - // treat glob as optional. +"use strict"; +/* eslint-disable node/no-deprecated-api */ + + + +var buffer = __nccwpck_require__(14300) +var Buffer = buffer.Buffer + +var safer = {} + +var key + +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) + } } -const defaultGlobOpts = { - nosort: true, - silent: true +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 + } } -// for EMFILE handling -let timeout = 0 +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 = safer + + +/***/ }), + +/***/ 72043: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +;(function (sax) { // wrapper for non-node envs + sax.parser = function (strict, opt) { return new SAXParser(strict, opt) } + sax.SAXParser = SAXParser + sax.SAXStream = SAXStream + sax.createStream = createStream + + // When we pass the MAX_BUFFER_LENGTH position, start checking for buffer overruns. + // When we check, schedule the next check for MAX_BUFFER_LENGTH - (max(buffer lengths)), + // since that's the earliest that a buffer overrun could occur. This way, checks are + // as rare as required, but as often as necessary to ensure never crossing this bound. + // Furthermore, buffers are only tested at most once per write(), so passing a very + // large string into write() might have undesirable effects, but this is manageable by + // the caller, so it is assumed to be safe. Thus, a call to write() may, in the extreme + // edge case, result in creating at most one complete copy of the string passed in. + // Set to Infinity to have unlimited buffers. + sax.MAX_BUFFER_LENGTH = 64 * 1024 -const isWindows = (process.platform === "win32") + var buffers = [ + 'comment', 'sgmlDecl', 'textNode', 'tagName', 'doctype', + 'procInstName', 'procInstBody', 'entity', 'attribName', + 'attribValue', 'cdata', 'script' + ] -const defaults = options => { - const methods = [ - 'unlink', - 'chmod', - 'stat', - 'lstat', - 'rmdir', - 'readdir' + sax.EVENTS = [ + 'text', + 'processinginstruction', + 'sgmldeclaration', + 'doctype', + 'comment', + 'opentagstart', + 'attribute', + 'opentag', + 'closetag', + 'opencdata', + 'cdata', + 'closecdata', + 'error', + 'end', + 'ready', + 'script', + 'opennamespace', + 'closenamespace' ] - methods.forEach(m => { - options[m] = options[m] || fs[m] - m = m + 'Sync' - options[m] = options[m] || fs[m] + + function SAXParser (strict, opt) { + if (!(this instanceof SAXParser)) { + return new SAXParser(strict, opt) + } + + var parser = this + clearBuffers(parser) + parser.q = parser.c = '' + parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH + parser.opt = opt || {} + parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags + parser.looseCase = parser.opt.lowercase ? 'toLowerCase' : 'toUpperCase' + parser.tags = [] + parser.closed = parser.closedRoot = parser.sawRoot = false + parser.tag = parser.error = null + parser.strict = !!strict + parser.noscript = !!(strict || parser.opt.noscript) + parser.state = S.BEGIN + parser.strictEntities = parser.opt.strictEntities + parser.ENTITIES = parser.strictEntities ? Object.create(sax.XML_ENTITIES) : Object.create(sax.ENTITIES) + parser.attribList = [] + + // namespaces form a prototype chain. + // it always points at the current tag, + // which protos to its parent tag. + if (parser.opt.xmlns) { + parser.ns = Object.create(rootNS) + } + + // mostly just for error reporting + parser.trackPosition = parser.opt.position !== false + if (parser.trackPosition) { + parser.position = parser.line = parser.column = 0 + } + emit(parser, 'onready') + } + + if (!Object.create) { + Object.create = function (o) { + function F () {} + F.prototype = o + var newf = new F() + return newf + } + } + + if (!Object.keys) { + Object.keys = function (o) { + var a = [] + for (var i in o) if (o.hasOwnProperty(i)) a.push(i) + return a + } + } + + function checkBufferLength (parser) { + var maxAllowed = Math.max(sax.MAX_BUFFER_LENGTH, 10) + var maxActual = 0 + for (var i = 0, l = buffers.length; i < l; i++) { + var len = parser[buffers[i]].length + if (len > maxAllowed) { + // Text/cdata nodes can get big, and since they're buffered, + // we can get here under normal conditions. + // Avoid issues by emitting the text node now, + // so at least it won't get any bigger. + switch (buffers[i]) { + case 'textNode': + closeText(parser) + break + + case 'cdata': + emitNode(parser, 'oncdata', parser.cdata) + parser.cdata = '' + break + + case 'script': + emitNode(parser, 'onscript', parser.script) + parser.script = '' + break + + default: + error(parser, 'Max buffer length exceeded: ' + buffers[i]) + } + } + maxActual = Math.max(maxActual, len) + } + // schedule the next check for the earliest possible buffer overrun. + var m = sax.MAX_BUFFER_LENGTH - maxActual + parser.bufferCheckPosition = m + parser.position + } + + function clearBuffers (parser) { + for (var i = 0, l = buffers.length; i < l; i++) { + parser[buffers[i]] = '' + } + } + + function flushBuffers (parser) { + closeText(parser) + if (parser.cdata !== '') { + emitNode(parser, 'oncdata', parser.cdata) + parser.cdata = '' + } + if (parser.script !== '') { + emitNode(parser, 'onscript', parser.script) + parser.script = '' + } + } + + SAXParser.prototype = { + end: function () { end(this) }, + write: write, + resume: function () { this.error = null; return this }, + close: function () { return this.write(null) }, + flush: function () { flushBuffers(this) } + } + + var Stream + try { + Stream = (__nccwpck_require__(12781).Stream) + } catch (ex) { + Stream = function () {} + } + + var streamWraps = sax.EVENTS.filter(function (ev) { + return ev !== 'error' && ev !== 'end' }) - options.maxBusyTries = options.maxBusyTries || 3 - options.emfileWait = options.emfileWait || 1000 - if (options.glob === false) { - options.disableGlob = true + function createStream (strict, opt) { + return new SAXStream(strict, opt) } - if (options.disableGlob !== true && glob === undefined) { - throw Error('glob dependency not found, set `options.disableGlob = true` if intentional') + + function SAXStream (strict, opt) { + if (!(this instanceof SAXStream)) { + return new SAXStream(strict, opt) + } + + Stream.apply(this) + + this._parser = new SAXParser(strict, opt) + this.writable = true + this.readable = true + + var me = this + + this._parser.onend = function () { + me.emit('end') + } + + this._parser.onerror = function (er) { + me.emit('error', er) + + // if didn't throw, then means error was handled. + // go ahead and clear error, so we can write again. + me._parser.error = null + } + + this._decoder = null + + streamWraps.forEach(function (ev) { + Object.defineProperty(me, 'on' + ev, { + get: function () { + return me._parser['on' + ev] + }, + set: function (h) { + if (!h) { + me.removeAllListeners(ev) + me._parser['on' + ev] = h + return h + } + me.on(ev, h) + }, + enumerable: true, + configurable: false + }) + }) } - options.disableGlob = options.disableGlob || false - options.glob = options.glob || defaultGlobOpts -} -const rimraf = (p, options, cb) => { - if (typeof options === 'function') { - cb = options - options = {} + SAXStream.prototype = Object.create(Stream.prototype, { + constructor: { + value: SAXStream + } + }) + + SAXStream.prototype.write = function (data) { + if (typeof Buffer === 'function' && + typeof Buffer.isBuffer === 'function' && + Buffer.isBuffer(data)) { + if (!this._decoder) { + var SD = (__nccwpck_require__(71576).StringDecoder) + this._decoder = new SD('utf8') + } + data = this._decoder.write(data) + } + + this._parser.write(data.toString()) + this.emit('data', data) + return true + } + + SAXStream.prototype.end = function (chunk) { + if (chunk && chunk.length) { + this.write(chunk) + } + this._parser.end() + return true + } + + SAXStream.prototype.on = function (ev, handler) { + var me = this + if (!me._parser['on' + ev] && streamWraps.indexOf(ev) !== -1) { + me._parser['on' + ev] = function () { + var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments) + args.splice(0, 0, ev) + me.emit.apply(me, args) + } + } + + return Stream.prototype.on.call(me, ev, handler) + } + + // this really needs to be replaced with character classes. + // XML allows all manner of ridiculous numbers and digits. + var CDATA = '[CDATA[' + var DOCTYPE = 'DOCTYPE' + var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace' + var XMLNS_NAMESPACE = 'http://www.w3.org/2000/xmlns/' + var rootNS = { xml: XML_NAMESPACE, xmlns: XMLNS_NAMESPACE } + + // http://www.w3.org/TR/REC-xml/#NT-NameStartChar + // This implementation works on strings, a single character at a time + // as such, it cannot ever support astral-plane characters (10000-EFFFF) + // without a significant breaking change to either this parser, or the + // JavaScript language. Implementation of an emoji-capable xml parser + // is left as an exercise for the reader. + var nameStart = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/ + + var nameBody = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/ + + var entityStart = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/ + var entityBody = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/ + + function isWhitespace (c) { + return c === ' ' || c === '\n' || c === '\r' || c === '\t' + } + + function isQuote (c) { + return c === '"' || c === '\'' + } + + function isAttribEnd (c) { + return c === '>' || isWhitespace(c) + } + + function isMatch (regex, c) { + return regex.test(c) + } + + function notMatch (regex, c) { + return !isMatch(regex, c) + } + + var S = 0 + sax.STATE = { + BEGIN: S++, // leading byte order mark or whitespace + BEGIN_WHITESPACE: S++, // leading whitespace + TEXT: S++, // general stuff + TEXT_ENTITY: S++, // & and such. + OPEN_WAKA: S++, // < + SGML_DECL: S++, // + SCRIPT: S++, //