How to use stringifyJsonBody method in Cypress

Best JavaScript code snippet using cypress

index.compiled.js

Source:index.compiled.js Github

copy

Full Screen

1(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){2(function (process,global){(function (){3(function (global, factory) {4 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :5 typeof define === 'function' && define.amd ? define(['exports'], factory) :6 (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.MockServiceWorker = {}));7}(this, (function (exports) { 'use strict';8 var statuses = {9 "100": "Continue",10 "101": "Switching Protocols",11 "102": "Processing",12 "103": "Early Hints",13 "200": "OK",14 "201": "Created",15 "202": "Accepted",16 "203": "Non-Authoritative Information",17 "204": "No Content",18 "205": "Reset Content",19 "206": "Partial Content",20 "207": "Multi-Status",21 "208": "Already Reported",22 "226": "IM Used",23 "300": "Multiple Choices",24 "301": "Moved Permanently",25 "302": "Found",26 "303": "See Other",27 "304": "Not Modified",28 "305": "Use Proxy",29 "307": "Temporary Redirect",30 "308": "Permanent Redirect",31 "400": "Bad Request",32 "401": "Unauthorized",33 "402": "Payment Required",34 "403": "Forbidden",35 "404": "Not Found",36 "405": "Method Not Allowed",37 "406": "Not Acceptable",38 "407": "Proxy Authentication Required",39 "408": "Request Timeout",40 "409": "Conflict",41 "410": "Gone",42 "411": "Length Required",43 "412": "Precondition Failed",44 "413": "Payload Too Large",45 "414": "URI Too Long",46 "415": "Unsupported Media Type",47 "416": "Range Not Satisfiable",48 "417": "Expectation Failed",49 "418": "I'm a Teapot",50 "421": "Misdirected Request",51 "422": "Unprocessable Entity",52 "423": "Locked",53 "424": "Failed Dependency",54 "425": "Too Early",55 "426": "Upgrade Required",56 "428": "Precondition Required",57 "429": "Too Many Requests",58 "431": "Request Header Fields Too Large",59 "451": "Unavailable For Legal Reasons",60 "500": "Internal Server Error",61 "501": "Not Implemented",62 "502": "Bad Gateway",63 "503": "Service Unavailable",64 "504": "Gateway Timeout",65 "505": "HTTP Version Not Supported",66 "506": "Variant Also Negotiates",67 "507": "Insufficient Storage",68 "508": "Loop Detected",69 "509": "Bandwidth Limit Exceeded",70 "510": "Not Extended",71 "511": "Network Authentication Required"72 };73 const status = (statusCode, statusText) => {74 return (res) => {75 res.status = statusCode;76 res.statusText =77 statusText || statuses[String(statusCode)];78 return res;79 };80 };81 var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};82 function createCommonjsModule(fn, basedir, module) {83 return module = {84 path: basedir,85 exports: {},86 require: function (path, base) {87 return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);88 }89 }, fn(module, module.exports), module.exports;90 }91 function commonjsRequire () {92 throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');93 }94 var Headers_1 = createCommonjsModule(function (module, exports) {95 Object.defineProperty(exports, "__esModule", { value: true });96 var HEADERS_INVALID_CHARACTERS = /[^a-z0-9\-#$%&'*+.^_`|~]/i;97 var Headers = /** @class */ (function () {98 function Headers(headers) {99 var _this = this;100 this.map = {};101 if ((headers === null || headers === void 0 ? void 0 : headers.constructor.name) === 'Headers') {102 headers.forEach(function (value, name) {103 _this.append(name, value);104 }, this);105 }106 else if (Array.isArray(headers)) {107 headers.forEach(function (_a) {108 var name = _a[0], value = _a[1];109 _this.append(name, Array.isArray(value) ? value.join(', ') : value);110 });111 }112 else if (headers) {113 Object.getOwnPropertyNames(headers).forEach(function (name) {114 _this.append(name, headers[name]);115 });116 }117 }118 /**119 * Sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist.120 */121 Headers.prototype.set = function (name, value) {122 this.map[this.normalizeName(name)] = this.normalizeValue(value);123 };124 /**125 * Appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist.126 */127 Headers.prototype.append = function (name, value) {128 name = this.normalizeName(name);129 value = this.normalizeValue(value);130 this.map[name] = this.has(name) ? this.map[name] + ", " + value : value;131 };132 /**133 * Deletes a header from the `Headers` object.134 */135 Headers.prototype.delete = function (name) {136 delete this.map[this.normalizeName(name)];137 return this;138 };139 /**140 * Returns a `ByteString` sequence of all the values of a header with a given name.141 */142 Headers.prototype.get = function (name) {143 return this.map[this.normalizeName(name)] || null;144 };145 /**146 * Returns the map of all headers in a `Headers` object.147 */148 Headers.prototype.getAllHeaders = function () {149 return this.map;150 };151 /**152 * Returns a boolean stating whether a `Headers` object contains a certain header.153 */154 Headers.prototype.has = function (name) {155 return this.map.hasOwnProperty(this.normalizeName(name));156 };157 Headers.prototype.forEach = function (callback, thisArg) {158 for (var name_1 in this.map) {159 if (this.map.hasOwnProperty(name_1)) {160 callback.call(thisArg, this.map[name_1], name_1, this);161 }162 }163 };164 Headers.prototype.normalizeName = function (name) {165 if (typeof name !== 'string') {166 name = String(name);167 }168 if (HEADERS_INVALID_CHARACTERS.test(name) || name.trim() === '') {169 throw new TypeError('Invalid character in header field name');170 }171 return name.toLowerCase();172 };173 Headers.prototype.normalizeValue = function (value) {174 if (typeof value !== 'string') {175 value = String(value);176 }177 return value;178 };179 return Headers;180 }());181 exports.Headers = Headers;182 });183 var headersToList_1 = createCommonjsModule(function (module, exports) {184 Object.defineProperty(exports, "__esModule", { value: true });185 function headersToList(headers) {186 var headersList = [];187 headers.forEach(function (value, name) {188 var resolvedValue = value.includes(',')189 ? value.split(',').map(function (v) { return v.trim(); })190 : value;191 headersList.push([name, resolvedValue]);192 });193 return headersList;194 }195 exports.headersToList = headersToList;196 });197 var headersToObject_1 = createCommonjsModule(function (module, exports) {198 Object.defineProperty(exports, "__esModule", { value: true });199 // List of headers that cannot have multiple values,200 // while potentially having a comma in their single value.201 var singleValueHeaders = ['user-agent'];202 /**203 * Converts a given `Headers` instance into a plain object.204 * Respects headers with multiple values.205 */206 function headersToObject(headers) {207 var headersObject = {};208 headers.forEach(function (value, name) {209 var isMultiValue = !singleValueHeaders.includes(name.toLowerCase()) && value.includes(',');210 headersObject[name] = isMultiValue211 ? value.split(',').map(function (s) { return s.trim(); })212 : value;213 });214 return headersObject;215 }216 exports.headersToObject = headersToObject;217 });218 var stringToHeaders_1 = createCommonjsModule(function (module, exports) {219 Object.defineProperty(exports, "__esModule", { value: true });220 /**221 * Converts a string representation of headers (i.e. from XMLHttpRequest)222 * to a new `Headers` instance.223 */224 function stringToHeaders(str) {225 var lines = str.trim().split(/[\r\n]+/);226 return lines.reduce(function (headers, line) {227 var parts = line.split(': ');228 var name = parts.shift();229 var value = parts.join(': ');230 headers.append(name, value);231 return headers;232 }, new Headers());233 }234 exports.stringToHeaders = stringToHeaders;235 });236 var listToHeaders_1 = createCommonjsModule(function (module, exports) {237 Object.defineProperty(exports, "__esModule", { value: true });238 function listToHeaders(list) {239 var headers = new Headers();240 list.forEach(function (_a) {241 var name = _a[0], value = _a[1];242 var values = [].concat(value);243 values.forEach(function (value) {244 headers.append(name, value);245 });246 });247 return headers;248 }249 exports.listToHeaders = listToHeaders;250 });251 var reduceHeadersObject_1 = createCommonjsModule(function (module, exports) {252 Object.defineProperty(exports, "__esModule", { value: true });253 /**254 * Reduces given headers object instnace.255 */256 function reduceHeadersObject(headers, reducer, initialState) {257 return Object.keys(headers).reduce(function (nextHeaders, name) {258 return reducer(nextHeaders, name, headers[name]);259 }, initialState);260 }261 exports.reduceHeadersObject = reduceHeadersObject;262 });263 var objectToHeaders_1 = createCommonjsModule(function (module, exports) {264 Object.defineProperty(exports, "__esModule", { value: true });265 /**266 * Converts a given headers object to a new `Headers` instance.267 */268 function objectToHeaders(obj) {269 return reduceHeadersObject_1.reduceHeadersObject(obj, function (headers, name, value) {270 var values = [].concat(value);271 values.forEach(function (value) {272 headers.append(name, value);273 });274 return headers;275 }, new Headers());276 }277 exports.objectToHeaders = objectToHeaders;278 });279 var flattenHeadersList_1 = createCommonjsModule(function (module, exports) {280 Object.defineProperty(exports, "__esModule", { value: true });281 function flattenHeadersList(list) {282 return list.map(function (_a) {283 var name = _a[0], values = _a[1];284 return [name, [].concat(values).join('; ')];285 });286 }287 exports.flattenHeadersList = flattenHeadersList;288 });289 var flattenHeadersObject_1 = createCommonjsModule(function (module, exports) {290 Object.defineProperty(exports, "__esModule", { value: true });291 function flattenHeadersObject(obj) {292 return reduceHeadersObject_1.reduceHeadersObject(obj, function (headers, name, value) {293 headers[name] = [].concat(value).join('; ');294 return headers;295 }, {});296 }297 exports.flattenHeadersObject = flattenHeadersObject;298 });299 var lib = createCommonjsModule(function (module, exports) {300 Object.defineProperty(exports, "__esModule", { value: true });301 exports.Headers = Headers_1.Headers;302 exports.headersToList = headersToList_1.headersToList;303 exports.headersToObject = headersToObject_1.headersToObject;304 exports.stringToHeaders = stringToHeaders_1.stringToHeaders;305 exports.listToHeaders = listToHeaders_1.listToHeaders;306 exports.objectToHeaders = objectToHeaders_1.objectToHeaders;307 exports.reduceHeadersObject = reduceHeadersObject_1.reduceHeadersObject;308 exports.flattenHeadersList = flattenHeadersList_1.flattenHeadersList;309 exports.flattenHeadersObject = flattenHeadersObject_1.flattenHeadersObject;310 });311 function set(...args) {312 return (res) => {313 const [name, value] = args;314 if (typeof name === 'string') {315 res.headers.append(name, value);316 }317 else {318 const headers = lib.objectToHeaders(name);319 headers.forEach((value, name) => {320 res.headers.append(name, value);321 });322 }323 return res;324 };325 }326 /*!327 * cookie328 * Copyright(c) 2012-2014 Roman Shtylman329 * Copyright(c) 2015 Douglas Christopher Wilson330 * MIT Licensed331 */332 /**333 * Module exports.334 * @public335 */336 var parse_1 = parse;337 var serialize_1 = serialize;338 /**339 * Module variables.340 * @private341 */342 var decode = decodeURIComponent;343 var encode = encodeURIComponent;344 var pairSplitRegExp = /; */;345 /**346 * RegExp to match field-content in RFC 7230 sec 3.2347 *348 * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]349 * field-vchar = VCHAR / obs-text350 * obs-text = %x80-FF351 */352 var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;353 /**354 * Parse a cookie header.355 *356 * Parse the given cookie header string into an object357 * The object has the various cookies as keys(names) => values358 *359 * @param {string} str360 * @param {object} [options]361 * @return {object}362 * @public363 */364 function parse(str, options) {365 if (typeof str !== 'string') {366 throw new TypeError('argument str must be a string');367 }368 var obj = {};369 var opt = options || {};370 var pairs = str.split(pairSplitRegExp);371 var dec = opt.decode || decode;372 for (var i = 0; i < pairs.length; i++) {373 var pair = pairs[i];374 var eq_idx = pair.indexOf('=');375 // skip things that don't look like key=value376 if (eq_idx < 0) {377 continue;378 }379 var key = pair.substr(0, eq_idx).trim();380 var val = pair.substr(++eq_idx, pair.length).trim();381 // quoted values382 if ('"' == val[0]) {383 val = val.slice(1, -1);384 }385 // only assign once386 if (undefined == obj[key]) {387 obj[key] = tryDecode(val, dec);388 }389 }390 return obj;391 }392 /**393 * Serialize data into a cookie header.394 *395 * Serialize the a name value pair into a cookie string suitable for396 * http headers. An optional options object specified cookie parameters.397 *398 * serialize('foo', 'bar', { httpOnly: true })399 * => "foo=bar; httpOnly"400 *401 * @param {string} name402 * @param {string} val403 * @param {object} [options]404 * @return {string}405 * @public406 */407 function serialize(name, val, options) {408 var opt = options || {};409 var enc = opt.encode || encode;410 if (typeof enc !== 'function') {411 throw new TypeError('option encode is invalid');412 }413 if (!fieldContentRegExp.test(name)) {414 throw new TypeError('argument name is invalid');415 }416 var value = enc(val);417 if (value && !fieldContentRegExp.test(value)) {418 throw new TypeError('argument val is invalid');419 }420 var str = name + '=' + value;421 if (null != opt.maxAge) {422 var maxAge = opt.maxAge - 0;423 if (isNaN(maxAge) || !isFinite(maxAge)) {424 throw new TypeError('option maxAge is invalid')425 }426 str += '; Max-Age=' + Math.floor(maxAge);427 }428 if (opt.domain) {429 if (!fieldContentRegExp.test(opt.domain)) {430 throw new TypeError('option domain is invalid');431 }432 str += '; Domain=' + opt.domain;433 }434 if (opt.path) {435 if (!fieldContentRegExp.test(opt.path)) {436 throw new TypeError('option path is invalid');437 }438 str += '; Path=' + opt.path;439 }440 if (opt.expires) {441 if (typeof opt.expires.toUTCString !== 'function') {442 throw new TypeError('option expires is invalid');443 }444 str += '; Expires=' + opt.expires.toUTCString();445 }446 if (opt.httpOnly) {447 str += '; HttpOnly';448 }449 if (opt.secure) {450 str += '; Secure';451 }452 if (opt.sameSite) {453 var sameSite = typeof opt.sameSite === 'string'454 ? opt.sameSite.toLowerCase() : opt.sameSite;455 switch (sameSite) {456 case true:457 str += '; SameSite=Strict';458 break;459 case 'lax':460 str += '; SameSite=Lax';461 break;462 case 'strict':463 str += '; SameSite=Strict';464 break;465 case 'none':466 str += '; SameSite=None';467 break;468 default:469 throw new TypeError('option sameSite is invalid');470 }471 }472 return str;473 }474 /**475 * Try decoding a string using a decoding function.476 *477 * @param {string} str478 * @param {function} decode479 * @private480 */481 function tryDecode(str, decode) {482 try {483 return decode(str);484 } catch (e) {485 return str;486 }487 }488 /**489 * Sets a given cookie on the response.490 * @example491 * res(cookie('name', 'value'))492 */493 const cookie = (name, value, options) => {494 return (res) => {495 const serializedCookie = serialize_1(name, value, options);496 res.headers.set('Set-Cookie', serializedCookie);497 if (typeof document !== 'undefined') {498 document.cookie = serializedCookie;499 }500 return res;501 };502 };503 /**504 * Sets the body of the response without any `Content-Type` header.505 * @example506 * res(body('message'))507 */508 const body = (value) => {509 return (res) => {510 res.body = value;511 return res;512 };513 };514 /**515 * Determines if the given value is an object.516 */517 function isObject(value) {518 return value != null && typeof value === 'object' && !Array.isArray(value);519 }520 /**521 * Deeply merges two given objects with the right one522 * having a priority during property assignment.523 */524 function mergeRight(left, right) {525 return Object.entries(right).reduce((result, [key, rightValue]) => {526 const leftValue = result[key];527 if (Array.isArray(leftValue) && Array.isArray(rightValue)) {528 result[key] = leftValue.concat(rightValue);529 return result;530 }531 if (isObject(leftValue) && isObject(rightValue)) {532 result[key] = mergeRight(leftValue, rightValue);533 return result;534 }535 result[key] = rightValue;536 return result;537 }, Object.assign({}, left));538 }539 /**540 * Sets the given value as the JSON body of the response.541 * @example542 * res(json({ key: 'value' }))543 * res(json('Some string'))544 * res(json([1, '2', false, { ok: true }]))545 */546 const json = (body, { merge = false } = {}) => {547 return (res) => {548 res.headers.set('Content-Type', 'application/json');549 res.body = merge ? mergeRight(res.body || {}, body) : body;550 return res;551 };552 };553 /**554 * Returns a GraphQL body payload.555 */556 const data = (payload) => {557 return json({ data: payload }, { merge: true });558 };559 /**560 * Returns a boolean indicating if the current process is running in NodeJS environment.561 * @see https://github.com/mswjs/msw/pull/255562 */563 function isNodeProcess() {564 // Check browser environment.565 if (typeof global !== 'object') {566 return false;567 }568 // Check nodejs or React Native environment.569 if (Object.prototype.toString.call(global.process) === '[object process]' ||570 navigator.product === 'ReactNative') {571 return true;572 }573 }574 const MIN_SERVER_RESPONSE_TIME = 100;575 const MAX_SERVER_RESPONSE_TIME = 400;576 const NODE_SERVER_RESPONSE_TIME = 5;577 const getRandomServerResponseTime = () => {578 if (isNodeProcess()) {579 return NODE_SERVER_RESPONSE_TIME;580 }581 return Math.floor(Math.random() * (MAX_SERVER_RESPONSE_TIME - MIN_SERVER_RESPONSE_TIME) +582 MIN_SERVER_RESPONSE_TIME);583 };584 /**585 * Delays the current response for the given duration (in ms)586 * @example587 * res(delay()) // realistic server response time588 * res(delay(1500)) // explicit response delay duration589 */590 const delay = (durationMs) => {591 return (res) => {592 res.delay = durationMs !== null && durationMs !== void 0 ? durationMs : getRandomServerResponseTime();593 return res;594 };595 };596 /**597 * Sets a given list of GraphQL errors on the mocked response.598 */599 const errors = (errorsList) => {600 if (errorsList == null) {601 return (res) => res;602 }603 return json({ errors: errorsList }, { merge: true });604 };605 const useFetch = isNodeProcess() ? require('node-fetch') : window.fetch;606 const augmentRequestInit = (requestInit) => {607 const headers = new lib.Headers(requestInit.headers);608 headers.set('x-msw-bypass', 'true');609 return Object.assign(Object.assign({}, requestInit), { headers: headers.getAllHeaders() });610 };611 const createFetchRequestParameters = (input) => {612 const { body, method } = input;613 const requestParameters = Object.assign(Object.assign({}, input), { body: undefined });614 if (['GET', 'HEAD'].includes(method)) {615 return requestParameters;616 }617 requestParameters.body =618 typeof body === 'object' ? JSON.stringify(body) : body;619 return requestParameters;620 };621 /**622 * Wrapper around the native `window.fetch()` function that performs623 * a request bypassing MSW. Requests performed using624 * this function will never be mocked.625 */626 const fetch = (input, requestInit = {}) => {627 // Keep the default `window.fetch()` call signature628 if (typeof input === 'string') {629 return useFetch(input, augmentRequestInit(requestInit));630 }631 const requestParameters = createFetchRequestParameters(input);632 const compliantRequest = augmentRequestInit(requestParameters);633 return useFetch(input.url.href, compliantRequest);634 };635 /**636 * Sets a given text as a "Cotent-Type: text/plain" body of the response.637 * @example638 * res(text('message'))639 */640 const text = (body) => {641 return (res) => {642 res.headers.set('Content-Type', 'text/plain');643 res.body = body;644 return res;645 };646 };647 /**648 * Sets the given XML as the body of the response.649 * @example650 * res(xml('<key>value</key>'))651 */652 const xml = (body) => {653 return (res) => {654 res.headers.set('Content-Type', 'text/xml');655 res.body = body;656 return res;657 };658 };659 var index = /*#__PURE__*/Object.freeze({660 __proto__: null,661 status: status,662 set: set,663 cookie: cookie,664 body: body,665 data: data,666 delay: delay,667 errors: errors,668 fetch: fetch,669 json: json,670 text: text,671 xml: xml672 });673 /*! *****************************************************************************674 Copyright (c) Microsoft Corporation. All rights reserved.675 Licensed under the Apache License, Version 2.0 (the "License"); you may not use676 this file except in compliance with the License. You may obtain a copy of the677 License at http://www.apache.org/licenses/LICENSE-2.0678 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY679 KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED680 WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,681 MERCHANTABLITY OR NON-INFRINGEMENT.682 See the Apache Version 2.0 License for specific language governing permissions683 and limitations under the License.684 ***************************************************************************** */685 function __awaiter(thisArg, _arguments, P, generator) {686 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }687 return new (P || (P = Promise))(function (resolve, reject) {688 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }689 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }690 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }691 step((generator = generator.apply(thisArg, _arguments || [])).next());692 });693 }694 var until = createCommonjsModule(function (module, exports) {695 Object.defineProperty(exports, "__esModule", { value: true });696 /**697 * Gracefully handles a given Promise factory.698 * @example699 * cosnt [error, data] = await until(() => asyncAction())700 */701 exports.until = async (promise) => {702 try {703 const data = await promise().catch((error) => {704 throw error;705 });706 return [null, data];707 }708 catch (error) {709 return [error, null];710 }711 };712 });713 var lib$1 = createCommonjsModule(function (module, exports) {714 Object.defineProperty(exports, "__esModule", { value: true });715 exports.until = until.until;716 });717 /**718 * Attempts to resolve a Service Worker instance from a given registration,719 * regardless of its state (active, installing, waiting).720 */721 const getWorkerByRegistration = (registration, absoluteWorkerUrl, findWorker) => {722 const allStates = [723 registration.active,724 registration.installing,725 registration.waiting,726 ];727 const existingStates = allStates.filter(Boolean);728 const mockWorker = existingStates.find((worker) => {729 return findWorker(worker.scriptURL, absoluteWorkerUrl);730 });731 return mockWorker || null;732 };733 /**734 * Returns an absolute Service Worker URL based on the given735 * relative URL (known during the registration).736 */737 function getAbsoluteWorkerUrl(relativeUrl) {738 return new URL(relativeUrl, location.origin).href;739 }740 /**741 * Returns an active Service Worker instance.742 * When not found, registers a new Service Worker.743 */744 const getWorkerInstance = (url, options = {}, findWorker) => __awaiter(void 0, void 0, void 0, function* () {745 // Resolve the absolute Service Worker URL.746 const absoluteWorkerUrl = getAbsoluteWorkerUrl(url);747 const [, mockRegistrations] = yield lib$1.until(() => __awaiter(void 0, void 0, void 0, function* () {748 const registrations = yield navigator.serviceWorker.getRegistrations();749 return registrations.filter((registration) => {750 return getWorkerByRegistration(registration, absoluteWorkerUrl, findWorker);751 });752 }));753 if (!navigator.serviceWorker.controller && mockRegistrations.length > 0) {754 // Reload the page when it has associated workers, but no active controller.755 // The absence of a controller can mean either:756 // - page has no Service Worker associated with it757 // - page has been hard-reloaded and its workers won't be used until the next reload.758 // Since we've checked that there are registrations associated with this page,759 // at this point we are sure it's hard reload that falls into this clause.760 location.reload();761 }762 const [existingRegistration] = mockRegistrations;763 if (existingRegistration) {764 // When the Service Worker is registered, update it and return the reference.765 return existingRegistration.update().then(() => {766 return [767 getWorkerByRegistration(existingRegistration, absoluteWorkerUrl, findWorker),768 existingRegistration,769 ];770 });771 }772 // When the Service Worker wasn't found, register it anew and return the reference.773 const [error, instance] = yield lib$1.until(() => __awaiter(void 0, void 0, void 0, function* () {774 const registration = yield navigator.serviceWorker.register(url, options);775 return [776 // Compare existing worker registration by its worker URL,777 // to prevent irrelevant workers to resolve here (such as Codesandbox worker).778 getWorkerByRegistration(registration, absoluteWorkerUrl, findWorker),779 registration,780 ];781 }));782 // Handle Service Worker registration errors.783 if (error) {784 const isWorkerMissing = error.message.includes('(404)');785 // Produce a custom error message when given a non-existing Service Worker url.786 // Suggest developers to check their setup.787 if (isWorkerMissing) {788 const scopeUrl = new URL((options === null || options === void 0 ? void 0 : options.scope) || '/', location.href);789 console.error(`\790[MSW] Failed to register a Service Worker for scope ('${scopeUrl.href}') with script ('${absoluteWorkerUrl}'): Service Worker script does not exist at the given path.791Did you forget to run "npx msw init <PUBLIC_DIR>"?792Learn more about creating the Service Worker script: https://mswjs.io/docs/cli/init`);793 return null;794 }795 // Fallback error message for any other registration errors.796 console.error(`[MSW] Failed to register a Service Worker:\n\m${error.message}`);797 return null;798 }799 return instance;800 });801 const activateMocking = (context, options) => __awaiter(void 0, void 0, void 0, function* () {802 var _a;803 (_a = context.worker) === null || _a === void 0 ? void 0 : _a.postMessage('MOCK_ACTIVATE');804 return context.events.once('MOCKING_ENABLED').then(() => {805 if (!(options === null || options === void 0 ? void 0 : options.quiet)) {806 console.groupCollapsed('%c[MSW] Mocking enabled.', 'color:orangered;font-weight:bold;');807 console.log('%cDocumentation: %chttps://mswjs.io/docs', 'font-weight:bold', 'font-weight:normal');808 console.log('Found an issue? https://github.com/mswjs/msw/issues');809 console.groupEnd();810 }811 });812 });813 /**814 * Creates a communication channel between the client815 * and the Service Worker associated with the given event.816 */817 const createBroadcastChannel = (event) => {818 const port = event.ports[0];819 return {820 /**821 * Sends a text message to the connected Service Worker.822 */823 send(message) {824 if (port) {825 port.postMessage(message);826 }827 },828 };829 };830 const defaultContext = {831 status,832 set,833 delay,834 fetch,835 };836 /**837 * Composes a given list of functions into a new function that838 * executes from right to left.839 */840 function compose(...funcs) {841 return funcs.reduce((f, g) => (...args) => f(g(...args)));842 }843 class NetworkError extends Error {844 constructor(message) {845 super(message);846 this.name = 'NetworkError';847 }848 }849 /**850 * Internal response transformer to ensure response JSON body851 * is always stringified.852 */853 const stringifyJsonBody = (res) => {854 var _a, _b;855 if (res.body && ((_b = (_a = res.headers) === null || _a === void 0 ? void 0 : _a.get('content-type')) === null || _b === void 0 ? void 0 : _b.endsWith('json'))) {856 res.body = JSON.stringify(res.body);857 }858 return res;859 };860 const defaultResponse = {861 status: 200,862 statusText: 'OK',863 body: null,864 delay: 0,865 once: false,866 };867 const defaultResponseTransformers = [868 stringifyJsonBody,869 ];870 function createResponseComposition(responseOverrides, defaultTransformers = defaultResponseTransformers) {871 return (...transformers) => {872 const initialResponse = Object.assign({}, defaultResponse, {873 headers: new lib.Headers({874 'x-powered-by': 'msw',875 }),876 }, responseOverrides);877 const resolvedTransformers = [878 ...defaultTransformers,879 ...transformers,880 ].filter(Boolean);881 const resolvedResponse = resolvedTransformers.length > 0882 ? compose(...resolvedTransformers)(initialResponse)883 : initialResponse;884 return resolvedResponse;885 };886 }887 const response = Object.assign(createResponseComposition(), {888 once: createResponseComposition({ once: true }),889 networkError(message) {890 throw new NetworkError(message);891 },892 });893 /**894 * Returns a mocked response for a given request using following request handlers.895 */896 const getResponse = (req, handlers) => __awaiter(void 0, void 0, void 0, function* () {897 const relevantHandlers = handlers898 .filter((requestHandler) => {899 // Skip a handler if it has been already used for a one-time response.900 return !requestHandler.shouldSkip;901 })902 .map((requestHandler) => {903 // Parse the captured request to get additional information.904 // Make the predicate function accept all the necessary information905 // to decide on the interception.906 const parsedRequest = requestHandler.parse907 ? requestHandler.parse(req)908 : null;909 return [requestHandler, parsedRequest];910 })911 .filter(([requestHandler, parsedRequest]) => {912 return requestHandler.predicate(req, parsedRequest);913 });914 if (relevantHandlers.length == 0) {915 // Handle a scenario when a request has no relevant request handlers.916 // In that case it would be bypassed (performed as-is).917 return {918 handler: null,919 response: null,920 };921 }922 const { requestHandler, parsedRequest, mockedResponse, publicRequest, } = yield relevantHandlers.reduce((asyncAcc, [requestHandler, parsedRequest]) => __awaiter(void 0, void 0, void 0, function* () {923 // Now the reduce function is async so we need to await if response was found924 const acc = yield asyncAcc;925 // If a first not empty response was found we'll stop evaluating other requests926 if (acc.requestHandler) {927 return acc;928 }929 const { getPublicRequest, defineContext, resolver } = requestHandler;930 const publicRequest = getPublicRequest931 ? getPublicRequest(req, parsedRequest)932 : req;933 const context = defineContext934 ? defineContext(publicRequest)935 : defaultContext;936 const mockedResponse = yield resolver(publicRequest, response, context);937 if (!mockedResponse) {938 return acc;939 }940 if (mockedResponse && mockedResponse.once) {941 // When responded with a one-time response, match the relevant request handler942 // as skipped, so it cannot affect the captured requests anymore.943 requestHandler.shouldSkip = true;944 }945 return {946 requestHandler,947 parsedRequest,948 mockedResponse,949 publicRequest,950 };951 }), Promise.resolve({ mockedResponse: null }));952 // Although reducing a list of relevant request handlers, it's possible953 // that in the end there will be no handler associted with the request954 // (i.e. if relevant handlers are fall-through).955 if (!requestHandler) {956 return {957 handler: null,958 response: null,959 };960 }961 return {962 handler: requestHandler,963 response: mockedResponse,964 publicRequest,965 parsedRequest,966 };967 });968 var punycode = createCommonjsModule(function (module, exports) {969 (function(root) {970 /** Detect free variables */971 var freeExports = exports &&972 !exports.nodeType && exports;973 var freeModule = module &&974 !module.nodeType && module;975 var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal;976 if (977 freeGlobal.global === freeGlobal ||978 freeGlobal.window === freeGlobal ||979 freeGlobal.self === freeGlobal980 ) {981 root = freeGlobal;982 }983 /**984 * The `punycode` object.985 * @name punycode986 * @type Object987 */988 var punycode,989 /** Highest positive signed 32-bit float value */990 maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1991 /** Bootstring parameters */992 base = 36,993 tMin = 1,994 tMax = 26,995 skew = 38,996 damp = 700,997 initialBias = 72,998 initialN = 128, // 0x80999 delimiter = '-', // '\x2D'1000 /** Regular expressions */1001 regexPunycode = /^xn--/,1002 regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars1003 regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators1004 /** Error messages */1005 errors = {1006 'overflow': 'Overflow: input needs wider integers to process',1007 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',1008 'invalid-input': 'Invalid input'1009 },1010 /** Convenience shortcuts */1011 baseMinusTMin = base - tMin,1012 floor = Math.floor,1013 stringFromCharCode = String.fromCharCode,1014 /** Temporary variable */1015 key;1016 /*--------------------------------------------------------------------------*/1017 /**1018 * A generic error utility function.1019 * @private1020 * @param {String} type The error type.1021 * @returns {Error} Throws a `RangeError` with the applicable error message.1022 */1023 function error(type) {1024 throw RangeError(errors[type]);1025 }1026 /**1027 * A generic `Array#map` utility function.1028 * @private1029 * @param {Array} array The array to iterate over.1030 * @param {Function} callback The function that gets called for every array1031 * item.1032 * @returns {Array} A new array of values returned by the callback function.1033 */1034 function map(array, fn) {1035 var length = array.length;1036 var result = [];1037 while (length--) {1038 result[length] = fn(array[length]);1039 }1040 return result;1041 }1042 /**1043 * A simple `Array#map`-like wrapper to work with domain name strings or email1044 * addresses.1045 * @private1046 * @param {String} domain The domain name or email address.1047 * @param {Function} callback The function that gets called for every1048 * character.1049 * @returns {Array} A new string of characters returned by the callback1050 * function.1051 */1052 function mapDomain(string, fn) {1053 var parts = string.split('@');1054 var result = '';1055 if (parts.length > 1) {1056 // In email addresses, only the domain name should be punycoded. Leave1057 // the local part (i.e. everything up to `@`) intact.1058 result = parts[0] + '@';1059 string = parts[1];1060 }1061 // Avoid `split(regex)` for IE8 compatibility. See #17.1062 string = string.replace(regexSeparators, '\x2E');1063 var labels = string.split('.');1064 var encoded = map(labels, fn).join('.');1065 return result + encoded;1066 }1067 /**1068 * Creates an array containing the numeric code points of each Unicode1069 * character in the string. While JavaScript uses UCS-2 internally,1070 * this function will convert a pair of surrogate halves (each of which1071 * UCS-2 exposes as separate characters) into a single code point,1072 * matching UTF-16.1073 * @see `punycode.ucs2.encode`1074 * @see <https://mathiasbynens.be/notes/javascript-encoding>1075 * @memberOf punycode.ucs21076 * @name decode1077 * @param {String} string The Unicode input string (UCS-2).1078 * @returns {Array} The new array of code points.1079 */1080 function ucs2decode(string) {1081 var output = [],1082 counter = 0,1083 length = string.length,1084 value,1085 extra;1086 while (counter < length) {1087 value = string.charCodeAt(counter++);1088 if (value >= 0xD800 && value <= 0xDBFF && counter < length) {1089 // high surrogate, and there is a next character1090 extra = string.charCodeAt(counter++);1091 if ((extra & 0xFC00) == 0xDC00) { // low surrogate1092 output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);1093 } else {1094 // unmatched surrogate; only append this code unit, in case the next1095 // code unit is the high surrogate of a surrogate pair1096 output.push(value);1097 counter--;1098 }1099 } else {1100 output.push(value);1101 }1102 }1103 return output;1104 }1105 /**1106 * Creates a string based on an array of numeric code points.1107 * @see `punycode.ucs2.decode`1108 * @memberOf punycode.ucs21109 * @name encode1110 * @param {Array} codePoints The array of numeric code points.1111 * @returns {String} The new Unicode string (UCS-2).1112 */1113 function ucs2encode(array) {1114 return map(array, function(value) {1115 var output = '';1116 if (value > 0xFFFF) {1117 value -= 0x10000;1118 output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);1119 value = 0xDC00 | value & 0x3FF;1120 }1121 output += stringFromCharCode(value);1122 return output;1123 }).join('');1124 }1125 /**1126 * Converts a basic code point into a digit/integer.1127 * @see `digitToBasic()`1128 * @private1129 * @param {Number} codePoint The basic numeric code point value.1130 * @returns {Number} The numeric value of a basic code point (for use in1131 * representing integers) in the range `0` to `base - 1`, or `base` if1132 * the code point does not represent a value.1133 */1134 function basicToDigit(codePoint) {1135 if (codePoint - 48 < 10) {1136 return codePoint - 22;1137 }1138 if (codePoint - 65 < 26) {1139 return codePoint - 65;1140 }1141 if (codePoint - 97 < 26) {1142 return codePoint - 97;1143 }1144 return base;1145 }1146 /**1147 * Converts a digit/integer into a basic code point.1148 * @see `basicToDigit()`1149 * @private1150 * @param {Number} digit The numeric value of a basic code point.1151 * @returns {Number} The basic code point whose value (when used for1152 * representing integers) is `digit`, which needs to be in the range1153 * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is1154 * used; else, the lowercase form is used. The behavior is undefined1155 * if `flag` is non-zero and `digit` has no uppercase form.1156 */1157 function digitToBasic(digit, flag) {1158 // 0..25 map to ASCII a..z or A..Z1159 // 26..35 map to ASCII 0..91160 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);1161 }1162 /**1163 * Bias adaptation function as per section 3.4 of RFC 3492.1164 * http://tools.ietf.org/html/rfc3492#section-3.41165 * @private1166 */1167 function adapt(delta, numPoints, firstTime) {1168 var k = 0;1169 delta = firstTime ? floor(delta / damp) : delta >> 1;1170 delta += floor(delta / numPoints);1171 for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {1172 delta = floor(delta / baseMinusTMin);1173 }1174 return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));1175 }1176 /**1177 * Converts a Punycode string of ASCII-only symbols to a string of Unicode1178 * symbols.1179 * @memberOf punycode1180 * @param {String} input The Punycode string of ASCII-only symbols.1181 * @returns {String} The resulting string of Unicode symbols.1182 */1183 function decode(input) {1184 // Don't use UCS-21185 var output = [],1186 inputLength = input.length,1187 out,1188 i = 0,1189 n = initialN,1190 bias = initialBias,1191 basic,1192 j,1193 index,1194 oldi,1195 w,1196 k,1197 digit,1198 t,1199 /** Cached calculation results */1200 baseMinusT;1201 // Handle the basic code points: let `basic` be the number of input code1202 // points before the last delimiter, or `0` if there is none, then copy1203 // the first basic code points to the output.1204 basic = input.lastIndexOf(delimiter);1205 if (basic < 0) {1206 basic = 0;1207 }1208 for (j = 0; j < basic; ++j) {1209 // if it's not a basic code point1210 if (input.charCodeAt(j) >= 0x80) {1211 error('not-basic');1212 }1213 output.push(input.charCodeAt(j));1214 }1215 // Main decoding loop: start just after the last delimiter if any basic code1216 // points were copied; start at the beginning otherwise.1217 for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {1218 // `index` is the index of the next character to be consumed.1219 // Decode a generalized variable-length integer into `delta`,1220 // which gets added to `i`. The overflow checking is easier1221 // if we increase `i` as we go, then subtract off its starting1222 // value at the end to obtain `delta`.1223 for (oldi = i, w = 1, k = base; /* no condition */; k += base) {1224 if (index >= inputLength) {1225 error('invalid-input');1226 }1227 digit = basicToDigit(input.charCodeAt(index++));1228 if (digit >= base || digit > floor((maxInt - i) / w)) {1229 error('overflow');1230 }1231 i += digit * w;1232 t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);1233 if (digit < t) {1234 break;1235 }1236 baseMinusT = base - t;1237 if (w > floor(maxInt / baseMinusT)) {1238 error('overflow');1239 }1240 w *= baseMinusT;1241 }1242 out = output.length + 1;1243 bias = adapt(i - oldi, out, oldi == 0);1244 // `i` was supposed to wrap around from `out` to `0`,1245 // incrementing `n` each time, so we'll fix that now:1246 if (floor(i / out) > maxInt - n) {1247 error('overflow');1248 }1249 n += floor(i / out);1250 i %= out;1251 // Insert `n` at position `i` of the output1252 output.splice(i++, 0, n);1253 }1254 return ucs2encode(output);1255 }1256 /**1257 * Converts a string of Unicode symbols (e.g. a domain name label) to a1258 * Punycode string of ASCII-only symbols.1259 * @memberOf punycode1260 * @param {String} input The string of Unicode symbols.1261 * @returns {String} The resulting Punycode string of ASCII-only symbols.1262 */1263 function encode(input) {1264 var n,1265 delta,1266 handledCPCount,1267 basicLength,1268 bias,1269 j,1270 m,1271 q,1272 k,1273 t,1274 currentValue,1275 output = [],1276 /** `inputLength` will hold the number of code points in `input`. */1277 inputLength,1278 /** Cached calculation results */1279 handledCPCountPlusOne,1280 baseMinusT,1281 qMinusT;1282 // Convert the input in UCS-2 to Unicode1283 input = ucs2decode(input);1284 // Cache the length1285 inputLength = input.length;1286 // Initialize the state1287 n = initialN;1288 delta = 0;1289 bias = initialBias;1290 // Handle the basic code points1291 for (j = 0; j < inputLength; ++j) {1292 currentValue = input[j];1293 if (currentValue < 0x80) {1294 output.push(stringFromCharCode(currentValue));1295 }1296 }1297 handledCPCount = basicLength = output.length;1298 // `handledCPCount` is the number of code points that have been handled;1299 // `basicLength` is the number of basic code points.1300 // Finish the basic string - if it is not empty - with a delimiter1301 if (basicLength) {1302 output.push(delimiter);1303 }1304 // Main encoding loop:1305 while (handledCPCount < inputLength) {1306 // All non-basic code points < n have been handled already. Find the next1307 // larger one:1308 for (m = maxInt, j = 0; j < inputLength; ++j) {1309 currentValue = input[j];1310 if (currentValue >= n && currentValue < m) {1311 m = currentValue;1312 }1313 }1314 // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,1315 // but guard against overflow1316 handledCPCountPlusOne = handledCPCount + 1;1317 if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {1318 error('overflow');1319 }1320 delta += (m - n) * handledCPCountPlusOne;1321 n = m;1322 for (j = 0; j < inputLength; ++j) {1323 currentValue = input[j];1324 if (currentValue < n && ++delta > maxInt) {1325 error('overflow');1326 }1327 if (currentValue == n) {1328 // Represent delta as a generalized variable-length integer1329 for (q = delta, k = base; /* no condition */; k += base) {1330 t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);1331 if (q < t) {1332 break;1333 }1334 qMinusT = q - t;1335 baseMinusT = base - t;1336 output.push(1337 stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))1338 );1339 q = floor(qMinusT / baseMinusT);1340 }1341 output.push(stringFromCharCode(digitToBasic(q, 0)));1342 bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);1343 delta = 0;1344 ++handledCPCount;1345 }1346 }1347 ++delta;1348 ++n;1349 }1350 return output.join('');1351 }1352 /**1353 * Converts a Punycode string representing a domain name or an email address1354 * to Unicode. Only the Punycoded parts of the input will be converted, i.e.1355 * it doesn't matter if you call it on a string that has already been1356 * converted to Unicode.1357 * @memberOf punycode1358 * @param {String} input The Punycoded domain name or email address to1359 * convert to Unicode.1360 * @returns {String} The Unicode representation of the given Punycode1361 * string.1362 */1363 function toUnicode(input) {1364 return mapDomain(input, function(string) {1365 return regexPunycode.test(string)1366 ? decode(string.slice(4).toLowerCase())1367 : string;1368 });1369 }1370 /**1371 * Converts a Unicode string representing a domain name or an email address to1372 * Punycode. Only the non-ASCII parts of the domain name will be converted,1373 * i.e. it doesn't matter if you call it with a domain that's already in1374 * ASCII.1375 * @memberOf punycode1376 * @param {String} input The domain name or email address to convert, as a1377 * Unicode string.1378 * @returns {String} The Punycode representation of the given domain name or1379 * email address.1380 */1381 function toASCII(input) {1382 return mapDomain(input, function(string) {1383 return regexNonASCII.test(string)1384 ? 'xn--' + encode(string)1385 : string;1386 });1387 }1388 /*--------------------------------------------------------------------------*/1389 /** Define the public API */1390 punycode = {1391 /**1392 * A string representing the current Punycode.js version number.1393 * @memberOf punycode1394 * @type String1395 */1396 'version': '1.3.2',1397 /**1398 * An object of methods to convert from JavaScript's internal character1399 * representation (UCS-2) to Unicode code points, and back.1400 * @see <https://mathiasbynens.be/notes/javascript-encoding>1401 * @memberOf punycode1402 * @type Object1403 */1404 'ucs2': {1405 'decode': ucs2decode,1406 'encode': ucs2encode1407 },1408 'decode': decode,1409 'encode': encode,1410 'toASCII': toASCII,1411 'toUnicode': toUnicode1412 };1413 /** Expose `punycode` */1414 // Some AMD build optimizers, like r.js, check for specific condition patterns1415 // like the following:1416 if (freeExports && freeModule) {1417 if (module.exports == freeExports) { // in Node.js or RingoJS v0.8.0+1418 freeModule.exports = punycode;1419 } else { // in Narwhal or RingoJS v0.7.0-1420 for (key in punycode) {1421 punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);1422 }1423 }1424 } else { // in Rhino or a web browser1425 root.punycode = punycode;1426 }1427 }(commonjsGlobal));1428 });1429 var util = {1430 isString: function(arg) {1431 return typeof(arg) === 'string';1432 },1433 isObject: function(arg) {1434 return typeof(arg) === 'object' && arg !== null;1435 },1436 isNull: function(arg) {1437 return arg === null;1438 },1439 isNullOrUndefined: function(arg) {1440 return arg == null;1441 }1442 };1443 // Copyright Joyent, Inc. and other Node contributors.1444 // If obj.hasOwnProperty has been overridden, then calling1445 // obj.hasOwnProperty(prop) will break.1446 // See: https://github.com/joyent/node/issues/17071447 function hasOwnProperty(obj, prop) {1448 return Object.prototype.hasOwnProperty.call(obj, prop);1449 }1450 var decode$1 = function(qs, sep, eq, options) {1451 sep = sep || '&';1452 eq = eq || '=';1453 var obj = {};1454 if (typeof qs !== 'string' || qs.length === 0) {1455 return obj;1456 }1457 var regexp = /\+/g;1458 qs = qs.split(sep);1459 var maxKeys = 1000;1460 if (options && typeof options.maxKeys === 'number') {1461 maxKeys = options.maxKeys;1462 }1463 var len = qs.length;1464 // maxKeys <= 0 means that we should not limit keys count1465 if (maxKeys > 0 && len > maxKeys) {1466 len = maxKeys;1467 }1468 for (var i = 0; i < len; ++i) {1469 var x = qs[i].replace(regexp, '%20'),1470 idx = x.indexOf(eq),1471 kstr, vstr, k, v;1472 if (idx >= 0) {1473 kstr = x.substr(0, idx);1474 vstr = x.substr(idx + 1);1475 } else {1476 kstr = x;1477 vstr = '';1478 }1479 k = decodeURIComponent(kstr);1480 v = decodeURIComponent(vstr);1481 if (!hasOwnProperty(obj, k)) {1482 obj[k] = v;1483 } else if (Array.isArray(obj[k])) {1484 obj[k].push(v);1485 } else {1486 obj[k] = [obj[k], v];1487 }1488 }1489 return obj;1490 };1491 // Copyright Joyent, Inc. and other Node contributors.1492 var stringifyPrimitive = function(v) {1493 switch (typeof v) {1494 case 'string':1495 return v;1496 case 'boolean':1497 return v ? 'true' : 'false';1498 case 'number':1499 return isFinite(v) ? v : '';1500 default:1501 return '';1502 }1503 };1504 var encode$1 = function(obj, sep, eq, name) {1505 sep = sep || '&';1506 eq = eq || '=';1507 if (obj === null) {1508 obj = undefined;1509 }1510 if (typeof obj === 'object') {1511 return Object.keys(obj).map(function(k) {1512 var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;1513 if (Array.isArray(obj[k])) {1514 return obj[k].map(function(v) {1515 return ks + encodeURIComponent(stringifyPrimitive(v));1516 }).join(sep);1517 } else {1518 return ks + encodeURIComponent(stringifyPrimitive(obj[k]));1519 }1520 }).join(sep);1521 }1522 if (!name) return '';1523 return encodeURIComponent(stringifyPrimitive(name)) + eq +1524 encodeURIComponent(stringifyPrimitive(obj));1525 };1526 var querystring = createCommonjsModule(function (module, exports) {1527 exports.decode = exports.parse = decode$1;1528 exports.encode = exports.stringify = encode$1;1529 });1530 var format = urlFormat;1531 function Url() {1532 this.protocol = null;1533 this.slashes = null;1534 this.auth = null;1535 this.host = null;1536 this.port = null;1537 this.hostname = null;1538 this.hash = null;1539 this.search = null;1540 this.query = null;1541 this.pathname = null;1542 this.path = null;1543 this.href = null;1544 }1545 // Reference: RFC 3986, RFC 1808, RFC 23961546 // define these here so at least they only have to be1547 // compiled once on the first module load.1548 var protocolPattern = /^([a-z0-9.+-]+:)/i,1549 portPattern = /:[0-9]*$/,1550 // Special case for a simple path URL1551 simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,1552 // RFC 2396: characters reserved for delimiting URLs.1553 // We actually just auto-escape these.1554 delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],1555 // RFC 2396: characters not allowed for various reasons.1556 unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),1557 // Allowed by RFCs, but cause of XSS attacks. Always escape these.1558 autoEscape = ['\''].concat(unwise),1559 // Characters that are never ever allowed in a hostname.1560 // Note that any invalid chars are also handled, but these1561 // are the ones that are *expected* to be seen, so we fast-path1562 // them.1563 nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),1564 hostEndingChars = ['/', '?', '#'],1565 hostnameMaxLen = 255,1566 hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,1567 hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,1568 // protocols that can allow "unsafe" and "unwise" chars.1569 unsafeProtocol = {1570 'javascript': true,1571 'javascript:': true1572 },1573 // protocols that never have a hostname.1574 hostlessProtocol = {1575 'javascript': true,1576 'javascript:': true1577 },1578 // protocols that always contain a // bit.1579 slashedProtocol = {1580 'http': true,1581 'https': true,1582 'ftp': true,1583 'gopher': true,1584 'file': true,1585 'http:': true,1586 'https:': true,1587 'ftp:': true,1588 'gopher:': true,1589 'file:': true1590 };1591 function urlParse(url, parseQueryString, slashesDenoteHost) {1592 if (url && util.isObject(url) && url instanceof Url) return url;1593 var u = new Url;1594 u.parse(url, parseQueryString, slashesDenoteHost);1595 return u;1596 }1597 Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {1598 if (!util.isString(url)) {1599 throw new TypeError("Parameter 'url' must be a string, not " + typeof url);1600 }1601 // Copy chrome, IE, opera backslash-handling behavior.1602 // Back slashes before the query string get converted to forward slashes1603 // See: https://code.google.com/p/chromium/issues/detail?id=259161604 var queryIndex = url.indexOf('?'),1605 splitter =1606 (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',1607 uSplit = url.split(splitter),1608 slashRegex = /\\/g;1609 uSplit[0] = uSplit[0].replace(slashRegex, '/');1610 url = uSplit.join(splitter);1611 var rest = url;1612 // trim before proceeding.1613 // This is to support parse stuff like " http://foo.com \n"1614 rest = rest.trim();1615 if (!slashesDenoteHost && url.split('#').length === 1) {1616 // Try fast path regexp1617 var simplePath = simplePathPattern.exec(rest);1618 if (simplePath) {1619 this.path = rest;1620 this.href = rest;1621 this.pathname = simplePath[1];1622 if (simplePath[2]) {1623 this.search = simplePath[2];1624 if (parseQueryString) {1625 this.query = querystring.parse(this.search.substr(1));1626 } else {1627 this.query = this.search.substr(1);1628 }1629 } else if (parseQueryString) {1630 this.search = '';1631 this.query = {};1632 }1633 return this;1634 }1635 }1636 var proto = protocolPattern.exec(rest);1637 if (proto) {1638 proto = proto[0];1639 var lowerProto = proto.toLowerCase();1640 this.protocol = lowerProto;1641 rest = rest.substr(proto.length);1642 }1643 // figure out if it's got a host1644 // user@server is *always* interpreted as a hostname, and url1645 // resolution will treat //foo/bar as host=foo,path=bar because that's1646 // how the browser resolves relative URLs.1647 if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {1648 var slashes = rest.substr(0, 2) === '//';1649 if (slashes && !(proto && hostlessProtocol[proto])) {1650 rest = rest.substr(2);1651 this.slashes = true;1652 }1653 }1654 if (!hostlessProtocol[proto] &&1655 (slashes || (proto && !slashedProtocol[proto]))) {1656 // there's a hostname.1657 // the first instance of /, ?, ;, or # ends the host.1658 //1659 // If there is an @ in the hostname, then non-host chars *are* allowed1660 // to the left of the last @ sign, unless some host-ending character1661 // comes *before* the @-sign.1662 // URLs are obnoxious.1663 //1664 // ex:1665 // http://a@b@c/ => user:a@b host:c1666 // http://a@b?@c => user:a host:c path:/?@c1667 // v0.12 TODO(isaacs): This is not quite how Chrome does things.1668 // Review our test case against browsers more comprehensively.1669 // find the first instance of any hostEndingChars1670 var hostEnd = -1;1671 for (var i = 0; i < hostEndingChars.length; i++) {1672 var hec = rest.indexOf(hostEndingChars[i]);1673 if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))1674 hostEnd = hec;1675 }1676 // at this point, either we have an explicit point where the1677 // auth portion cannot go past, or the last @ char is the decider.1678 var auth, atSign;1679 if (hostEnd === -1) {1680 // atSign can be anywhere.1681 atSign = rest.lastIndexOf('@');1682 } else {1683 // atSign must be in auth portion.1684 // http://a@b/c@d => host:b auth:a path:/c@d1685 atSign = rest.lastIndexOf('@', hostEnd);1686 }1687 // Now we have a portion which is definitely the auth.1688 // Pull that off.1689 if (atSign !== -1) {1690 auth = rest.slice(0, atSign);1691 rest = rest.slice(atSign + 1);1692 this.auth = decodeURIComponent(auth);1693 }1694 // the host is the remaining to the left of the first non-host char1695 hostEnd = -1;1696 for (var i = 0; i < nonHostChars.length; i++) {1697 var hec = rest.indexOf(nonHostChars[i]);1698 if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))1699 hostEnd = hec;1700 }1701 // if we still have not hit it, then the entire thing is a host.1702 if (hostEnd === -1)1703 hostEnd = rest.length;1704 this.host = rest.slice(0, hostEnd);1705 rest = rest.slice(hostEnd);1706 // pull out port.1707 this.parseHost();1708 // we've indicated that there is a hostname,1709 // so even if it's empty, it has to be present.1710 this.hostname = this.hostname || '';1711 // if hostname begins with [ and ends with ]1712 // assume that it's an IPv6 address.1713 var ipv6Hostname = this.hostname[0] === '[' &&1714 this.hostname[this.hostname.length - 1] === ']';1715 // validate a little.1716 if (!ipv6Hostname) {1717 var hostparts = this.hostname.split(/\./);1718 for (var i = 0, l = hostparts.length; i < l; i++) {1719 var part = hostparts[i];1720 if (!part) continue;1721 if (!part.match(hostnamePartPattern)) {1722 var newpart = '';1723 for (var j = 0, k = part.length; j < k; j++) {1724 if (part.charCodeAt(j) > 127) {1725 // we replace non-ASCII char with a temporary placeholder1726 // we need this to make sure size of hostname is not1727 // broken by replacing non-ASCII by nothing1728 newpart += 'x';1729 } else {1730 newpart += part[j];1731 }1732 }1733 // we test again with ASCII char only1734 if (!newpart.match(hostnamePartPattern)) {1735 var validParts = hostparts.slice(0, i);1736 var notHost = hostparts.slice(i + 1);1737 var bit = part.match(hostnamePartStart);1738 if (bit) {1739 validParts.push(bit[1]);1740 notHost.unshift(bit[2]);1741 }1742 if (notHost.length) {1743 rest = '/' + notHost.join('.') + rest;1744 }1745 this.hostname = validParts.join('.');1746 break;1747 }1748 }1749 }1750 }1751 if (this.hostname.length > hostnameMaxLen) {1752 this.hostname = '';1753 } else {1754 // hostnames are always lower case.1755 this.hostname = this.hostname.toLowerCase();1756 }1757 if (!ipv6Hostname) {1758 // IDNA Support: Returns a punycoded representation of "domain".1759 // It only converts parts of the domain name that1760 // have non-ASCII characters, i.e. it doesn't matter if1761 // you call it with a domain that already is ASCII-only.1762 this.hostname = punycode.toASCII(this.hostname);1763 }1764 var p = this.port ? ':' + this.port : '';1765 var h = this.hostname || '';1766 this.host = h + p;1767 this.href += this.host;1768 // strip [ and ] from the hostname1769 // the host field still retains them, though1770 if (ipv6Hostname) {1771 this.hostname = this.hostname.substr(1, this.hostname.length - 2);1772 if (rest[0] !== '/') {1773 rest = '/' + rest;1774 }1775 }1776 }1777 // now rest is set to the post-host stuff.1778 // chop off any delim chars.1779 if (!unsafeProtocol[lowerProto]) {1780 // First, make 100% sure that any "autoEscape" chars get1781 // escaped, even if encodeURIComponent doesn't think they1782 // need to be.1783 for (var i = 0, l = autoEscape.length; i < l; i++) {1784 var ae = autoEscape[i];1785 if (rest.indexOf(ae) === -1)1786 continue;1787 var esc = encodeURIComponent(ae);1788 if (esc === ae) {1789 esc = escape(ae);1790 }1791 rest = rest.split(ae).join(esc);1792 }1793 }1794 // chop off from the tail first.1795 var hash = rest.indexOf('#');1796 if (hash !== -1) {1797 // got a fragment string.1798 this.hash = rest.substr(hash);1799 rest = rest.slice(0, hash);1800 }1801 var qm = rest.indexOf('?');1802 if (qm !== -1) {1803 this.search = rest.substr(qm);1804 this.query = rest.substr(qm + 1);1805 if (parseQueryString) {1806 this.query = querystring.parse(this.query);1807 }1808 rest = rest.slice(0, qm);1809 } else if (parseQueryString) {1810 // no query string, but parseQueryString still requested1811 this.search = '';1812 this.query = {};1813 }1814 if (rest) this.pathname = rest;1815 if (slashedProtocol[lowerProto] &&1816 this.hostname && !this.pathname) {1817 this.pathname = '/';1818 }1819 //to support http.request1820 if (this.pathname || this.search) {1821 var p = this.pathname || '';1822 var s = this.search || '';1823 this.path = p + s;1824 }1825 // finally, reconstruct the href based on what has been validated.1826 this.href = this.format();1827 return this;1828 };1829 // format a parsed object into a url string1830 function urlFormat(obj) {1831 // ensure it's an object, and not a string url.1832 // If it's an obj, this is a no-op.1833 // this way, you can call url_format() on strings1834 // to clean up potentially wonky urls.1835 if (util.isString(obj)) obj = urlParse(obj);1836 if (!(obj instanceof Url)) return Url.prototype.format.call(obj);1837 return obj.format();1838 }1839 Url.prototype.format = function() {1840 var auth = this.auth || '';1841 if (auth) {1842 auth = encodeURIComponent(auth);1843 auth = auth.replace(/%3A/i, ':');1844 auth += '@';1845 }1846 var protocol = this.protocol || '',1847 pathname = this.pathname || '',1848 hash = this.hash || '',1849 host = false,1850 query = '';1851 if (this.host) {1852 host = auth + this.host;1853 } else if (this.hostname) {1854 host = auth + (this.hostname.indexOf(':') === -1 ?1855 this.hostname :1856 '[' + this.hostname + ']');1857 if (this.port) {1858 host += ':' + this.port;1859 }1860 }1861 if (this.query &&1862 util.isObject(this.query) &&1863 Object.keys(this.query).length) {1864 query = querystring.stringify(this.query);1865 }1866 var search = this.search || (query && ('?' + query)) || '';1867 if (protocol && protocol.substr(-1) !== ':') protocol += ':';1868 // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.1869 // unless they had them to begin with.1870 if (this.slashes ||1871 (!protocol || slashedProtocol[protocol]) && host !== false) {1872 host = '//' + (host || '');1873 if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;1874 } else if (!host) {1875 host = '';1876 }1877 if (hash && hash.charAt(0) !== '#') hash = '#' + hash;1878 if (search && search.charAt(0) !== '?') search = '?' + search;1879 pathname = pathname.replace(/[?#]/g, function(match) {1880 return encodeURIComponent(match);1881 });1882 search = search.replace('#', '%23');1883 return protocol + host + pathname + search + hash;1884 };1885 Url.prototype.resolve = function(relative) {1886 return this.resolveObject(urlParse(relative, false, true)).format();1887 };1888 Url.prototype.resolveObject = function(relative) {1889 if (util.isString(relative)) {1890 var rel = new Url();1891 rel.parse(relative, false, true);1892 relative = rel;1893 }1894 var result = new Url();1895 var tkeys = Object.keys(this);1896 for (var tk = 0; tk < tkeys.length; tk++) {1897 var tkey = tkeys[tk];1898 result[tkey] = this[tkey];1899 }1900 // hash is always overridden, no matter what.1901 // even href="" will remove it.1902 result.hash = relative.hash;1903 // if the relative url is empty, then there's nothing left to do here.1904 if (relative.href === '') {1905 result.href = result.format();1906 return result;1907 }1908 // hrefs like //foo/bar always cut to the protocol.1909 if (relative.slashes && !relative.protocol) {1910 // take everything except the protocol from relative1911 var rkeys = Object.keys(relative);1912 for (var rk = 0; rk < rkeys.length; rk++) {1913 var rkey = rkeys[rk];1914 if (rkey !== 'protocol')1915 result[rkey] = relative[rkey];1916 }1917 //urlParse appends trailing / to urls like http://www.example.com1918 if (slashedProtocol[result.protocol] &&1919 result.hostname && !result.pathname) {1920 result.path = result.pathname = '/';1921 }1922 result.href = result.format();1923 return result;1924 }1925 if (relative.protocol && relative.protocol !== result.protocol) {1926 // if it's a known url protocol, then changing1927 // the protocol does weird things1928 // first, if it's not file:, then we MUST have a host,1929 // and if there was a path1930 // to begin with, then we MUST have a path.1931 // if it is file:, then the host is dropped,1932 // because that's known to be hostless.1933 // anything else is assumed to be absolute.1934 if (!slashedProtocol[relative.protocol]) {1935 var keys = Object.keys(relative);1936 for (var v = 0; v < keys.length; v++) {1937 var k = keys[v];1938 result[k] = relative[k];1939 }1940 result.href = result.format();1941 return result;1942 }1943 result.protocol = relative.protocol;1944 if (!relative.host && !hostlessProtocol[relative.protocol]) {1945 var relPath = (relative.pathname || '').split('/');1946 while (relPath.length && !(relative.host = relPath.shift()));1947 if (!relative.host) relative.host = '';1948 if (!relative.hostname) relative.hostname = '';1949 if (relPath[0] !== '') relPath.unshift('');1950 if (relPath.length < 2) relPath.unshift('');1951 result.pathname = relPath.join('/');1952 } else {1953 result.pathname = relative.pathname;1954 }1955 result.search = relative.search;1956 result.query = relative.query;1957 result.host = relative.host || '';1958 result.auth = relative.auth;1959 result.hostname = relative.hostname || relative.host;1960 result.port = relative.port;1961 // to support http.request1962 if (result.pathname || result.search) {1963 var p = result.pathname || '';1964 var s = result.search || '';1965 result.path = p + s;1966 }1967 result.slashes = result.slashes || relative.slashes;1968 result.href = result.format();1969 return result;1970 }1971 var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),1972 isRelAbs = (1973 relative.host ||1974 relative.pathname && relative.pathname.charAt(0) === '/'1975 ),1976 mustEndAbs = (isRelAbs || isSourceAbs ||1977 (result.host && relative.pathname)),1978 removeAllDots = mustEndAbs,1979 srcPath = result.pathname && result.pathname.split('/') || [],1980 relPath = relative.pathname && relative.pathname.split('/') || [],1981 psychotic = result.protocol && !slashedProtocol[result.protocol];1982 // if the url is a non-slashed url, then relative1983 // links like ../.. should be able1984 // to crawl up to the hostname, as well. This is strange.1985 // result.protocol has already been set by now.1986 // Later on, put the first path part into the host field.1987 if (psychotic) {1988 result.hostname = '';1989 result.port = null;1990 if (result.host) {1991 if (srcPath[0] === '') srcPath[0] = result.host;1992 else srcPath.unshift(result.host);1993 }1994 result.host = '';1995 if (relative.protocol) {1996 relative.hostname = null;1997 relative.port = null;1998 if (relative.host) {1999 if (relPath[0] === '') relPath[0] = relative.host;2000 else relPath.unshift(relative.host);2001 }2002 relative.host = null;2003 }2004 mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');2005 }2006 if (isRelAbs) {2007 // it's absolute.2008 result.host = (relative.host || relative.host === '') ?2009 relative.host : result.host;2010 result.hostname = (relative.hostname || relative.hostname === '') ?2011 relative.hostname : result.hostname;2012 result.search = relative.search;2013 result.query = relative.query;2014 srcPath = relPath;2015 // fall through to the dot-handling below.2016 } else if (relPath.length) {2017 // it's relative2018 // throw away the existing file, and take the new path instead.2019 if (!srcPath) srcPath = [];2020 srcPath.pop();2021 srcPath = srcPath.concat(relPath);2022 result.search = relative.search;2023 result.query = relative.query;2024 } else if (!util.isNullOrUndefined(relative.search)) {2025 // just pull out the search.2026 // like href='?foo'.2027 // Put this after the other two cases because it simplifies the booleans2028 if (psychotic) {2029 result.hostname = result.host = srcPath.shift();2030 //occationaly the auth can get stuck only in host2031 //this especially happens in cases like2032 //url.resolveObject('mailto:local1@domain1', 'local2@domain2')2033 var authInHost = result.host && result.host.indexOf('@') > 0 ?2034 result.host.split('@') : false;2035 if (authInHost) {2036 result.auth = authInHost.shift();2037 result.host = result.hostname = authInHost.shift();2038 }2039 }2040 result.search = relative.search;2041 result.query = relative.query;2042 //to support http.request2043 if (!util.isNull(result.pathname) || !util.isNull(result.search)) {2044 result.path = (result.pathname ? result.pathname : '') +2045 (result.search ? result.search : '');2046 }2047 result.href = result.format();2048 return result;2049 }2050 if (!srcPath.length) {2051 // no path at all. easy.2052 // we've already handled the other stuff above.2053 result.pathname = null;2054 //to support http.request2055 if (result.search) {2056 result.path = '/' + result.search;2057 } else {2058 result.path = null;2059 }2060 result.href = result.format();2061 return result;2062 }2063 // if a url ENDs in . or .., then it must get a trailing slash.2064 // however, if it ends in anything else non-slashy,2065 // then it must NOT get a trailing slash.2066 var last = srcPath.slice(-1)[0];2067 var hasTrailingSlash = (2068 (result.host || relative.host || srcPath.length > 1) &&2069 (last === '.' || last === '..') || last === '');2070 // strip single dots, resolve double dots to parent dir2071 // if the path tries to go above the root, `up` ends up > 02072 var up = 0;2073 for (var i = srcPath.length; i >= 0; i--) {2074 last = srcPath[i];2075 if (last === '.') {2076 srcPath.splice(i, 1);2077 } else if (last === '..') {2078 srcPath.splice(i, 1);2079 up++;2080 } else if (up) {2081 srcPath.splice(i, 1);2082 up--;2083 }2084 }2085 // if the path is allowed to go above the root, restore leading ..s2086 if (!mustEndAbs && !removeAllDots) {2087 for (; up--; up) {2088 srcPath.unshift('..');2089 }2090 }2091 if (mustEndAbs && srcPath[0] !== '' &&2092 (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {2093 srcPath.unshift('');2094 }2095 if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {2096 srcPath.push('');2097 }2098 var isAbsolute = srcPath[0] === '' ||2099 (srcPath[0] && srcPath[0].charAt(0) === '/');2100 // put the host back2101 if (psychotic) {2102 result.hostname = result.host = isAbsolute ? '' :2103 srcPath.length ? srcPath.shift() : '';2104 //occationaly the auth can get stuck only in host2105 //this especially happens in cases like2106 //url.resolveObject('mailto:local1@domain1', 'local2@domain2')2107 var authInHost = result.host && result.host.indexOf('@') > 0 ?2108 result.host.split('@') : false;2109 if (authInHost) {2110 result.auth = authInHost.shift();2111 result.host = result.hostname = authInHost.shift();2112 }2113 }2114 mustEndAbs = mustEndAbs || (result.host && srcPath.length);2115 if (mustEndAbs && !isAbsolute) {2116 srcPath.unshift('');2117 }2118 if (!srcPath.length) {2119 result.pathname = null;2120 result.path = null;2121 } else {2122 result.pathname = srcPath.join('/');2123 }2124 //to support request.http2125 if (!util.isNull(result.pathname) || !util.isNull(result.search)) {2126 result.path = (result.pathname ? result.pathname : '') +2127 (result.search ? result.search : '');2128 }2129 result.auth = relative.auth || result.auth;2130 result.slashes = result.slashes || relative.slashes;2131 result.href = result.format();2132 return result;2133 };2134 Url.prototype.parseHost = function() {2135 var host = this.host;2136 var port = portPattern.exec(host);2137 if (port) {2138 port = port[0];2139 if (port !== ':') {2140 this.port = port.substr(1);2141 }2142 host = host.substr(0, host.length - port.length);2143 }2144 if (host) this.hostname = host;2145 };2146 /**2147 * Returns a relative URL if the given request URL is relative to the current origin.2148 * Otherwise returns an absolute URL.2149 */2150 const getPublicUrlFromRequest = (request) => {2151 return request.referrer.startsWith(request.url.origin)2152 ? request.url.pathname2153 : format({2154 protocol: request.url.protocol,2155 host: request.url.host,2156 pathname: request.url.pathname,2157 });2158 };2159 function onUnhandledRequest(request, onUnhandledRequest = 'bypass') {2160 if (typeof onUnhandledRequest === 'function') {2161 onUnhandledRequest(request);2162 return;2163 }2164 const publicUrl = getPublicUrlFromRequest(request);2165 const message = `captured a ${request.method} ${request.url} request without a corresponding request handler.2166 If you wish to intercept this request, consider creating a request handler for it:2167 rest.${request.method.toLowerCase()}('${publicUrl}', (req, res, ctx) => {2168 return res(ctx.text('body'))2169 })`;2170 switch (onUnhandledRequest) {2171 case 'error': {2172 throw new Error(`[MSW] Error: ${message}`);2173 }2174 case 'warn': {2175 console.warn(`[MSW] Warning: ${message}`);2176 }2177 default:2178 return;2179 }2180 }2181 /**2182 * Parses a given string into a JSON.2183 * Does not throw an exception on an invalid JSON string.2184 */2185 function jsonParse(str) {2186 try {2187 return JSON.parse(str);2188 }2189 catch (error) {2190 return undefined;2191 }2192 }2193 /**2194 * Parses a given request/response body based on the `Content-Type` header.2195 */2196 function parseBody(body, headers) {2197 var _a;2198 if (body) {2199 // If the intercepted request's body has a JSON Content-Type2200 // parse it into an object, otherwise leave as-is.2201 const hasJsonContent = (_a = headers === null || headers === void 0 ? void 0 : headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.includes('json');2202 if (hasJsonContent && typeof body !== 'object') {2203 return jsonParse(body) || body;2204 }2205 return body;2206 }2207 // Return whatever falsey body value is given.2208 return body;2209 }2210 function getAllCookies() {2211 return parse_1(document.cookie);2212 }2213 /**2214 * Returns relevant document cookies based on the request `credentials` option.2215 */2216 function getRequestCookies(req) {2217 switch (req.credentials) {2218 case 'same-origin': {2219 // Return document cookies only when requested a resource2220 // from the same origin as the current document.2221 return location.origin === req.url.origin ? getAllCookies() : {};2222 }2223 case 'include': {2224 // Return all document cookies.2225 return getAllCookies();2226 }2227 default: {2228 return {};2229 }2230 }2231 }2232 /**2233 * Performs a case-insensitive comparison of two given strings.2234 */2235 function isStringEqual(actual, expected) {2236 return actual.toLowerCase() === expected.toLowerCase();2237 }2238 const handleRequestWith = (context, options) => {2239 return (event) => __awaiter(void 0, void 0, void 0, function* () {2240 const channel = createBroadcastChannel(event);2241 try {2242 const message = JSON.parse(event.data, function (key, value) {2243 if (key === 'url') {2244 return new URL(value);2245 }2246 // Serialize headers2247 if (key === 'headers') {2248 return new lib.Headers(value);2249 }2250 // Prevent empty fields from presering an empty value.2251 // It's invalid to perform a GET request with { body: "" }2252 if (2253 // Check if we are parsing deeper in `event.data.payload`,2254 // because this custom JSON parser is invoked for each depth level.2255 this.method &&2256 isStringEqual(this.method, 'GET') &&2257 key === 'body' &&2258 value === '') {2259 return undefined;2260 }2261 return value;2262 });2263 const { type, payload: req } = message;2264 // Ignore irrelevant worker message types2265 if (type !== 'REQUEST') {2266 return null;2267 }2268 // Parse the request's body based on the "Content-Type" header.2269 req.body = parseBody(req.body, req.headers);2270 // Set document cookies on the request.2271 req.cookies = getRequestCookies(req);2272 const { response, handler, publicRequest, parsedRequest, } = yield getResponse(req, context.requestHandlers);2273 // Handle a scenario when there is no request handler2274 // found for a given request.2275 if (!handler) {2276 onUnhandledRequest(req, options.onUnhandledRequest);2277 return channel.send({ type: 'MOCK_NOT_FOUND' });2278 }2279 // Handle a scenario when there is a request handler,2280 // but it doesn't return any mocked response.2281 if (!response) {2282 console.warn('[MSW] Expected a mocking resolver function to return a mocked response Object, but got: %s. Original response is going to be used instead.', response);2283 return channel.send({ type: 'MOCK_NOT_FOUND' });2284 }2285 const responseWithSerializedHeaders = Object.assign(Object.assign({}, response), { headers: lib.headersToList(response.headers) });2286 if (!options.quiet) {2287 setTimeout(() => {2288 handler.log(publicRequest, responseWithSerializedHeaders, handler, parsedRequest);2289 }, response.delay);2290 }2291 channel.send({2292 type: 'MOCK_SUCCESS',2293 payload: responseWithSerializedHeaders,2294 });2295 }2296 catch (error) {2297 if (error instanceof NetworkError) {2298 // Treat emulated network error differently,2299 // as it is an intended exception in a request handler.2300 return channel.send({2301 type: 'NETWORK_ERROR',2302 payload: {2303 name: error.name,2304 message: error.message,2305 },2306 });2307 }2308 // Treat all the other exceptions in a request handler2309 // as unintended, alerting that there is a problem needs fixing.2310 channel.send({2311 type: 'INTERNAL_ERROR',2312 payload: {2313 status: 500,2314 body: JSON.stringify({2315 errorType: error.constructor.name,2316 message: error.message,2317 location: error.stack,2318 }),2319 },2320 });2321 }2322 });2323 };2324 function requestIntegrityCheck(context, serviceWorker) {2325 return __awaiter(this, void 0, void 0, function* () {2326 // Signal Service Worker to report back its integrity2327 serviceWorker.postMessage('INTEGRITY_CHECK_REQUEST');2328 const { payload: actualChecksum } = yield context.events.once('INTEGRITY_CHECK_RESPONSE');2329 // Compare the response from the Service Worker and the2330 // global variable set by webpack upon build.2331 if (actualChecksum !== "65d33ca82955e1c5928aed19d1bdf3f9") {2332 throw new Error(`Currently active Service Worker (${actualChecksum}) is behind the latest published one (${"65d33ca82955e1c5928aed19d1bdf3f9"}).`);2333 }2334 return serviceWorker;2335 });2336 }2337 /**2338 * Intercepts and defers any requests on the page2339 * until the Service Worker instance is ready.2340 * Must only be used in a browser.2341 */2342 function deferNetworkRequestsUntil(predicatePromise) {2343 // Defer any `XMLHttpRequest` requests until the Service Worker is ready.2344 const originalXhrSend = window.XMLHttpRequest.prototype.send;2345 window.XMLHttpRequest.prototype.send = function (...args) {2346 // Keep this function synchronous to comply with `XMLHttpRequest.prototype.send`,2347 // because that method is always synchronous.2348 lib$1.until(() => predicatePromise).then(() => {2349 window.XMLHttpRequest.prototype.send = originalXhrSend;2350 this.send(...args);2351 });2352 };2353 // Defer any `fetch` requests until the Service Worker is ready.2354 const originalFetch = window.fetch;2355 window.fetch = (...args) => __awaiter(this, void 0, void 0, function* () {2356 yield lib$1.until(() => predicatePromise);2357 window.fetch = originalFetch;2358 return window.fetch(...args);2359 });2360 }2361 const DEFAULT_START_OPTIONS = {2362 serviceWorker: {2363 url: '/mockServiceWorker.js',2364 options: null,2365 },2366 quiet: false,2367 waitUntilReady: true,2368 onUnhandledRequest: 'bypass',2369 findWorker: (scriptURL, mockServiceWorkerUrl) => scriptURL === mockServiceWorkerUrl,2370 };2371 const createStart = (context) => {2372 /**2373 * Registers and activates the mock Service Worker.2374 */2375 return function start(options) {2376 const resolvedOptions = mergeRight(DEFAULT_START_OPTIONS, options || {});2377 const startWorkerInstance = () => __awaiter(this, void 0, void 0, function* () {2378 if (!('serviceWorker' in navigator)) {2379 console.error(`[MSW] Failed to register a Service Worker: this browser does not support Service Workers (see https://caniuse.com/serviceworkers), or your application is running on an insecure host (consider using HTTPS for custom hostnames).`);2380 return null;2381 }2382 // Remove all previously existing event listeners.2383 // This way none of the listeners persists between Fast refresh2384 // of the application's code.2385 context.events.removeAllListeners();2386 context.events.addListener(navigator.serviceWorker, 'message', handleRequestWith(context, resolvedOptions));2387 const [, instance] = yield lib$1.until(() => getWorkerInstance(resolvedOptions.serviceWorker.url, resolvedOptions.serviceWorker.options, resolvedOptions.findWorker));2388 if (!instance) {2389 return null;2390 }2391 const [worker, registration] = instance;2392 if (!worker) {2393 if (options === null || options === void 0 ? void 0 : options.findWorker) {2394 console.error(`\2395[MSW] Failed to locate the Service Worker registration using a custom "findWorker" predicate.2396Please ensure that the custom predicate properly locates the Service Worker registration at "${resolvedOptions.serviceWorker.url}".2397More details: https://mswjs.io/docs/api/setup-worker/start#findworker2398`);2399 }2400 else {2401 console.error(`\2402[MSW] Failed to locate the Service Worker registration.2403This most likely means that the worker script URL "${resolvedOptions.serviceWorker.url}" cannot resolve against the actual public hostname (${location.host}). This may happen if your application runs behind a proxy, or has a dynamic hostname.2404Please consider using a custom "serviceWorker.url" option to point to the actual worker script location, or a custom "findWorker" option to resolve the Service Worker registration manually. More details: https://mswjs.io/docs/api/setup-worker/start`);2405 }2406 return null;2407 }2408 context.worker = worker;2409 context.registration = registration;2410 context.events.addListener(window, 'beforeunload', () => {2411 if (worker.state !== 'redundant') {2412 // Notify the Service Worker that this client has closed.2413 // Internally, it's similar to disabling the mocking, only2414 // client close event has a handler that self-terminates2415 // the Service Worker when there are no open clients.2416 worker.postMessage('CLIENT_CLOSED');2417 }2418 // Make sure we're always clearing the interval - there are reports that not doing this can2419 // cause memory leaks in headless browser environments.2420 window.clearInterval(context.keepAliveInterval);2421 });2422 // Check if the active Service Worker is the latest published one2423 const [integrityError] = yield lib$1.until(() => requestIntegrityCheck(context, worker));2424 if (integrityError) {2425 console.error(`\2426[MSW] Detected outdated Service Worker: ${integrityError.message}2427The mocking is still enabled, but it's highly recommended that you update your Service Worker by running:2428$ npx msw init <PUBLIC_DIR>2429This is necessary to ensure that the Service Worker is in sync with the library to guarantee its stability.2430If this message still persists after updating, please report an issue: https://github.com/open-draft/msw/issues\2431 `);2432 }2433 // Signal the Service Worker to enable requests interception2434 const [activationError] = yield lib$1.until(() => activateMocking(context, options));2435 if (activationError) {2436 console.error('Failed to enable mocking', activationError);2437 return null;2438 }2439 context.keepAliveInterval = window.setInterval(() => worker.postMessage('KEEPALIVE_REQUEST'), 5000);2440 return registration;2441 });2442 const workerRegistration = startWorkerInstance();2443 // Defer any network requests until the Service Worker instance is ready.2444 // This prevents a race condition between the Service Worker registration2445 // and application's runtime requests (i.e. requests on mount).2446 if (resolvedOptions.waitUntilReady) {2447 deferNetworkRequestsUntil(workerRegistration);2448 }2449 return workerRegistration;2450 };2451 };2452 const createStop = (context) => {2453 /**2454 * Signal the Service Worker to disable mocking for this client.2455 * Use this an an explicit way to stop the mocking, while preserving2456 * the worker-client relation. Does not affect the worker's lifecycle.2457 */2458 return function stop() {2459 var _a;2460 (_a = context.worker) === null || _a === void 0 ? void 0 : _a.postMessage('MOCK_DEACTIVATE');2461 context.events.removeAllListeners();2462 window.clearInterval(context.keepAliveInterval);2463 };2464 };2465 function use(currentHandlers, ...handlers) {2466 currentHandlers.unshift(...handlers);2467 }2468 function restoreHandlers(handlers) {2469 handlers.forEach((handler) => {2470 if ('shouldSkip' in handler) {2471 handler.shouldSkip = false;2472 }2473 });2474 }2475 function resetHandlers(initialHandlers, ...nextHandlers) {2476 return nextHandlers.length > 0 ? [...nextHandlers] : [...initialHandlers];2477 }2478 // Declare the list of event handlers on the module's scope2479 // so it persists between Fash refreshes of the application's code.2480 let listeners = [];2481 function setupWorker(...requestHandlers) {2482 requestHandlers.forEach((handler) => {2483 if (Array.isArray(handler))2484 throw new Error(`[MSW] Failed to call "setupWorker" given an Array of request handlers (setupWorker([a, b])), expected to receive each handler individually: setupWorker(a, b).`);2485 });2486 const context = {2487 worker: null,2488 registration: null,2489 requestHandlers: [...requestHandlers],2490 events: {2491 addListener(target, event, callback) {2492 target.addEventListener(event, callback);2493 listeners.push({ event, target, callback });2494 return () => {2495 target.removeEventListener(event, callback);2496 };2497 },2498 removeAllListeners() {2499 for (const { target, event, callback } of listeners) {2500 target.removeEventListener(event, callback);2501 }2502 listeners = [];2503 },2504 once(type) {2505 const bindings = [];2506 return new Promise((resolve, reject) => {2507 const handleIncomingMessage = (event) => {2508 try {2509 const message = JSON.parse(event.data);2510 if (message.type === type) {2511 resolve(message);2512 }2513 }2514 catch (error) {2515 reject(error);2516 }2517 };2518 bindings.push(context.events.addListener(navigator.serviceWorker, 'message', handleIncomingMessage), context.events.addListener(navigator.serviceWorker, 'messageerror', reject));2519 }).finally(() => {2520 bindings.forEach((unbind) => unbind());2521 });2522 },2523 },2524 };2525 // Error when attempting to run this function in a NodeJS environment.2526 if (isNodeProcess()) {2527 throw new Error('[MSW] Failed to execute `setupWorker` in a non-browser environment. Consider using `setupServer` for NodeJS environment instead.');2528 }2529 return {2530 start: createStart(context),2531 stop: createStop(context),2532 use(...handlers) {2533 use(context.requestHandlers, ...handlers);2534 },2535 restoreHandlers() {2536 restoreHandlers(context.requestHandlers);2537 },2538 resetHandlers(...nextHandlers) {2539 context.requestHandlers = resetHandlers(requestHandlers, ...nextHandlers);2540 },2541 };2542 }2543 /**2544 * Formats a mocked request for introspection in browser's console.2545 */2546 function prepareRequest(req) {2547 return Object.assign(Object.assign({}, req), { headers: req.headers.getAllHeaders() });2548 }2549 /**2550 * Formats a mocked response for introspection in browser's console.2551 */2552 function prepareResponse(res) {2553 const responseHeaders = lib.listToHeaders(res.headers);2554 return Object.assign(Object.assign({}, res), { 2555 // Parse a response JSON body for preview in the logs2556 body: parseBody(res.body, responseHeaders) });2557 }2558 function getTimestamp() {2559 const now = new Date();2560 return [now.getHours(), now.getMinutes(), now.getSeconds()]2561 .map(String)2562 .map((chunk) => chunk.slice(0, 2))2563 .map((chunk) => chunk.padStart(2, '0'))2564 .join(':');2565 }2566 /**2567 * Returns a HEX color for a given response status code number.2568 */2569 function getStatusCodeColor(status) {2570 if (status < 300) {2571 return '#69AB32';2572 }2573 if (status < 400) {2574 return '#F0BB4B';2575 }2576 return '#E95F5D';2577 }2578 /**2579 * Converts a string path to a Regular Expression.2580 * Transforms path parameters into named RegExp groups.2581 */2582 const pathToRegExp = (path) => {2583 const pattern = path2584 // Escape literal dots2585 .replace(/\./g, '\\.')2586 // Escape literal slashes2587 .replace(/\//g, '/')2588 // Escape literal question marks2589 .replace(/\?/g, '\\?')2590 // Ignore trailing slashes2591 .replace(/\/+$/, '')2592 // Replace wildcard with any zero-to-any character sequence2593 .replace(/\*+/g, '.*')2594 // Replace parameters with named capturing groups2595 .replace(/:([^\d|^\/][a-zA-Z0-9_]*(?=(?:\/|\\.)|$))/g, (_, paramName) => `(?<${paramName}>[^\/]+?)`)2596 // Allow optional trailing slash2597 .concat('(\\/|$)');2598 return new RegExp(pattern, 'gi');2599 };2600 /**2601 * Matches a given url against a path.2602 */2603 const match = (path, url) => {2604 const expression = path instanceof RegExp ? path : pathToRegExp(path);2605 const match = expression.exec(url) || false;2606 // Matches in strict mode: match string should equal to input (url)2607 // Otherwise loose matches will be considered truthy:2608 // match('/messages/:id', '/messages/123/users') // true2609 const matches = path instanceof RegExp ? !!match : !!match && match[0] === match.input;2610 return {2611 matches,2612 params: match && matches ? match.groups || null : null,2613 };2614 };2615 var getCleanUrl_1 = createCommonjsModule(function (module, exports) {2616 Object.defineProperty(exports, "__esModule", { value: true });2617 exports.getCleanUrl = void 0;2618 /**2619 * Removes query parameters and hashes from a given URL.2620 */2621 function getCleanUrl(url, isAbsolute) {2622 if (isAbsolute === void 0) { isAbsolute = true; }2623 return [isAbsolute && url.origin, url.pathname].filter(Boolean).join('');2624 }2625 exports.getCleanUrl = getCleanUrl;2626 });2627 /**2628 * Returns an absolute URL based on the given relative URL, if possible.2629 * Ignores regular expressions.2630 */2631 const getAbsoluteUrl = (mask) => {2632 // Global `location` object doesn't exist in Node.2633 // Relative request predicate URL cannot become absolute.2634 const hasLocation = typeof location !== 'undefined';2635 return typeof mask === 'string' && mask.startsWith('/')2636 ? `${hasLocation ? location.origin : ''}${mask}`2637 : mask;2638 };2639 /**2640 * Converts a given request handler mask into a URL, if given a valid URL string.2641 */2642 function getUrlByMask(mask) {2643 /**2644 * If a string mask contains an asterisk (wildcard), return it as-is.2645 * Converting a URL-like path string into an actual URL is misleading.2646 * @see https://github.com/mswjs/msw/issues/3572647 */2648 if (mask instanceof RegExp || mask.includes('*')) {2649 return mask;2650 }2651 try {2652 // Attempt to create a URL instance out of the mask string.2653 // Resolve mask to an absolute URL, because even a valid relative URL2654 // cannot be converted into the URL instance (required absolute URL only).2655 return new URL(getAbsoluteUrl(mask));2656 }2657 catch (error) {2658 // Otherwise, the mask is a path string.2659 return mask;2660 }2661 }2662 function getCleanMask(resolvedMask) {2663 return resolvedMask instanceof URL2664 ? getCleanUrl_1.getCleanUrl(resolvedMask)2665 : resolvedMask instanceof RegExp2666 ? resolvedMask2667 : getAbsoluteUrl(resolvedMask);2668 }2669 /**2670 * Returns the result of matching given request URL2671 * against a mask.2672 */2673 function matchRequestUrl(url, mask) {2674 const resolvedMask = getUrlByMask(mask);2675 const cleanMask = getCleanMask(resolvedMask);2676 const cleanRequestUrl = getCleanUrl_1.getCleanUrl(url);2677 return match(cleanMask, cleanRequestUrl);2678 }2679 (function (RESTMethods) {2680 RESTMethods["HEAD"] = "HEAD";2681 RESTMethods["GET"] = "GET";2682 RESTMethods["POST"] = "POST";2683 RESTMethods["PUT"] = "PUT";2684 RESTMethods["PATCH"] = "PATCH";2685 RESTMethods["OPTIONS"] = "OPTIONS";2686 RESTMethods["DELETE"] = "DELETE";2687 })(exports.RESTMethods || (exports.RESTMethods = {}));2688 const restContext = {2689 set,2690 status,2691 cookie,2692 body,2693 text,2694 json,2695 xml,2696 delay,2697 fetch,2698 };2699 const createRestHandler = (method) => {2700 return (mask, resolver) => {2701 const resolvedMask = getUrlByMask(mask);2702 return {2703 parse(req) {2704 // Match the request during parsing to prevent matching it twice2705 // in order to get the request URL parameters.2706 const match = matchRequestUrl(req.url, mask);2707 return {2708 match,2709 };2710 },2711 predicate(req, parsedRequest) {2712 return isStringEqual(method, req.method) && parsedRequest.match.matches;2713 },2714 getPublicRequest(req, parsedRequest) {2715 // Get request path parameters based on the given mask2716 const params = (mask && parsedRequest.match.params) || {};2717 return Object.assign(Object.assign({}, req), { params });2718 },2719 resolver,2720 defineContext() {2721 return restContext;2722 },2723 log(req, res, handler) {2724 // Warn on request handler URL containing query parameters.2725 if (resolvedMask instanceof URL && resolvedMask.search !== '') {2726 const queryParams = [];2727 resolvedMask.searchParams.forEach((_, paramName) => queryParams.push(paramName));2728 console.warn(`\2729[MSW] Found a redundant usage of query parameters in the request handler URL for "${method} ${mask}". Please match against a path instead, and access query parameters in the response resolver function:2730rest.${method.toLowerCase()}("${resolvedMask.pathname}", (req, res, ctx) => {2731 const query = req.url.searchParams2732${queryParams2733 .map((paramName) => `\2734 const ${paramName} = query.get("${paramName}")`)2735 .join('\n')}2736})\2737`);2738 }2739 const publicUrl = getPublicUrlFromRequest(req);2740 const loggedRequest = prepareRequest(req);2741 const loggedResponse = prepareResponse(res);2742 console.groupCollapsed('[MSW] %s %s %s (%c%s%c)', getTimestamp(), req.method, publicUrl, `color:${getStatusCodeColor(res.status)}`, res.status, 'color:inherit');2743 console.log('Request', loggedRequest);2744 console.log('Handler:', {2745 mask,2746 resolver: handler.resolver,2747 });2748 console.log('Response', loggedResponse);2749 console.groupEnd();2750 },2751 };2752 };2753 };2754 const rest = {2755 head: createRestHandler(exports.RESTMethods.HEAD),2756 get: createRestHandler(exports.RESTMethods.GET),2757 post: createRestHandler(exports.RESTMethods.POST),2758 put: createRestHandler(exports.RESTMethods.PUT),2759 delete: createRestHandler(exports.RESTMethods.DELETE),2760 patch: createRestHandler(exports.RESTMethods.PATCH),2761 options: createRestHandler(exports.RESTMethods.OPTIONS),2762 };2763 function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }2764 /**2765 * Return true if `value` is object-like. A value is object-like if it's not2766 * `null` and has a `typeof` result of "object".2767 */2768 function isObjectLike(value) {2769 return _typeof(value) == 'object' && value !== null;2770 }2771 // In ES2015 (or a polyfilled) environment, this will be Symbol.iterator2772 var SYMBOL_TO_STRING_TAG = typeof Symbol === 'function' && Symbol.toStringTag != null ? Symbol.toStringTag : '@@toStringTag';2773 /**2774 * Represents a location in a Source.2775 */2776 /**2777 * Takes a Source and a UTF-8 character offset, and returns the corresponding2778 * line and column as a SourceLocation.2779 */2780 function getLocation(source, position) {2781 var lineRegexp = /\r\n|[\n\r]/g;2782 var line = 1;2783 var column = position + 1;2784 var match;2785 while ((match = lineRegexp.exec(source.body)) && match.index < position) {2786 line += 1;2787 column = position + 1 - (match.index + match[0].length);2788 }2789 return {2790 line: line,2791 column: column2792 };2793 }2794 /**2795 * Render a helpful description of the location in the GraphQL Source document.2796 */2797 function printLocation(location) {2798 return printSourceLocation(location.source, getLocation(location.source, location.start));2799 }2800 /**2801 * Render a helpful description of the location in the GraphQL Source document.2802 */2803 function printSourceLocation(source, sourceLocation) {2804 var firstLineColumnOffset = source.locationOffset.column - 1;2805 var body = whitespace(firstLineColumnOffset) + source.body;2806 var lineIndex = sourceLocation.line - 1;2807 var lineOffset = source.locationOffset.line - 1;2808 var lineNum = sourceLocation.line + lineOffset;2809 var columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0;2810 var columnNum = sourceLocation.column + columnOffset;2811 var locationStr = "".concat(source.name, ":").concat(lineNum, ":").concat(columnNum, "\n");2812 var lines = body.split(/\r\n|[\n\r]/g);2813 var locationLine = lines[lineIndex]; // Special case for minified documents2814 if (locationLine.length > 120) {2815 var subLineIndex = Math.floor(columnNum / 80);2816 var subLineColumnNum = columnNum % 80;2817 var subLines = [];2818 for (var i = 0; i < locationLine.length; i += 80) {2819 subLines.push(locationLine.slice(i, i + 80));2820 }2821 return locationStr + printPrefixedLines([["".concat(lineNum), subLines[0]]].concat(subLines.slice(1, subLineIndex + 1).map(function (subLine) {2822 return ['', subLine];2823 }), [[' ', whitespace(subLineColumnNum - 1) + '^'], ['', subLines[subLineIndex + 1]]]));2824 }2825 return locationStr + printPrefixedLines([// Lines specified like this: ["prefix", "string"],2826 ["".concat(lineNum - 1), lines[lineIndex - 1]], ["".concat(lineNum), locationLine], ['', whitespace(columnNum - 1) + '^'], ["".concat(lineNum + 1), lines[lineIndex + 1]]]);2827 }2828 function printPrefixedLines(lines) {2829 var existingLines = lines.filter(function (_ref) {2830 var _ = _ref[0],2831 line = _ref[1];2832 return line !== undefined;2833 });2834 var padLen = Math.max.apply(Math, existingLines.map(function (_ref2) {2835 var prefix = _ref2[0];2836 return prefix.length;2837 }));2838 return existingLines.map(function (_ref3) {2839 var prefix = _ref3[0],2840 line = _ref3[1];2841 return leftPad(padLen, prefix) + (line ? ' | ' + line : ' |');2842 }).join('\n');2843 }2844 function whitespace(len) {2845 return Array(len + 1).join(' ');2846 }2847 function leftPad(len, str) {2848 return whitespace(len - str.length) + str;2849 }2850 function _typeof$1(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$1 = function _typeof(obj) { return typeof obj; }; } else { _typeof$1 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$1(obj); }2851 function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }2852 function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }2853 function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }2854 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); }2855 function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }2856 function _possibleConstructorReturn(self, call) { if (call && (_typeof$1(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }2857 function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }2858 function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }2859 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; }; } return _construct.apply(null, arguments); }2860 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; } }2861 function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }2862 function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }2863 function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }2864 /**2865 * A GraphQLError describes an Error found during the parse, validate, or2866 * execute phases of performing a GraphQL operation. In addition to a message2867 * and stack trace, it also includes information about the locations in a2868 * GraphQL document and/or execution result that correspond to the Error.2869 */2870 var GraphQLError = /*#__PURE__*/function (_Error) {2871 _inherits(GraphQLError, _Error);2872 var _super = _createSuper(GraphQLError);2873 /**2874 * A message describing the Error for debugging purposes.2875 *2876 * Enumerable, and appears in the result of JSON.stringify().2877 *2878 * Note: should be treated as readonly, despite invariant usage.2879 */2880 /**2881 * An array of { line, column } locations within the source GraphQL document2882 * which correspond to this error.2883 *2884 * Errors during validation often contain multiple locations, for example to2885 * point out two things with the same name. Errors during execution include a2886 * single location, the field which produced the error.2887 *2888 * Enumerable, and appears in the result of JSON.stringify().2889 */2890 /**2891 * An array describing the JSON-path into the execution response which2892 * corresponds to this error. Only included for errors during execution.2893 *2894 * Enumerable, and appears in the result of JSON.stringify().2895 */2896 /**2897 * An array of GraphQL AST Nodes corresponding to this error.2898 */2899 /**2900 * The source GraphQL document for the first location of this error.2901 *2902 * Note that if this Error represents more than one node, the source may not2903 * represent nodes after the first node.2904 */2905 /**2906 * An array of character offsets within the source GraphQL document2907 * which correspond to this error.2908 */2909 /**2910 * The original error thrown from a field resolver during execution.2911 */2912 /**2913 * Extension fields to add to the formatted error.2914 */2915 function GraphQLError(message, nodes, source, positions, path, originalError, extensions) {2916 var _locations2, _source2, _positions2, _extensions2;2917 var _this;2918 _classCallCheck(this, GraphQLError);2919 _this = _super.call(this, message); // Compute list of blame nodes.2920 var _nodes = Array.isArray(nodes) ? nodes.length !== 0 ? nodes : undefined : nodes ? [nodes] : undefined; // Compute locations in the source for the given nodes/positions.2921 var _source = source;2922 if (!_source && _nodes) {2923 var _nodes$0$loc;2924 _source = (_nodes$0$loc = _nodes[0].loc) === null || _nodes$0$loc === void 0 ? void 0 : _nodes$0$loc.source;2925 }2926 var _positions = positions;2927 if (!_positions && _nodes) {2928 _positions = _nodes.reduce(function (list, node) {2929 if (node.loc) {2930 list.push(node.loc.start);2931 }2932 return list;2933 }, []);2934 }2935 if (_positions && _positions.length === 0) {2936 _positions = undefined;2937 }2938 var _locations;2939 if (positions && source) {2940 _locations = positions.map(function (pos) {2941 return getLocation(source, pos);2942 });2943 } else if (_nodes) {2944 _locations = _nodes.reduce(function (list, node) {2945 if (node.loc) {2946 list.push(getLocation(node.loc.source, node.loc.start));2947 }2948 return list;2949 }, []);2950 }2951 var _extensions = extensions;2952 if (_extensions == null && originalError != null) {2953 var originalExtensions = originalError.extensions;2954 if (isObjectLike(originalExtensions)) {2955 _extensions = originalExtensions;2956 }2957 }2958 Object.defineProperties(_assertThisInitialized(_this), {2959 name: {2960 value: 'GraphQLError'2961 },2962 message: {2963 value: message,2964 // By being enumerable, JSON.stringify will include `message` in the2965 // resulting output. This ensures that the simplest possible GraphQL2966 // service adheres to the spec.2967 enumerable: true,2968 writable: true2969 },2970 locations: {2971 // Coercing falsy values to undefined ensures they will not be included2972 // in JSON.stringify() when not provided.2973 value: (_locations2 = _locations) !== null && _locations2 !== void 0 ? _locations2 : undefined,2974 // By being enumerable, JSON.stringify will include `locations` in the2975 // resulting output. This ensures that the simplest possible GraphQL2976 // service adheres to the spec.2977 enumerable: _locations != null2978 },2979 path: {2980 // Coercing falsy values to undefined ensures they will not be included2981 // in JSON.stringify() when not provided.2982 value: path !== null && path !== void 0 ? path : undefined,2983 // By being enumerable, JSON.stringify will include `path` in the2984 // resulting output. This ensures that the simplest possible GraphQL2985 // service adheres to the spec.2986 enumerable: path != null2987 },2988 nodes: {2989 value: _nodes !== null && _nodes !== void 0 ? _nodes : undefined2990 },2991 source: {2992 value: (_source2 = _source) !== null && _source2 !== void 0 ? _source2 : undefined2993 },2994 positions: {2995 value: (_positions2 = _positions) !== null && _positions2 !== void 0 ? _positions2 : undefined2996 },2997 originalError: {2998 value: originalError2999 },3000 extensions: {3001 // Coercing falsy values to undefined ensures they will not be included3002 // in JSON.stringify() when not provided.3003 value: (_extensions2 = _extensions) !== null && _extensions2 !== void 0 ? _extensions2 : undefined,3004 // By being enumerable, JSON.stringify will include `path` in the3005 // resulting output. This ensures that the simplest possible GraphQL3006 // service adheres to the spec.3007 enumerable: _extensions != null3008 }3009 }); // Include (non-enumerable) stack trace.3010 if (originalError === null || originalError === void 0 ? void 0 : originalError.stack) {3011 Object.defineProperty(_assertThisInitialized(_this), 'stack', {3012 value: originalError.stack,3013 writable: true,3014 configurable: true3015 });3016 return _possibleConstructorReturn(_this);3017 } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')3018 if (Error.captureStackTrace) {3019 Error.captureStackTrace(_assertThisInitialized(_this), GraphQLError);3020 } else {3021 Object.defineProperty(_assertThisInitialized(_this), 'stack', {3022 value: Error().stack,3023 writable: true,3024 configurable: true3025 });3026 }3027 return _this;3028 }3029 _createClass(GraphQLError, [{3030 key: "toString",3031 value: function toString() {3032 return printError(this);3033 } // FIXME: workaround to not break chai comparisons, should be remove in v163034 // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet3035 }, {3036 key: SYMBOL_TO_STRING_TAG,3037 get: function get() {3038 return 'Object';3039 }3040 }]);3041 return GraphQLError;3042 }( /*#__PURE__*/_wrapNativeSuper(Error));3043 /**3044 * Prints a GraphQLError to a string, representing useful location information3045 * about the error's position in the source.3046 */3047 function printError(error) {3048 var output = error.message;3049 if (error.nodes) {3050 for (var _i2 = 0, _error$nodes2 = error.nodes; _i2 < _error$nodes2.length; _i2++) {3051 var node = _error$nodes2[_i2];3052 if (node.loc) {3053 output += '\n\n' + printLocation(node.loc);3054 }3055 }3056 } else if (error.source && error.locations) {3057 for (var _i4 = 0, _error$locations2 = error.locations; _i4 < _error$locations2.length; _i4++) {3058 var location = _error$locations2[_i4];3059 output += '\n\n' + printSourceLocation(error.source, location);3060 }3061 }3062 return output;3063 }3064 /**3065 * Produces a GraphQLError representing a syntax error, containing useful3066 * descriptive information about the syntax error's position in the source.3067 */3068 function syntaxError(source, position, description) {3069 return new GraphQLError("Syntax Error: ".concat(description), undefined, source, [position]);3070 }3071 /**3072 * The set of allowed kind values for AST nodes.3073 */3074 var Kind = Object.freeze({3075 // Name3076 NAME: 'Name',3077 // Document3078 DOCUMENT: 'Document',3079 OPERATION_DEFINITION: 'OperationDefinition',3080 VARIABLE_DEFINITION: 'VariableDefinition',3081 SELECTION_SET: 'SelectionSet',3082 FIELD: 'Field',3083 ARGUMENT: 'Argument',3084 // Fragments3085 FRAGMENT_SPREAD: 'FragmentSpread',3086 INLINE_FRAGMENT: 'InlineFragment',3087 FRAGMENT_DEFINITION: 'FragmentDefinition',3088 // Values3089 VARIABLE: 'Variable',3090 INT: 'IntValue',3091 FLOAT: 'FloatValue',3092 STRING: 'StringValue',3093 BOOLEAN: 'BooleanValue',3094 NULL: 'NullValue',3095 ENUM: 'EnumValue',3096 LIST: 'ListValue',3097 OBJECT: 'ObjectValue',3098 OBJECT_FIELD: 'ObjectField',3099 // Directives3100 DIRECTIVE: 'Directive',3101 // Types3102 NAMED_TYPE: 'NamedType',3103 LIST_TYPE: 'ListType',3104 NON_NULL_TYPE: 'NonNullType',3105 // Type System Definitions3106 SCHEMA_DEFINITION: 'SchemaDefinition',3107 OPERATION_TYPE_DEFINITION: 'OperationTypeDefinition',3108 // Type Definitions3109 SCALAR_TYPE_DEFINITION: 'ScalarTypeDefinition',3110 OBJECT_TYPE_DEFINITION: 'ObjectTypeDefinition',3111 FIELD_DEFINITION: 'FieldDefinition',3112 INPUT_VALUE_DEFINITION: 'InputValueDefinition',3113 INTERFACE_TYPE_DEFINITION: 'InterfaceTypeDefinition',3114 UNION_TYPE_DEFINITION: 'UnionTypeDefinition',3115 ENUM_TYPE_DEFINITION: 'EnumTypeDefinition',3116 ENUM_VALUE_DEFINITION: 'EnumValueDefinition',3117 INPUT_OBJECT_TYPE_DEFINITION: 'InputObjectTypeDefinition',3118 // Directive Definitions3119 DIRECTIVE_DEFINITION: 'DirectiveDefinition',3120 // Type System Extensions3121 SCHEMA_EXTENSION: 'SchemaExtension',3122 // Type Extensions3123 SCALAR_TYPE_EXTENSION: 'ScalarTypeExtension',3124 OBJECT_TYPE_EXTENSION: 'ObjectTypeExtension',3125 INTERFACE_TYPE_EXTENSION: 'InterfaceTypeExtension',3126 UNION_TYPE_EXTENSION: 'UnionTypeExtension',3127 ENUM_TYPE_EXTENSION: 'EnumTypeExtension',3128 INPUT_OBJECT_TYPE_EXTENSION: 'InputObjectTypeExtension'3129 });3130 /**3131 * The enum type representing the possible kind values of AST nodes.3132 */3133 function invariant(condition, message) {3134 var booleanCondition = Boolean(condition); // istanbul ignore else (See transformation done in './resources/inlineInvariant.js')3135 if (!booleanCondition) {3136 throw new Error(message != null ? message : 'Unexpected invariant triggered.');3137 }3138 }3139 // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')3140 var nodejsCustomInspectSymbol = typeof Symbol === 'function' && typeof Symbol.for === 'function' ? Symbol.for('nodejs.util.inspect.custom') : undefined;3141 /**3142 * The `defineInspect()` function defines `inspect()` prototype method as alias of `toJSON`3143 */3144 function defineInspect(classObject) {3145 var fn = classObject.prototype.toJSON;3146 typeof fn === 'function' || invariant(0);3147 classObject.prototype.inspect = fn; // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2317')3148 if (nodejsCustomInspectSymbol) {3149 classObject.prototype[nodejsCustomInspectSymbol] = fn;3150 }3151 }3152 /**3153 * Contains a range of UTF-8 character offsets and token references that3154 * identify the region of the source from which the AST derived.3155 */3156 var Location = /*#__PURE__*/function () {3157 /**3158 * The character offset at which this Node begins.3159 */3160 /**3161 * The character offset at which this Node ends.3162 */3163 /**3164 * The Token at which this Node begins.3165 */3166 /**3167 * The Token at which this Node ends.3168 */3169 /**3170 * The Source document the AST represents.3171 */3172 function Location(startToken, endToken, source) {3173 this.start = startToken.start;3174 this.end = endToken.end;3175 this.startToken = startToken;3176 this.endToken = endToken;3177 this.source = source;3178 }3179 var _proto = Location.prototype;3180 _proto.toJSON = function toJSON() {3181 return {3182 start: this.start,3183 end: this.end3184 };3185 };3186 return Location;3187 }(); // Print a simplified form when appearing in `inspect` and `util.inspect`.3188 defineInspect(Location);3189 /**3190 * Represents a range of characters represented by a lexical token3191 * within a Source.3192 */3193 var Token = /*#__PURE__*/function () {3194 /**3195 * The kind of Token.3196 */3197 /**3198 * The character offset at which this Node begins.3199 */3200 /**3201 * The character offset at which this Node ends.3202 */3203 /**3204 * The 1-indexed line number on which this Token appears.3205 */3206 /**3207 * The 1-indexed column number at which this Token begins.3208 */3209 /**3210 * For non-punctuation tokens, represents the interpreted value of the token.3211 */3212 /**3213 * Tokens exist as nodes in a double-linked-list amongst all tokens3214 * including ignored tokens. <SOF> is always the first node and <EOF>3215 * the last.3216 */3217 function Token(kind, start, end, line, column, prev, value) {3218 this.kind = kind;3219 this.start = start;3220 this.end = end;3221 this.line = line;3222 this.column = column;3223 this.value = value;3224 this.prev = prev;3225 this.next = null;3226 }3227 var _proto2 = Token.prototype;3228 _proto2.toJSON = function toJSON() {3229 return {3230 kind: this.kind,3231 value: this.value,3232 line: this.line,3233 column: this.column3234 };3235 };3236 return Token;3237 }(); // Print a simplified form when appearing in `inspect` and `util.inspect`.3238 defineInspect(Token);3239 /**3240 * The list of all possible AST node types.3241 */3242 /**3243 * An exported enum describing the different kinds of tokens that the3244 * lexer emits.3245 */3246 var TokenKind = Object.freeze({3247 SOF: '<SOF>',3248 EOF: '<EOF>',3249 BANG: '!',3250 DOLLAR: '$',3251 AMP: '&',3252 PAREN_L: '(',3253 PAREN_R: ')',3254 SPREAD: '...',3255 COLON: ':',3256 EQUALS: '=',3257 AT: '@',3258 BRACKET_L: '[',3259 BRACKET_R: ']',3260 BRACE_L: '{',3261 PIPE: '|',3262 BRACE_R: '}',3263 NAME: 'Name',3264 INT: 'Int',3265 FLOAT: 'Float',3266 STRING: 'String',3267 BLOCK_STRING: 'BlockString',3268 COMMENT: 'Comment'3269 });3270 /**3271 * The enum type representing the token kinds values.3272 */3273 function _typeof$2(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$2 = function _typeof(obj) { return typeof obj; }; } else { _typeof$2 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$2(obj); }3274 var MAX_ARRAY_LENGTH = 10;3275 var MAX_RECURSIVE_DEPTH = 2;3276 /**3277 * Used to print values in error messages.3278 */3279 function inspect(value) {3280 return formatValue(value, []);3281 }3282 function formatValue(value, seenValues) {3283 switch (_typeof$2(value)) {3284 case 'string':3285 return JSON.stringify(value);3286 case 'function':3287 return value.name ? "[function ".concat(value.name, "]") : '[function]';3288 case 'object':3289 if (value === null) {3290 return 'null';3291 }3292 return formatObjectValue(value, seenValues);3293 default:3294 return String(value);3295 }3296 }3297 function formatObjectValue(value, previouslySeenValues) {3298 if (previouslySeenValues.indexOf(value) !== -1) {3299 return '[Circular]';3300 }3301 var seenValues = [].concat(previouslySeenValues, [value]);3302 var customInspectFn = getCustomFn(value);3303 if (customInspectFn !== undefined) {3304 var customValue = customInspectFn.call(value); // check for infinite recursion3305 if (customValue !== value) {3306 return typeof customValue === 'string' ? customValue : formatValue(customValue, seenValues);3307 }3308 } else if (Array.isArray(value)) {3309 return formatArray(value, seenValues);3310 }3311 return formatObject(value, seenValues);3312 }3313 function formatObject(object, seenValues) {3314 var keys = Object.keys(object);3315 if (keys.length === 0) {3316 return '{}';3317 }3318 if (seenValues.length > MAX_RECURSIVE_DEPTH) {3319 return '[' + getObjectTag(object) + ']';3320 }3321 var properties = keys.map(function (key) {3322 var value = formatValue(object[key], seenValues);3323 return key + ': ' + value;3324 });3325 return '{ ' + properties.join(', ') + ' }';3326 }3327 function formatArray(array, seenValues) {3328 if (array.length === 0) {3329 return '[]';3330 }3331 if (seenValues.length > MAX_RECURSIVE_DEPTH) {3332 return '[Array]';3333 }3334 var len = Math.min(MAX_ARRAY_LENGTH, array.length);3335 var remaining = array.length - len;3336 var items = [];3337 for (var i = 0; i < len; ++i) {3338 items.push(formatValue(array[i], seenValues));3339 }3340 if (remaining === 1) {3341 items.push('... 1 more item');3342 } else if (remaining > 1) {3343 items.push("... ".concat(remaining, " more items"));3344 }3345 return '[' + items.join(', ') + ']';3346 }3347 function getCustomFn(object) {3348 var customInspectFn = object[String(nodejsCustomInspectSymbol)];3349 if (typeof customInspectFn === 'function') {3350 return customInspectFn;3351 }3352 if (typeof object.inspect === 'function') {3353 return object.inspect;3354 }3355 }3356 function getObjectTag(object) {3357 var tag = Object.prototype.toString.call(object).replace(/^\[object /, '').replace(/]$/, '');3358 if (tag === 'Object' && typeof object.constructor === 'function') {3359 var name = object.constructor.name;3360 if (typeof name === 'string' && name !== '') {3361 return name;3362 }3363 }3364 return tag;3365 }3366 function devAssert(condition, message) {3367 var booleanCondition = Boolean(condition); // istanbul ignore else (See transformation done in './resources/inlineInvariant.js')3368 if (!booleanCondition) {3369 throw new Error(message);3370 }3371 }3372 /**3373 * A replacement for instanceof which includes an error warning when multi-realm3374 * constructors are detected.3375 */3376 // See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production3377 // See: https://webpack.js.org/guides/production/3378 var instanceOf = process.env.NODE_ENV === 'production' ? // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')3379 // eslint-disable-next-line no-shadow3380 function instanceOf(value, constructor) {3381 return value instanceof constructor;3382 } : // eslint-disable-next-line no-shadow3383 function instanceOf(value, constructor) {3384 if (value instanceof constructor) {3385 return true;3386 }3387 if (value) {3388 var valueClass = value.constructor;3389 var className = constructor.name;3390 if (className && valueClass && valueClass.name === className) {3391 throw new Error("Cannot use ".concat(className, " \"").concat(value, "\" from another module or realm.\n\nEnsure that there is only one instance of \"graphql\" in the node_modules\ndirectory. If different versions of \"graphql\" are the dependencies of other\nrelied on modules, use \"resolutions\" to ensure only one version is installed.\n\nhttps://yarnpkg.com/en/docs/selective-version-resolutions\n\nDuplicate \"graphql\" modules cannot be used at the same time since different\nversions may have different capabilities and behavior. The data from one\nversion used in the function from another could produce confusing and\nspurious results."));3392 }3393 }3394 return false;3395 };3396 function _defineProperties$1(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }3397 function _createClass$1(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$1(Constructor.prototype, protoProps); if (staticProps) _defineProperties$1(Constructor, staticProps); return Constructor; }3398 /**3399 * A representation of source input to GraphQL. The `name` and `locationOffset` parameters are3400 * optional, but they are useful for clients who store GraphQL documents in source files.3401 * For example, if the GraphQL input starts at line 40 in a file named `Foo.graphql`, it might3402 * be useful for `name` to be `"Foo.graphql"` and location to be `{ line: 40, column: 1 }`.3403 * The `line` and `column` properties in `locationOffset` are 1-indexed.3404 */3405 var Source = /*#__PURE__*/function () {3406 function Source(body) {3407 var name = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'GraphQL request';3408 var locationOffset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {3409 line: 1,3410 column: 13411 };3412 typeof body === 'string' || devAssert(0, "Body must be a string. Received: ".concat(inspect(body), "."));3413 this.body = body;3414 this.name = name;3415 this.locationOffset = locationOffset;3416 this.locationOffset.line > 0 || devAssert(0, 'line in locationOffset is 1-indexed and must be positive.');3417 this.locationOffset.column > 0 || devAssert(0, 'column in locationOffset is 1-indexed and must be positive.');3418 } // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet3419 _createClass$1(Source, [{3420 key: SYMBOL_TO_STRING_TAG,3421 get: function get() {3422 return 'Source';3423 }3424 }]);3425 return Source;3426 }();3427 /**3428 * Test if the given value is a Source object.3429 *3430 * @internal3431 */3432 // eslint-disable-next-line no-redeclare3433 function isSource(source) {3434 return instanceOf(source, Source);3435 }3436 /**3437 * The set of allowed directive location values.3438 */3439 var DirectiveLocation = Object.freeze({3440 // Request Definitions3441 QUERY: 'QUERY',3442 MUTATION: 'MUTATION',3443 SUBSCRIPTION: 'SUBSCRIPTION',3444 FIELD: 'FIELD',3445 FRAGMENT_DEFINITION: 'FRAGMENT_DEFINITION',3446 FRAGMENT_SPREAD: 'FRAGMENT_SPREAD',3447 INLINE_FRAGMENT: 'INLINE_FRAGMENT',3448 VARIABLE_DEFINITION: 'VARIABLE_DEFINITION',3449 // Type System Definitions3450 SCHEMA: 'SCHEMA',3451 SCALAR: 'SCALAR',3452 OBJECT: 'OBJECT',3453 FIELD_DEFINITION: 'FIELD_DEFINITION',3454 ARGUMENT_DEFINITION: 'ARGUMENT_DEFINITION',3455 INTERFACE: 'INTERFACE',3456 UNION: 'UNION',3457 ENUM: 'ENUM',3458 ENUM_VALUE: 'ENUM_VALUE',3459 INPUT_OBJECT: 'INPUT_OBJECT',3460 INPUT_FIELD_DEFINITION: 'INPUT_FIELD_DEFINITION'3461 });3462 /**3463 * The enum type representing the directive location values.3464 */3465 /**3466 * Produces the value of a block string from its parsed raw value, similar to3467 * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc.3468 *3469 * This implements the GraphQL spec's BlockStringValue() static algorithm.3470 *3471 * @internal3472 */3473 function dedentBlockStringValue(rawString) {3474 // Expand a block string's raw value into independent lines.3475 var lines = rawString.split(/\r\n|[\n\r]/g); // Remove common indentation from all lines but first.3476 var commonIndent = getBlockStringIndentation(rawString);3477 if (commonIndent !== 0) {3478 for (var i = 1; i < lines.length; i++) {3479 lines[i] = lines[i].slice(commonIndent);3480 }3481 } // Remove leading and trailing blank lines.3482 var startLine = 0;3483 while (startLine < lines.length && isBlank(lines[startLine])) {3484 ++startLine;3485 }3486 var endLine = lines.length;3487 while (endLine > startLine && isBlank(lines[endLine - 1])) {3488 --endLine;3489 } // Return a string of the lines joined with U+000A.3490 return lines.slice(startLine, endLine).join('\n');3491 }3492 function isBlank(str) {3493 for (var i = 0; i < str.length; ++i) {3494 if (str[i] !== ' ' && str[i] !== '\t') {3495 return false;3496 }3497 }3498 return true;3499 }3500 /**3501 * @internal3502 */3503 function getBlockStringIndentation(value) {3504 var _commonIndent;3505 var isFirstLine = true;3506 var isEmptyLine = true;3507 var indent = 0;3508 var commonIndent = null;3509 for (var i = 0; i < value.length; ++i) {3510 switch (value.charCodeAt(i)) {3511 case 13:3512 // \r3513 if (value.charCodeAt(i + 1) === 10) {3514 ++i; // skip \r\n as one symbol3515 }3516 // falls through3517 case 10:3518 // \n3519 isFirstLine = false;3520 isEmptyLine = true;3521 indent = 0;3522 break;3523 case 9: // \t3524 case 32:3525 // <space>3526 ++indent;3527 break;3528 default:3529 if (isEmptyLine && !isFirstLine && (commonIndent === null || indent < commonIndent)) {3530 commonIndent = indent;3531 }3532 isEmptyLine = false;3533 }3534 }3535 return (_commonIndent = commonIndent) !== null && _commonIndent !== void 0 ? _commonIndent : 0;3536 }3537 /**3538 * Given a Source object, creates a Lexer for that source.3539 * A Lexer is a stateful stream generator in that every time3540 * it is advanced, it returns the next token in the Source. Assuming the3541 * source lexes, the final Token emitted by the lexer will be of kind3542 * EOF, after which the lexer will repeatedly return the same EOF token3543 * whenever called.3544 */3545 var Lexer = /*#__PURE__*/function () {3546 /**3547 * The previously focused non-ignored token.3548 */3549 /**3550 * The currently focused non-ignored token.3551 */3552 /**3553 * The (1-indexed) line containing the current token.3554 */3555 /**3556 * The character offset at which the current line begins.3557 */3558 function Lexer(source) {3559 var startOfFileToken = new Token(TokenKind.SOF, 0, 0, 0, 0, null);3560 this.source = source;3561 this.lastToken = startOfFileToken;3562 this.token = startOfFileToken;3563 this.line = 1;3564 this.lineStart = 0;3565 }3566 /**3567 * Advances the token stream to the next non-ignored token.3568 */3569 var _proto = Lexer.prototype;3570 _proto.advance = function advance() {3571 this.lastToken = this.token;3572 var token = this.token = this.lookahead();3573 return token;3574 }3575 /**3576 * Looks ahead and returns the next non-ignored token, but does not change3577 * the state of Lexer.3578 */3579 ;3580 _proto.lookahead = function lookahead() {3581 var token = this.token;3582 if (token.kind !== TokenKind.EOF) {3583 do {3584 var _token$next;3585 // Note: next is only mutable during parsing, so we cast to allow this.3586 token = (_token$next = token.next) !== null && _token$next !== void 0 ? _token$next : token.next = readToken(this, token);3587 } while (token.kind === TokenKind.COMMENT);3588 }3589 return token;3590 };3591 return Lexer;3592 }();3593 /**3594 * @internal3595 */3596 function isPunctuatorTokenKind(kind) {3597 return kind === TokenKind.BANG || kind === TokenKind.DOLLAR || kind === TokenKind.AMP || kind === TokenKind.PAREN_L || kind === TokenKind.PAREN_R || kind === TokenKind.SPREAD || kind === TokenKind.COLON || kind === TokenKind.EQUALS || kind === TokenKind.AT || kind === TokenKind.BRACKET_L || kind === TokenKind.BRACKET_R || kind === TokenKind.BRACE_L || kind === TokenKind.PIPE || kind === TokenKind.BRACE_R;3598 }3599 function printCharCode(code) {3600 return (// NaN/undefined represents access beyond the end of the file.3601 isNaN(code) ? TokenKind.EOF : // Trust JSON for ASCII.3602 code < 0x007f ? JSON.stringify(String.fromCharCode(code)) : // Otherwise print the escaped form.3603 "\"\\u".concat(('00' + code.toString(16).toUpperCase()).slice(-4), "\"")3604 );3605 }3606 /**3607 * Gets the next token from the source starting at the given position.3608 *3609 * This skips over whitespace until it finds the next lexable token, then lexes3610 * punctuators immediately or calls the appropriate helper function for more3611 * complicated tokens.3612 */3613 function readToken(lexer, prev) {3614 var source = lexer.source;3615 var body = source.body;3616 var bodyLength = body.length;3617 var pos = prev.end;3618 while (pos < bodyLength) {3619 var code = body.charCodeAt(pos);3620 var _line = lexer.line;3621 var _col = 1 + pos - lexer.lineStart; // SourceCharacter3622 switch (code) {3623 case 0xfeff: // <BOM>3624 case 9: // \t3625 case 32: // <space>3626 case 44:3627 // ,3628 ++pos;3629 continue;3630 case 10:3631 // \n3632 ++pos;3633 ++lexer.line;3634 lexer.lineStart = pos;3635 continue;3636 case 13:3637 // \r3638 if (body.charCodeAt(pos + 1) === 10) {3639 pos += 2;3640 } else {3641 ++pos;3642 }3643 ++lexer.line;3644 lexer.lineStart = pos;3645 continue;3646 case 33:3647 // !3648 return new Token(TokenKind.BANG, pos, pos + 1, _line, _col, prev);3649 case 35:3650 // #3651 return readComment(source, pos, _line, _col, prev);3652 case 36:3653 // $3654 return new Token(TokenKind.DOLLAR, pos, pos + 1, _line, _col, prev);3655 case 38:3656 // &3657 return new Token(TokenKind.AMP, pos, pos + 1, _line, _col, prev);3658 case 40:3659 // (3660 return new Token(TokenKind.PAREN_L, pos, pos + 1, _line, _col, prev);3661 case 41:3662 // )3663 return new Token(TokenKind.PAREN_R, pos, pos + 1, _line, _col, prev);3664 case 46:3665 // .3666 if (body.charCodeAt(pos + 1) === 46 && body.charCodeAt(pos + 2) === 46) {3667 return new Token(TokenKind.SPREAD, pos, pos + 3, _line, _col, prev);3668 }3669 break;3670 case 58:3671 // :3672 return new Token(TokenKind.COLON, pos, pos + 1, _line, _col, prev);3673 case 61:3674 // =3675 return new Token(TokenKind.EQUALS, pos, pos + 1, _line, _col, prev);3676 case 64:3677 // @3678 return new Token(TokenKind.AT, pos, pos + 1, _line, _col, prev);3679 case 91:3680 // [3681 return new Token(TokenKind.BRACKET_L, pos, pos + 1, _line, _col, prev);3682 case 93:3683 // ]3684 return new Token(TokenKind.BRACKET_R, pos, pos + 1, _line, _col, prev);3685 case 123:3686 // {3687 return new Token(TokenKind.BRACE_L, pos, pos + 1, _line, _col, prev);3688 case 124:3689 // |3690 return new Token(TokenKind.PIPE, pos, pos + 1, _line, _col, prev);3691 case 125:3692 // }3693 return new Token(TokenKind.BRACE_R, pos, pos + 1, _line, _col, prev);3694 case 34:3695 // "3696 if (body.charCodeAt(pos + 1) === 34 && body.charCodeAt(pos + 2) === 34) {3697 return readBlockString(source, pos, _line, _col, prev, lexer);3698 }3699 return readString(source, pos, _line, _col, prev);3700 case 45: // -3701 case 48: // 03702 case 49: // 13703 case 50: // 23704 case 51: // 33705 case 52: // 43706 case 53: // 53707 case 54: // 63708 case 55: // 73709 case 56: // 83710 case 57:3711 // 93712 return readNumber(source, pos, code, _line, _col, prev);3713 case 65: // A3714 case 66: // B3715 case 67: // C3716 case 68: // D3717 case 69: // E3718 case 70: // F3719 case 71: // G3720 case 72: // H3721 case 73: // I3722 case 74: // J3723 case 75: // K3724 case 76: // L3725 case 77: // M3726 case 78: // N3727 case 79: // O3728 case 80: // P3729 case 81: // Q3730 case 82: // R3731 case 83: // S3732 case 84: // T3733 case 85: // U3734 case 86: // V3735 case 87: // W3736 case 88: // X3737 case 89: // Y3738 case 90: // Z3739 case 95: // _3740 case 97: // a3741 case 98: // b3742 case 99: // c3743 case 100: // d3744 case 101: // e3745 case 102: // f3746 case 103: // g3747 case 104: // h3748 case 105: // i3749 case 106: // j3750 case 107: // k3751 case 108: // l3752 case 109: // m3753 case 110: // n3754 case 111: // o3755 case 112: // p3756 case 113: // q3757 case 114: // r3758 case 115: // s3759 case 116: // t3760 case 117: // u3761 case 118: // v3762 case 119: // w3763 case 120: // x3764 case 121: // y3765 case 122:3766 // z3767 return readName(source, pos, _line, _col, prev);3768 }3769 throw syntaxError(source, pos, unexpectedCharacterMessage(code));3770 }3771 var line = lexer.line;3772 var col = 1 + pos - lexer.lineStart;3773 return new Token(TokenKind.EOF, bodyLength, bodyLength, line, col, prev);3774 }3775 /**3776 * Report a message that an unexpected character was encountered.3777 */3778 function unexpectedCharacterMessage(code) {3779 if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) {3780 return "Cannot contain the invalid character ".concat(printCharCode(code), ".");3781 }3782 if (code === 39) {3783 // '3784 return 'Unexpected single quote character (\'), did you mean to use a double quote (")?';3785 }3786 return "Cannot parse the unexpected character ".concat(printCharCode(code), ".");3787 }3788 /**3789 * Reads a comment token from the source file.3790 *3791 * #[\u0009\u0020-\uFFFF]*3792 */3793 function readComment(source, start, line, col, prev) {3794 var body = source.body;3795 var code;3796 var position = start;3797 do {3798 code = body.charCodeAt(++position);3799 } while (!isNaN(code) && ( // SourceCharacter but not LineTerminator3800 code > 0x001f || code === 0x0009));3801 return new Token(TokenKind.COMMENT, start, position, line, col, prev, body.slice(start + 1, position));3802 }3803 /**3804 * Reads a number token from the source file, either a float3805 * or an int depending on whether a decimal point appears.3806 *3807 * Int: -?(0|[1-9][0-9]*)3808 * Float: -?(0|[1-9][0-9]*)(\.[0-9]+)?((E|e)(+|-)?[0-9]+)?3809 */3810 function readNumber(source, start, firstCode, line, col, prev) {3811 var body = source.body;3812 var code = firstCode;3813 var position = start;3814 var isFloat = false;3815 if (code === 45) {3816 // -3817 code = body.charCodeAt(++position);3818 }3819 if (code === 48) {3820 // 03821 code = body.charCodeAt(++position);3822 if (code >= 48 && code <= 57) {3823 throw syntaxError(source, position, "Invalid number, unexpected digit after 0: ".concat(printCharCode(code), "."));3824 }3825 } else {3826 position = readDigits(source, position, code);3827 code = body.charCodeAt(position);3828 }3829 if (code === 46) {3830 // .3831 isFloat = true;3832 code = body.charCodeAt(++position);3833 position = readDigits(source, position, code);3834 code = body.charCodeAt(position);3835 }3836 if (code === 69 || code === 101) {3837 // E e3838 isFloat = true;3839 code = body.charCodeAt(++position);3840 if (code === 43 || code === 45) {3841 // + -3842 code = body.charCodeAt(++position);3843 }3844 position = readDigits(source, position, code);3845 code = body.charCodeAt(position);3846 } // Numbers cannot be followed by . or NameStart3847 if (code === 46 || isNameStart(code)) {3848 throw syntaxError(source, position, "Invalid number, expected digit but got: ".concat(printCharCode(code), "."));3849 }3850 return new Token(isFloat ? TokenKind.FLOAT : TokenKind.INT, start, position, line, col, prev, body.slice(start, position));3851 }3852 /**3853 * Returns the new position in the source after reading digits.3854 */3855 function readDigits(source, start, firstCode) {3856 var body = source.body;3857 var position = start;3858 var code = firstCode;3859 if (code >= 48 && code <= 57) {3860 // 0 - 93861 do {3862 code = body.charCodeAt(++position);3863 } while (code >= 48 && code <= 57); // 0 - 93864 return position;3865 }3866 throw syntaxError(source, position, "Invalid number, expected digit but got: ".concat(printCharCode(code), "."));3867 }3868 /**3869 * Reads a string token from the source file.3870 *3871 * "([^"\\\u000A\u000D]|(\\(u[0-9a-fA-F]{4}|["\\/bfnrt])))*"3872 */3873 function readString(source, start, line, col, prev) {3874 var body = source.body;3875 var position = start + 1;3876 var chunkStart = position;3877 var code = 0;3878 var value = '';3879 while (position < body.length && !isNaN(code = body.charCodeAt(position)) && // not LineTerminator3880 code !== 0x000a && code !== 0x000d) {3881 // Closing Quote (")3882 if (code === 34) {3883 value += body.slice(chunkStart, position);3884 return new Token(TokenKind.STRING, start, position + 1, line, col, prev, value);3885 } // SourceCharacter3886 if (code < 0x0020 && code !== 0x0009) {3887 throw syntaxError(source, position, "Invalid character within String: ".concat(printCharCode(code), "."));3888 }3889 ++position;3890 if (code === 92) {3891 // \3892 value += body.slice(chunkStart, position - 1);3893 code = body.charCodeAt(position);3894 switch (code) {3895 case 34:3896 value += '"';3897 break;3898 case 47:3899 value += '/';3900 break;3901 case 92:3902 value += '\\';3903 break;3904 case 98:3905 value += '\b';3906 break;3907 case 102:3908 value += '\f';3909 break;3910 case 110:3911 value += '\n';3912 break;3913 case 114:3914 value += '\r';3915 break;3916 case 116:3917 value += '\t';3918 break;3919 case 117:3920 {3921 // uXXXX3922 var charCode = uniCharCode(body.charCodeAt(position + 1), body.charCodeAt(position + 2), body.charCodeAt(position + 3), body.charCodeAt(position + 4));3923 if (charCode < 0) {3924 var invalidSequence = body.slice(position + 1, position + 5);3925 throw syntaxError(source, position, "Invalid character escape sequence: \\u".concat(invalidSequence, "."));3926 }3927 value += String.fromCharCode(charCode);3928 position += 4;3929 break;3930 }3931 default:3932 throw syntaxError(source, position, "Invalid character escape sequence: \\".concat(String.fromCharCode(code), "."));3933 }3934 ++position;3935 chunkStart = position;3936 }3937 }3938 throw syntaxError(source, position, 'Unterminated string.');3939 }3940 /**3941 * Reads a block string token from the source file.3942 *3943 * """("?"?(\\"""|\\(?!=""")|[^"\\]))*"""3944 */3945 function readBlockString(source, start, line, col, prev, lexer) {3946 var body = source.body;3947 var position = start + 3;3948 var chunkStart = position;3949 var code = 0;3950 var rawValue = '';3951 while (position < body.length && !isNaN(code = body.charCodeAt(position))) {3952 // Closing Triple-Quote (""")3953 if (code === 34 && body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34) {3954 rawValue += body.slice(chunkStart, position);3955 return new Token(TokenKind.BLOCK_STRING, start, position + 3, line, col, prev, dedentBlockStringValue(rawValue));3956 } // SourceCharacter3957 if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) {3958 throw syntaxError(source, position, "Invalid character within String: ".concat(printCharCode(code), "."));3959 }3960 if (code === 10) {3961 // new line3962 ++position;3963 ++lexer.line;3964 lexer.lineStart = position;3965 } else if (code === 13) {3966 // carriage return3967 if (body.charCodeAt(position + 1) === 10) {3968 position += 2;3969 } else {3970 ++position;3971 }3972 ++lexer.line;3973 lexer.lineStart = position;3974 } else if ( // Escape Triple-Quote (\""")3975 code === 92 && body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34 && body.charCodeAt(position + 3) === 34) {3976 rawValue += body.slice(chunkStart, position) + '"""';3977 position += 4;3978 chunkStart = position;3979 } else {3980 ++position;3981 }3982 }3983 throw syntaxError(source, position, 'Unterminated string.');3984 }3985 /**3986 * Converts four hexadecimal chars to the integer that the3987 * string represents. For example, uniCharCode('0','0','0','f')3988 * will return 15, and uniCharCode('0','0','f','f') returns 255.3989 *3990 * Returns a negative number on error, if a char was invalid.3991 *3992 * This is implemented by noting that char2hex() returns -1 on error,3993 * which means the result of ORing the char2hex() will also be negative.3994 */3995 function uniCharCode(a, b, c, d) {3996 return char2hex(a) << 12 | char2hex(b) << 8 | char2hex(c) << 4 | char2hex(d);3997 }3998 /**3999 * Converts a hex character to its integer value.4000 * '0' becomes 0, '9' becomes 94001 * 'A' becomes 10, 'F' becomes 154002 * 'a' becomes 10, 'f' becomes 154003 *4004 * Returns -1 on error.4005 */4006 function char2hex(a) {4007 return a >= 48 && a <= 57 ? a - 48 // 0-94008 : a >= 65 && a <= 70 ? a - 55 // A-F4009 : a >= 97 && a <= 102 ? a - 87 // a-f4010 : -1;4011 }4012 /**4013 * Reads an alphanumeric + underscore name from the source.4014 *4015 * [_A-Za-z][_0-9A-Za-z]*4016 */4017 function readName(source, start, line, col, prev) {4018 var body = source.body;4019 var bodyLength = body.length;4020 var position = start + 1;4021 var code = 0;4022 while (position !== bodyLength && !isNaN(code = body.charCodeAt(position)) && (code === 95 || // _4023 code >= 48 && code <= 57 || // 0-94024 code >= 65 && code <= 90 || // A-Z4025 code >= 97 && code <= 122) // a-z4026 ) {4027 ++position;4028 }4029 return new Token(TokenKind.NAME, start, position, line, col, prev, body.slice(start, position));4030 } // _ A-Z a-z4031 function isNameStart(code) {4032 return code === 95 || code >= 65 && code <= 90 || code >= 97 && code <= 122;4033 }4034 /**4035 * Configuration options to control parser behavior4036 */4037 /**4038 * Given a GraphQL source, parses it into a Document.4039 * Throws GraphQLError if a syntax error is encountered.4040 */4041 function parse$1(source, options) {4042 var parser = new Parser(source, options);4043 return parser.parseDocument();4044 }4045 /**4046 * This class is exported only to assist people in implementing their own parsers4047 * without duplicating too much code and should be used only as last resort for cases4048 * such as experimental syntax or if certain features could not be contributed upstream.4049 *4050 * It is still part of the internal API and is versioned, so any changes to it are never4051 * considered breaking changes. If you still need to support multiple versions of the4052 * library, please use the `versionInfo` variable for version detection.4053 *4054 * @internal4055 */4056 var Parser = /*#__PURE__*/function () {4057 function Parser(source, options) {4058 var sourceObj = isSource(source) ? source : new Source(source);4059 this._lexer = new Lexer(sourceObj);4060 this._options = options;4061 }4062 /**4063 * Converts a name lex token into a name parse node.4064 */4065 var _proto = Parser.prototype;4066 _proto.parseName = function parseName() {4067 var token = this.expectToken(TokenKind.NAME);4068 return {4069 kind: Kind.NAME,4070 value: token.value,4071 loc: this.loc(token)4072 };4073 } // Implements the parsing rules in the Document section.4074 /**4075 * Document : Definition+4076 */4077 ;4078 _proto.parseDocument = function parseDocument() {4079 var start = this._lexer.token;4080 return {4081 kind: Kind.DOCUMENT,4082 definitions: this.many(TokenKind.SOF, this.parseDefinition, TokenKind.EOF),4083 loc: this.loc(start)4084 };4085 }4086 /**4087 * Definition :4088 * - ExecutableDefinition4089 * - TypeSystemDefinition4090 * - TypeSystemExtension4091 *4092 * ExecutableDefinition :4093 * - OperationDefinition4094 * - FragmentDefinition4095 */4096 ;4097 _proto.parseDefinition = function parseDefinition() {4098 if (this.peek(TokenKind.NAME)) {4099 switch (this._lexer.token.value) {4100 case 'query':4101 case 'mutation':4102 case 'subscription':4103 return this.parseOperationDefinition();4104 case 'fragment':4105 return this.parseFragmentDefinition();4106 case 'schema':4107 case 'scalar':4108 case 'type':4109 case 'interface':4110 case 'union':4111 case 'enum':4112 case 'input':4113 case 'directive':4114 return this.parseTypeSystemDefinition();4115 case 'extend':4116 return this.parseTypeSystemExtension();4117 }4118 } else if (this.peek(TokenKind.BRACE_L)) {4119 return this.parseOperationDefinition();4120 } else if (this.peekDescription()) {4121 return this.parseTypeSystemDefinition();4122 }4123 throw this.unexpected();4124 } // Implements the parsing rules in the Operations section.4125 /**4126 * OperationDefinition :4127 * - SelectionSet4128 * - OperationType Name? VariableDefinitions? Directives? SelectionSet4129 */4130 ;4131 _proto.parseOperationDefinition = function parseOperationDefinition() {4132 var start = this._lexer.token;4133 if (this.peek(TokenKind.BRACE_L)) {4134 return {4135 kind: Kind.OPERATION_DEFINITION,4136 operation: 'query',4137 name: undefined,4138 variableDefinitions: [],4139 directives: [],4140 selectionSet: this.parseSelectionSet(),4141 loc: this.loc(start)4142 };4143 }4144 var operation = this.parseOperationType();4145 var name;4146 if (this.peek(TokenKind.NAME)) {4147 name = this.parseName();4148 }4149 return {4150 kind: Kind.OPERATION_DEFINITION,4151 operation: operation,4152 name: name,4153 variableDefinitions: this.parseVariableDefinitions(),4154 directives: this.parseDirectives(false),4155 selectionSet: this.parseSelectionSet(),4156 loc: this.loc(start)4157 };4158 }4159 /**4160 * OperationType : one of query mutation subscription4161 */4162 ;4163 _proto.parseOperationType = function parseOperationType() {4164 var operationToken = this.expectToken(TokenKind.NAME);4165 switch (operationToken.value) {4166 case 'query':4167 return 'query';4168 case 'mutation':4169 return 'mutation';4170 case 'subscription':4171 return 'subscription';4172 }4173 throw this.unexpected(operationToken);4174 }4175 /**4176 * VariableDefinitions : ( VariableDefinition+ )4177 */4178 ;4179 _proto.parseVariableDefinitions = function parseVariableDefinitions() {4180 return this.optionalMany(TokenKind.PAREN_L, this.parseVariableDefinition, TokenKind.PAREN_R);4181 }4182 /**4183 * VariableDefinition : Variable : Type DefaultValue? Directives[Const]?4184 */4185 ;4186 _proto.parseVariableDefinition = function parseVariableDefinition() {4187 var start = this._lexer.token;4188 return {4189 kind: Kind.VARIABLE_DEFINITION,4190 variable: this.parseVariable(),4191 type: (this.expectToken(TokenKind.COLON), this.parseTypeReference()),4192 defaultValue: this.expectOptionalToken(TokenKind.EQUALS) ? this.parseValueLiteral(true) : undefined,4193 directives: this.parseDirectives(true),4194 loc: this.loc(start)4195 };4196 }4197 /**4198 * Variable : $ Name4199 */4200 ;4201 _proto.parseVariable = function parseVariable() {4202 var start = this._lexer.token;4203 this.expectToken(TokenKind.DOLLAR);4204 return {4205 kind: Kind.VARIABLE,4206 name: this.parseName(),4207 loc: this.loc(start)4208 };4209 }4210 /**4211 * SelectionSet : { Selection+ }4212 */4213 ;4214 _proto.parseSelectionSet = function parseSelectionSet() {4215 var start = this._lexer.token;4216 return {4217 kind: Kind.SELECTION_SET,4218 selections: this.many(TokenKind.BRACE_L, this.parseSelection, TokenKind.BRACE_R),4219 loc: this.loc(start)4220 };4221 }4222 /**4223 * Selection :4224 * - Field4225 * - FragmentSpread4226 * - InlineFragment4227 */4228 ;4229 _proto.parseSelection = function parseSelection() {4230 return this.peek(TokenKind.SPREAD) ? this.parseFragment() : this.parseField();4231 }4232 /**4233 * Field : Alias? Name Arguments? Directives? SelectionSet?4234 *4235 * Alias : Name :4236 */4237 ;4238 _proto.parseField = function parseField() {4239 var start = this._lexer.token;4240 var nameOrAlias = this.parseName();4241 var alias;4242 var name;4243 if (this.expectOptionalToken(TokenKind.COLON)) {4244 alias = nameOrAlias;4245 name = this.parseName();4246 } else {4247 name = nameOrAlias;4248 }4249 return {4250 kind: Kind.FIELD,4251 alias: alias,4252 name: name,4253 arguments: this.parseArguments(false),4254 directives: this.parseDirectives(false),4255 selectionSet: this.peek(TokenKind.BRACE_L) ? this.parseSelectionSet() : undefined,4256 loc: this.loc(start)4257 };4258 }4259 /**4260 * Arguments[Const] : ( Argument[?Const]+ )4261 */4262 ;4263 _proto.parseArguments = function parseArguments(isConst) {4264 var item = isConst ? this.parseConstArgument : this.parseArgument;4265 return this.optionalMany(TokenKind.PAREN_L, item, TokenKind.PAREN_R);4266 }4267 /**4268 * Argument[Const] : Name : Value[?Const]4269 */4270 ;4271 _proto.parseArgument = function parseArgument() {4272 var start = this._lexer.token;4273 var name = this.parseName();4274 this.expectToken(TokenKind.COLON);4275 return {4276 kind: Kind.ARGUMENT,4277 name: name,4278 value: this.parseValueLiteral(false),4279 loc: this.loc(start)4280 };4281 };4282 _proto.parseConstArgument = function parseConstArgument() {4283 var start = this._lexer.token;4284 return {4285 kind: Kind.ARGUMENT,4286 name: this.parseName(),4287 value: (this.expectToken(TokenKind.COLON), this.parseValueLiteral(true)),4288 loc: this.loc(start)4289 };4290 } // Implements the parsing rules in the Fragments section.4291 /**4292 * Corresponds to both FragmentSpread and InlineFragment in the spec.4293 *4294 * FragmentSpread : ... FragmentName Directives?4295 *4296 * InlineFragment : ... TypeCondition? Directives? SelectionSet4297 */4298 ;4299 _proto.parseFragment = function parseFragment() {4300 var start = this._lexer.token;4301 this.expectToken(TokenKind.SPREAD);4302 var hasTypeCondition = this.expectOptionalKeyword('on');4303 if (!hasTypeCondition && this.peek(TokenKind.NAME)) {4304 return {4305 kind: Kind.FRAGMENT_SPREAD,4306 name: this.parseFragmentName(),4307 directives: this.parseDirectives(false),4308 loc: this.loc(start)4309 };4310 }4311 return {4312 kind: Kind.INLINE_FRAGMENT,4313 typeCondition: hasTypeCondition ? this.parseNamedType() : undefined,4314 directives: this.parseDirectives(false),4315 selectionSet: this.parseSelectionSet(),4316 loc: this.loc(start)4317 };4318 }4319 /**4320 * FragmentDefinition :4321 * - fragment FragmentName on TypeCondition Directives? SelectionSet4322 *4323 * TypeCondition : NamedType4324 */4325 ;4326 _proto.parseFragmentDefinition = function parseFragmentDefinition() {4327 var _this$_options;4328 var start = this._lexer.token;4329 this.expectKeyword('fragment'); // Experimental support for defining variables within fragments changes4330 // the grammar of FragmentDefinition:4331 // - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet4332 if (((_this$_options = this._options) === null || _this$_options === void 0 ? void 0 : _this$_options.experimentalFragmentVariables) === true) {4333 return {4334 kind: Kind.FRAGMENT_DEFINITION,4335 name: this.parseFragmentName(),4336 variableDefinitions: this.parseVariableDefinitions(),4337 typeCondition: (this.expectKeyword('on'), this.parseNamedType()),4338 directives: this.parseDirectives(false),4339 selectionSet: this.parseSelectionSet(),4340 loc: this.loc(start)4341 };4342 }4343 return {4344 kind: Kind.FRAGMENT_DEFINITION,4345 name: this.parseFragmentName(),4346 typeCondition: (this.expectKeyword('on'), this.parseNamedType()),4347 directives: this.parseDirectives(false),4348 selectionSet: this.parseSelectionSet(),4349 loc: this.loc(start)4350 };4351 }4352 /**4353 * FragmentName : Name but not `on`4354 */4355 ;4356 _proto.parseFragmentName = function parseFragmentName() {4357 if (this._lexer.token.value === 'on') {4358 throw this.unexpected();4359 }4360 return this.parseName();4361 } // Implements the parsing rules in the Values section.4362 /**4363 * Value[Const] :4364 * - [~Const] Variable4365 * - IntValue4366 * - FloatValue4367 * - StringValue4368 * - BooleanValue4369 * - NullValue4370 * - EnumValue4371 * - ListValue[?Const]4372 * - ObjectValue[?Const]4373 *4374 * BooleanValue : one of `true` `false`4375 *4376 * NullValue : `null`4377 *4378 * EnumValue : Name but not `true`, `false` or `null`4379 */4380 ;4381 _proto.parseValueLiteral = function parseValueLiteral(isConst) {4382 var token = this._lexer.token;4383 switch (token.kind) {4384 case TokenKind.BRACKET_L:4385 return this.parseList(isConst);4386 case TokenKind.BRACE_L:4387 return this.parseObject(isConst);4388 case TokenKind.INT:4389 this._lexer.advance();4390 return {4391 kind: Kind.INT,4392 value: token.value,4393 loc: this.loc(token)4394 };4395 case TokenKind.FLOAT:4396 this._lexer.advance();4397 return {4398 kind: Kind.FLOAT,4399 value: token.value,4400 loc: this.loc(token)4401 };4402 case TokenKind.STRING:4403 case TokenKind.BLOCK_STRING:4404 return this.parseStringLiteral();4405 case TokenKind.NAME:4406 this._lexer.advance();4407 switch (token.value) {4408 case 'true':4409 return {4410 kind: Kind.BOOLEAN,4411 value: true,4412 loc: this.loc(token)4413 };4414 case 'false':4415 return {4416 kind: Kind.BOOLEAN,4417 value: false,4418 loc: this.loc(token)4419 };4420 case 'null':4421 return {4422 kind: Kind.NULL,4423 loc: this.loc(token)4424 };4425 default:4426 return {4427 kind: Kind.ENUM,4428 value: token.value,4429 loc: this.loc(token)4430 };4431 }4432 case TokenKind.DOLLAR:4433 if (!isConst) {4434 return this.parseVariable();4435 }4436 break;4437 }4438 throw this.unexpected();4439 };4440 _proto.parseStringLiteral = function parseStringLiteral() {4441 var token = this._lexer.token;4442 this._lexer.advance();4443 return {4444 kind: Kind.STRING,4445 value: token.value,4446 block: token.kind === TokenKind.BLOCK_STRING,4447 loc: this.loc(token)4448 };4449 }4450 /**4451 * ListValue[Const] :4452 * - [ ]4453 * - [ Value[?Const]+ ]4454 */4455 ;4456 _proto.parseList = function parseList(isConst) {4457 var _this = this;4458 var start = this._lexer.token;4459 var item = function item() {4460 return _this.parseValueLiteral(isConst);4461 };4462 return {4463 kind: Kind.LIST,4464 values: this.any(TokenKind.BRACKET_L, item, TokenKind.BRACKET_R),4465 loc: this.loc(start)4466 };4467 }4468 /**4469 * ObjectValue[Const] :4470 * - { }4471 * - { ObjectField[?Const]+ }4472 */4473 ;4474 _proto.parseObject = function parseObject(isConst) {4475 var _this2 = this;4476 var start = this._lexer.token;4477 var item = function item() {4478 return _this2.parseObjectField(isConst);4479 };4480 return {4481 kind: Kind.OBJECT,4482 fields: this.any(TokenKind.BRACE_L, item, TokenKind.BRACE_R),4483 loc: this.loc(start)4484 };4485 }4486 /**4487 * ObjectField[Const] : Name : Value[?Const]4488 */4489 ;4490 _proto.parseObjectField = function parseObjectField(isConst) {4491 var start = this._lexer.token;4492 var name = this.parseName();4493 this.expectToken(TokenKind.COLON);4494 return {4495 kind: Kind.OBJECT_FIELD,4496 name: name,4497 value: this.parseValueLiteral(isConst),4498 loc: this.loc(start)4499 };4500 } // Implements the parsing rules in the Directives section.4501 /**4502 * Directives[Const] : Directive[?Const]+4503 */4504 ;4505 _proto.parseDirectives = function parseDirectives(isConst) {4506 var directives = [];4507 while (this.peek(TokenKind.AT)) {4508 directives.push(this.parseDirective(isConst));4509 }4510 return directives;4511 }4512 /**4513 * Directive[Const] : @ Name Arguments[?Const]?4514 */4515 ;4516 _proto.parseDirective = function parseDirective(isConst) {4517 var start = this._lexer.token;4518 this.expectToken(TokenKind.AT);4519 return {4520 kind: Kind.DIRECTIVE,4521 name: this.parseName(),4522 arguments: this.parseArguments(isConst),4523 loc: this.loc(start)4524 };4525 } // Implements the parsing rules in the Types section.4526 /**4527 * Type :4528 * - NamedType4529 * - ListType4530 * - NonNullType4531 */4532 ;4533 _proto.parseTypeReference = function parseTypeReference() {4534 var start = this._lexer.token;4535 var type;4536 if (this.expectOptionalToken(TokenKind.BRACKET_L)) {4537 type = this.parseTypeReference();4538 this.expectToken(TokenKind.BRACKET_R);4539 type = {4540 kind: Kind.LIST_TYPE,4541 type: type,4542 loc: this.loc(start)4543 };4544 } else {4545 type = this.parseNamedType();4546 }4547 if (this.expectOptionalToken(TokenKind.BANG)) {4548 return {4549 kind: Kind.NON_NULL_TYPE,4550 type: type,4551 loc: this.loc(start)4552 };4553 }4554 return type;4555 }4556 /**4557 * NamedType : Name4558 */4559 ;4560 _proto.parseNamedType = function parseNamedType() {4561 var start = this._lexer.token;4562 return {4563 kind: Kind.NAMED_TYPE,4564 name: this.parseName(),4565 loc: this.loc(start)4566 };4567 } // Implements the parsing rules in the Type Definition section.4568 /**4569 * TypeSystemDefinition :4570 * - SchemaDefinition4571 * - TypeDefinition4572 * - DirectiveDefinition4573 *4574 * TypeDefinition :4575 * - ScalarTypeDefinition4576 * - ObjectTypeDefinition4577 * - InterfaceTypeDefinition4578 * - UnionTypeDefinition4579 * - EnumTypeDefinition4580 * - InputObjectTypeDefinition4581 */4582 ;4583 _proto.parseTypeSystemDefinition = function parseTypeSystemDefinition() {4584 // Many definitions begin with a description and require a lookahead.4585 var keywordToken = this.peekDescription() ? this._lexer.lookahead() : this._lexer.token;4586 if (keywordToken.kind === TokenKind.NAME) {4587 switch (keywordToken.value) {4588 case 'schema':4589 return this.parseSchemaDefinition();4590 case 'scalar':4591 return this.parseScalarTypeDefinition();4592 case 'type':4593 return this.parseObjectTypeDefinition();4594 case 'interface':4595 return this.parseInterfaceTypeDefinition();4596 case 'union':4597 return this.parseUnionTypeDefinition();4598 case 'enum':4599 return this.parseEnumTypeDefinition();4600 case 'input':4601 return this.parseInputObjectTypeDefinition();4602 case 'directive':4603 return this.parseDirectiveDefinition();4604 }4605 }4606 throw this.unexpected(keywordToken);4607 };4608 _proto.peekDescription = function peekDescription() {4609 return this.peek(TokenKind.STRING) || this.peek(TokenKind.BLOCK_STRING);4610 }4611 /**4612 * Description : StringValue4613 */4614 ;4615 _proto.parseDescription = function parseDescription() {4616 if (this.peekDescription()) {4617 return this.parseStringLiteral();4618 }4619 }4620 /**4621 * SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ }4622 */4623 ;4624 _proto.parseSchemaDefinition = function parseSchemaDefinition() {4625 var start = this._lexer.token;4626 var description = this.parseDescription();4627 this.expectKeyword('schema');4628 var directives = this.parseDirectives(true);4629 var operationTypes = this.many(TokenKind.BRACE_L, this.parseOperationTypeDefinition, TokenKind.BRACE_R);4630 return {4631 kind: Kind.SCHEMA_DEFINITION,4632 description: description,4633 directives: directives,4634 operationTypes: operationTypes,4635 loc: this.loc(start)4636 };4637 }4638 /**4639 * OperationTypeDefinition : OperationType : NamedType4640 */4641 ;4642 _proto.parseOperationTypeDefinition = function parseOperationTypeDefinition() {4643 var start = this._lexer.token;4644 var operation = this.parseOperationType();4645 this.expectToken(TokenKind.COLON);4646 var type = this.parseNamedType();4647 return {4648 kind: Kind.OPERATION_TYPE_DEFINITION,4649 operation: operation,4650 type: type,4651 loc: this.loc(start)4652 };4653 }4654 /**4655 * ScalarTypeDefinition : Description? scalar Name Directives[Const]?4656 */4657 ;4658 _proto.parseScalarTypeDefinition = function parseScalarTypeDefinition() {4659 var start = this._lexer.token;4660 var description = this.parseDescription();4661 this.expectKeyword('scalar');4662 var name = this.parseName();4663 var directives = this.parseDirectives(true);4664 return {4665 kind: Kind.SCALAR_TYPE_DEFINITION,4666 description: description,4667 name: name,4668 directives: directives,4669 loc: this.loc(start)4670 };4671 }4672 /**4673 * ObjectTypeDefinition :4674 * Description?4675 * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition?4676 */4677 ;4678 _proto.parseObjectTypeDefinition = function parseObjectTypeDefinition() {4679 var start = this._lexer.token;4680 var description = this.parseDescription();4681 this.expectKeyword('type');4682 var name = this.parseName();4683 var interfaces = this.parseImplementsInterfaces();4684 var directives = this.parseDirectives(true);4685 var fields = this.parseFieldsDefinition();4686 return {4687 kind: Kind.OBJECT_TYPE_DEFINITION,4688 description: description,4689 name: name,4690 interfaces: interfaces,4691 directives: directives,4692 fields: fields,4693 loc: this.loc(start)4694 };4695 }4696 /**4697 * ImplementsInterfaces :4698 * - implements `&`? NamedType4699 * - ImplementsInterfaces & NamedType4700 */4701 ;4702 _proto.parseImplementsInterfaces = function parseImplementsInterfaces() {4703 var _this$_options2;4704 if (!this.expectOptionalKeyword('implements')) {4705 return [];4706 }4707 if (((_this$_options2 = this._options) === null || _this$_options2 === void 0 ? void 0 : _this$_options2.allowLegacySDLImplementsInterfaces) === true) {4708 var types = []; // Optional leading ampersand4709 this.expectOptionalToken(TokenKind.AMP);4710 do {4711 types.push(this.parseNamedType());4712 } while (this.expectOptionalToken(TokenKind.AMP) || this.peek(TokenKind.NAME));4713 return types;4714 }4715 return this.delimitedMany(TokenKind.AMP, this.parseNamedType);4716 }4717 /**4718 * FieldsDefinition : { FieldDefinition+ }4719 */4720 ;4721 _proto.parseFieldsDefinition = function parseFieldsDefinition() {4722 var _this$_options3;4723 // Legacy support for the SDL?4724 if (((_this$_options3 = this._options) === null || _this$_options3 === void 0 ? void 0 : _this$_options3.allowLegacySDLEmptyFields) === true && this.peek(TokenKind.BRACE_L) && this._lexer.lookahead().kind === TokenKind.BRACE_R) {4725 this._lexer.advance();4726 this._lexer.advance();4727 return [];4728 }4729 return this.optionalMany(TokenKind.BRACE_L, this.parseFieldDefinition, TokenKind.BRACE_R);4730 }4731 /**4732 * FieldDefinition :4733 * - Description? Name ArgumentsDefinition? : Type Directives[Const]?4734 */4735 ;4736 _proto.parseFieldDefinition = function parseFieldDefinition() {4737 var start = this._lexer.token;4738 var description = this.parseDescription();4739 var name = this.parseName();4740 var args = this.parseArgumentDefs();4741 this.expectToken(TokenKind.COLON);4742 var type = this.parseTypeReference();4743 var directives = this.parseDirectives(true);4744 return {4745 kind: Kind.FIELD_DEFINITION,4746 description: description,4747 name: name,4748 arguments: args,4749 type: type,4750 directives: directives,4751 loc: this.loc(start)4752 };4753 }4754 /**4755 * ArgumentsDefinition : ( InputValueDefinition+ )4756 */4757 ;4758 _proto.parseArgumentDefs = function parseArgumentDefs() {4759 return this.optionalMany(TokenKind.PAREN_L, this.parseInputValueDef, TokenKind.PAREN_R);4760 }4761 /**4762 * InputValueDefinition :4763 * - Description? Name : Type DefaultValue? Directives[Const]?4764 */4765 ;4766 _proto.parseInputValueDef = function parseInputValueDef() {4767 var start = this._lexer.token;4768 var description = this.parseDescription();4769 var name = this.parseName();4770 this.expectToken(TokenKind.COLON);4771 var type = this.parseTypeReference();4772 var defaultValue;4773 if (this.expectOptionalToken(TokenKind.EQUALS)) {4774 defaultValue = this.parseValueLiteral(true);4775 }4776 var directives = this.parseDirectives(true);4777 return {4778 kind: Kind.INPUT_VALUE_DEFINITION,4779 description: description,4780 name: name,4781 type: type,4782 defaultValue: defaultValue,4783 directives: directives,4784 loc: this.loc(start)4785 };4786 }4787 /**4788 * InterfaceTypeDefinition :4789 * - Description? interface Name Directives[Const]? FieldsDefinition?4790 */4791 ;4792 _proto.parseInterfaceTypeDefinition = function parseInterfaceTypeDefinition() {4793 var start = this._lexer.token;4794 var description = this.parseDescription();4795 this.expectKeyword('interface');4796 var name = this.parseName();4797 var interfaces = this.parseImplementsInterfaces();4798 var directives = this.parseDirectives(true);4799 var fields = this.parseFieldsDefinition();4800 return {4801 kind: Kind.INTERFACE_TYPE_DEFINITION,4802 description: description,4803 name: name,4804 interfaces: interfaces,4805 directives: directives,4806 fields: fields,4807 loc: this.loc(start)4808 };4809 }4810 /**4811 * UnionTypeDefinition :4812 * - Description? union Name Directives[Const]? UnionMemberTypes?4813 */4814 ;4815 _proto.parseUnionTypeDefinition = function parseUnionTypeDefinition() {4816 var start = this._lexer.token;4817 var description = this.parseDescription();4818 this.expectKeyword('union');4819 var name = this.parseName();4820 var directives = this.parseDirectives(true);4821 var types = this.parseUnionMemberTypes();4822 return {4823 kind: Kind.UNION_TYPE_DEFINITION,4824 description: description,4825 name: name,4826 directives: directives,4827 types: types,4828 loc: this.loc(start)4829 };4830 }4831 /**4832 * UnionMemberTypes :4833 * - = `|`? NamedType4834 * - UnionMemberTypes | NamedType4835 */4836 ;4837 _proto.parseUnionMemberTypes = function parseUnionMemberTypes() {4838 return this.expectOptionalToken(TokenKind.EQUALS) ? this.delimitedMany(TokenKind.PIPE, this.parseNamedType) : [];4839 }4840 /**4841 * EnumTypeDefinition :4842 * - Description? enum Name Directives[Const]? EnumValuesDefinition?4843 */4844 ;4845 _proto.parseEnumTypeDefinition = function parseEnumTypeDefinition() {4846 var start = this._lexer.token;4847 var description = this.parseDescription();4848 this.expectKeyword('enum');4849 var name = this.parseName();4850 var directives = this.parseDirectives(true);4851 var values = this.parseEnumValuesDefinition();4852 return {4853 kind: Kind.ENUM_TYPE_DEFINITION,4854 description: description,4855 name: name,4856 directives: directives,4857 values: values,4858 loc: this.loc(start)4859 };4860 }4861 /**4862 * EnumValuesDefinition : { EnumValueDefinition+ }4863 */4864 ;4865 _proto.parseEnumValuesDefinition = function parseEnumValuesDefinition() {4866 return this.optionalMany(TokenKind.BRACE_L, this.parseEnumValueDefinition, TokenKind.BRACE_R);4867 }4868 /**4869 * EnumValueDefinition : Description? EnumValue Directives[Const]?4870 *4871 * EnumValue : Name4872 */4873 ;4874 _proto.parseEnumValueDefinition = function parseEnumValueDefinition() {4875 var start = this._lexer.token;4876 var description = this.parseDescription();4877 var name = this.parseName();4878 var directives = this.parseDirectives(true);4879 return {4880 kind: Kind.ENUM_VALUE_DEFINITION,4881 description: description,4882 name: name,4883 directives: directives,4884 loc: this.loc(start)4885 };4886 }4887 /**4888 * InputObjectTypeDefinition :4889 * - Description? input Name Directives[Const]? InputFieldsDefinition?4890 */4891 ;4892 _proto.parseInputObjectTypeDefinition = function parseInputObjectTypeDefinition() {4893 var start = this._lexer.token;4894 var description = this.parseDescription();4895 this.expectKeyword('input');4896 var name = this.parseName();4897 var directives = this.parseDirectives(true);4898 var fields = this.parseInputFieldsDefinition();4899 return {4900 kind: Kind.INPUT_OBJECT_TYPE_DEFINITION,4901 description: description,4902 name: name,4903 directives: directives,4904 fields: fields,4905 loc: this.loc(start)4906 };4907 }4908 /**4909 * InputFieldsDefinition : { InputValueDefinition+ }4910 */4911 ;4912 _proto.parseInputFieldsDefinition = function parseInputFieldsDefinition() {4913 return this.optionalMany(TokenKind.BRACE_L, this.parseInputValueDef, TokenKind.BRACE_R);4914 }4915 /**4916 * TypeSystemExtension :4917 * - SchemaExtension4918 * - TypeExtension4919 *4920 * TypeExtension :4921 * - ScalarTypeExtension4922 * - ObjectTypeExtension4923 * - InterfaceTypeExtension4924 * - UnionTypeExtension4925 * - EnumTypeExtension4926 * - InputObjectTypeDefinition4927 */4928 ;4929 _proto.parseTypeSystemExtension = function parseTypeSystemExtension() {4930 var keywordToken = this._lexer.lookahead();4931 if (keywordToken.kind === TokenKind.NAME) {4932 switch (keywordToken.value) {4933 case 'schema':4934 return this.parseSchemaExtension();4935 case 'scalar':4936 return this.parseScalarTypeExtension();4937 case 'type':4938 return this.parseObjectTypeExtension();4939 case 'interface':4940 return this.parseInterfaceTypeExtension();4941 case 'union':4942 return this.parseUnionTypeExtension();4943 case 'enum':4944 return this.parseEnumTypeExtension();4945 case 'input':4946 return this.parseInputObjectTypeExtension();4947 }4948 }4949 throw this.unexpected(keywordToken);4950 }4951 /**4952 * SchemaExtension :4953 * - extend schema Directives[Const]? { OperationTypeDefinition+ }4954 * - extend schema Directives[Const]4955 */4956 ;4957 _proto.parseSchemaExtension = function parseSchemaExtension() {4958 var start = this._lexer.token;4959 this.expectKeyword('extend');4960 this.expectKeyword('schema');4961 var directives = this.parseDirectives(true);4962 var operationTypes = this.optionalMany(TokenKind.BRACE_L, this.parseOperationTypeDefinition, TokenKind.BRACE_R);4963 if (directives.length === 0 && operationTypes.length === 0) {4964 throw this.unexpected();4965 }4966 return {4967 kind: Kind.SCHEMA_EXTENSION,4968 directives: directives,4969 operationTypes: operationTypes,4970 loc: this.loc(start)4971 };4972 }4973 /**4974 * ScalarTypeExtension :4975 * - extend scalar Name Directives[Const]4976 */4977 ;4978 _proto.parseScalarTypeExtension = function parseScalarTypeExtension() {4979 var start = this._lexer.token;4980 this.expectKeyword('extend');4981 this.expectKeyword('scalar');4982 var name = this.parseName();4983 var directives = this.parseDirectives(true);4984 if (directives.length === 0) {4985 throw this.unexpected();4986 }4987 return {4988 kind: Kind.SCALAR_TYPE_EXTENSION,4989 name: name,4990 directives: directives,4991 loc: this.loc(start)4992 };4993 }4994 /**4995 * ObjectTypeExtension :4996 * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition4997 * - extend type Name ImplementsInterfaces? Directives[Const]4998 * - extend type Name ImplementsInterfaces4999 */5000 ;5001 _proto.parseObjectTypeExtension = function parseObjectTypeExtension() {5002 var start = this._lexer.token;5003 this.expectKeyword('extend');5004 this.expectKeyword('type');5005 var name = this.parseName();5006 var interfaces = this.parseImplementsInterfaces();5007 var directives = this.parseDirectives(true);5008 var fields = this.parseFieldsDefinition();5009 if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) {5010 throw this.unexpected();5011 }5012 return {5013 kind: Kind.OBJECT_TYPE_EXTENSION,5014 name: name,5015 interfaces: interfaces,5016 directives: directives,5017 fields: fields,5018 loc: this.loc(start)5019 };5020 }5021 /**5022 * InterfaceTypeExtension :5023 * - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition5024 * - extend interface Name ImplementsInterfaces? Directives[Const]5025 * - extend interface Name ImplementsInterfaces5026 */5027 ;5028 _proto.parseInterfaceTypeExtension = function parseInterfaceTypeExtension() {5029 var start = this._lexer.token;5030 this.expectKeyword('extend');5031 this.expectKeyword('interface');5032 var name = this.parseName();5033 var interfaces = this.parseImplementsInterfaces();5034 var directives = this.parseDirectives(true);5035 var fields = this.parseFieldsDefinition();5036 if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) {5037 throw this.unexpected();5038 }5039 return {5040 kind: Kind.INTERFACE_TYPE_EXTENSION,5041 name: name,5042 interfaces: interfaces,5043 directives: directives,5044 fields: fields,5045 loc: this.loc(start)5046 };5047 }5048 /**5049 * UnionTypeExtension :5050 * - extend union Name Directives[Const]? UnionMemberTypes5051 * - extend union Name Directives[Const]5052 */5053 ;5054 _proto.parseUnionTypeExtension = function parseUnionTypeExtension() {5055 var start = this._lexer.token;5056 this.expectKeyword('extend');5057 this.expectKeyword('union');5058 var name = this.parseName();5059 var directives = this.parseDirectives(true);5060 var types = this.parseUnionMemberTypes();5061 if (directives.length === 0 && types.length === 0) {5062 throw this.unexpected();5063 }5064 return {5065 kind: Kind.UNION_TYPE_EXTENSION,5066 name: name,5067 directives: directives,5068 types: types,5069 loc: this.loc(start)5070 };5071 }5072 /**5073 * EnumTypeExtension :5074 * - extend enum Name Directives[Const]? EnumValuesDefinition5075 * - extend enum Name Directives[Const]5076 */5077 ;5078 _proto.parseEnumTypeExtension = function parseEnumTypeExtension() {5079 var start = this._lexer.token;5080 this.expectKeyword('extend');5081 this.expectKeyword('enum');5082 var name = this.parseName();5083 var directives = this.parseDirectives(true);5084 var values = this.parseEnumValuesDefinition();5085 if (directives.length === 0 && values.length === 0) {5086 throw this.unexpected();5087 }5088 return {5089 kind: Kind.ENUM_TYPE_EXTENSION,5090 name: name,5091 directives: directives,5092 values: values,5093 loc: this.loc(start)5094 };5095 }5096 /**5097 * InputObjectTypeExtension :5098 * - extend input Name Directives[Const]? InputFieldsDefinition5099 * - extend input Name Directives[Const]5100 */5101 ;5102 _proto.parseInputObjectTypeExtension = function parseInputObjectTypeExtension() {5103 var start = this._lexer.token;5104 this.expectKeyword('extend');5105 this.expectKeyword('input');5106 var name = this.parseName();5107 var directives = this.parseDirectives(true);5108 var fields = this.parseInputFieldsDefinition();5109 if (directives.length === 0 && fields.length === 0) {5110 throw this.unexpected();5111 }5112 return {5113 kind: Kind.INPUT_OBJECT_TYPE_EXTENSION,5114 name: name,5115 directives: directives,5116 fields: fields,5117 loc: this.loc(start)5118 };5119 }5120 /**5121 * DirectiveDefinition :5122 * - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations5123 */5124 ;5125 _proto.parseDirectiveDefinition = function parseDirectiveDefinition() {5126 var start = this._lexer.token;5127 var description = this.parseDescription();5128 this.expectKeyword('directive');5129 this.expectToken(TokenKind.AT);5130 var name = this.parseName();5131 var args = this.parseArgumentDefs();5132 var repeatable = this.expectOptionalKeyword('repeatable');5133 this.expectKeyword('on');5134 var locations = this.parseDirectiveLocations();5135 return {5136 kind: Kind.DIRECTIVE_DEFINITION,5137 description: description,5138 name: name,5139 arguments: args,5140 repeatable: repeatable,5141 locations: locations,5142 loc: this.loc(start)5143 };5144 }5145 /**5146 * DirectiveLocations :5147 * - `|`? DirectiveLocation5148 * - DirectiveLocations | DirectiveLocation5149 */5150 ;5151 _proto.parseDirectiveLocations = function parseDirectiveLocations() {5152 return this.delimitedMany(TokenKind.PIPE, this.parseDirectiveLocation);5153 }5154 /*5155 * DirectiveLocation :5156 * - ExecutableDirectiveLocation5157 * - TypeSystemDirectiveLocation5158 *5159 * ExecutableDirectiveLocation : one of5160 * `QUERY`5161 * `MUTATION`5162 * `SUBSCRIPTION`5163 * `FIELD`5164 * `FRAGMENT_DEFINITION`5165 * `FRAGMENT_SPREAD`5166 * `INLINE_FRAGMENT`5167 *5168 * TypeSystemDirectiveLocation : one of5169 * `SCHEMA`5170 * `SCALAR`5171 * `OBJECT`5172 * `FIELD_DEFINITION`5173 * `ARGUMENT_DEFINITION`5174 * `INTERFACE`5175 * `UNION`5176 * `ENUM`5177 * `ENUM_VALUE`5178 * `INPUT_OBJECT`5179 * `INPUT_FIELD_DEFINITION`5180 */5181 ;5182 _proto.parseDirectiveLocation = function parseDirectiveLocation() {5183 var start = this._lexer.token;5184 var name = this.parseName();5185 if (DirectiveLocation[name.value] !== undefined) {5186 return name;5187 }5188 throw this.unexpected(start);5189 } // Core parsing utility functions5190 /**5191 * Returns a location object, used to identify the place in the source that created a given parsed object.5192 */5193 ;5194 _proto.loc = function loc(startToken) {5195 var _this$_options4;5196 if (((_this$_options4 = this._options) === null || _this$_options4 === void 0 ? void 0 : _this$_options4.noLocation) !== true) {5197 return new Location(startToken, this._lexer.lastToken, this._lexer.source);5198 }5199 }5200 /**5201 * Determines if the next token is of a given kind5202 */5203 ;5204 _proto.peek = function peek(kind) {5205 return this._lexer.token.kind === kind;5206 }5207 /**5208 * If the next token is of the given kind, return that token after advancing the lexer.5209 * Otherwise, do not change the parser state and throw an error.5210 */5211 ;5212 _proto.expectToken = function expectToken(kind) {5213 var token = this._lexer.token;5214 if (token.kind === kind) {5215 this._lexer.advance();5216 return token;5217 }5218 throw syntaxError(this._lexer.source, token.start, "Expected ".concat(getTokenKindDesc(kind), ", found ").concat(getTokenDesc(token), "."));5219 }5220 /**5221 * If the next token is of the given kind, return that token after advancing the lexer.5222 * Otherwise, do not change the parser state and return undefined.5223 */5224 ;5225 _proto.expectOptionalToken = function expectOptionalToken(kind) {5226 var token = this._lexer.token;5227 if (token.kind === kind) {5228 this._lexer.advance();5229 return token;5230 }5231 return undefined;5232 }5233 /**5234 * If the next token is a given keyword, advance the lexer.5235 * Otherwise, do not change the parser state and throw an error.5236 */5237 ;5238 _proto.expectKeyword = function expectKeyword(value) {5239 var token = this._lexer.token;5240 if (token.kind === TokenKind.NAME && token.value === value) {5241 this._lexer.advance();5242 } else {5243 throw syntaxError(this._lexer.source, token.start, "Expected \"".concat(value, "\", found ").concat(getTokenDesc(token), "."));5244 }5245 }5246 /**5247 * If the next token is a given keyword, return "true" after advancing the lexer.5248 * Otherwise, do not change the parser state and return "false".5249 */5250 ;5251 _proto.expectOptionalKeyword = function expectOptionalKeyword(value) {5252 var token = this._lexer.token;5253 if (token.kind === TokenKind.NAME && token.value === value) {5254 this._lexer.advance();5255 return true;5256 }5257 return false;5258 }5259 /**5260 * Helper function for creating an error when an unexpected lexed token is encountered.5261 */5262 ;5263 _proto.unexpected = function unexpected(atToken) {5264 var token = atToken !== null && atToken !== void 0 ? atToken : this._lexer.token;5265 return syntaxError(this._lexer.source, token.start, "Unexpected ".concat(getTokenDesc(token), "."));5266 }5267 /**5268 * Returns a possibly empty list of parse nodes, determined by the parseFn.5269 * This list begins with a lex token of openKind and ends with a lex token of closeKind.5270 * Advances the parser to the next lex token after the closing token.5271 */5272 ;5273 _proto.any = function any(openKind, parseFn, closeKind) {5274 this.expectToken(openKind);5275 var nodes = [];5276 while (!this.expectOptionalToken(closeKind)) {5277 nodes.push(parseFn.call(this));5278 }5279 return nodes;5280 }5281 /**5282 * Returns a list of parse nodes, determined by the parseFn.5283 * It can be empty only if open token is missing otherwise it will always return non-empty list5284 * that begins with a lex token of openKind and ends with a lex token of closeKind.5285 * Advances the parser to the next lex token after the closing token.5286 */5287 ;5288 _proto.optionalMany = function optionalMany(openKind, parseFn, closeKind) {5289 if (this.expectOptionalToken(openKind)) {5290 var nodes = [];5291 do {5292 nodes.push(parseFn.call(this));5293 } while (!this.expectOptionalToken(closeKind));5294 return nodes;5295 }5296 return [];5297 }5298 /**5299 * Returns a non-empty list of parse nodes, determined by the parseFn.5300 * This list begins with a lex token of openKind and ends with a lex token of closeKind.5301 * Advances the parser to the next lex token after the closing token.5302 */5303 ;5304 _proto.many = function many(openKind, parseFn, closeKind) {5305 this.expectToken(openKind);5306 var nodes = [];5307 do {5308 nodes.push(parseFn.call(this));5309 } while (!this.expectOptionalToken(closeKind));5310 return nodes;5311 }5312 /**5313 * Returns a non-empty list of parse nodes, determined by the parseFn.5314 * This list may begin with a lex token of delimiterKind followed by items separated by lex tokens of tokenKind.5315 * Advances the parser to the next lex token after last item in the list.5316 */5317 ;5318 _proto.delimitedMany = function delimitedMany(delimiterKind, parseFn) {5319 this.expectOptionalToken(delimiterKind);5320 var nodes = [];5321 do {5322 nodes.push(parseFn.call(this));5323 } while (this.expectOptionalToken(delimiterKind));5324 return nodes;5325 };5326 return Parser;5327 }();5328 /**5329 * A helper function to describe a token as a string for debugging.5330 */5331 function getTokenDesc(token) {5332 var value = token.value;5333 return getTokenKindDesc(token.kind) + (value != null ? " \"".concat(value, "\"") : '');5334 }5335 /**5336 * A helper function to describe a token kind as a string for debugging.5337 */5338 function getTokenKindDesc(kind) {5339 return isPunctuatorTokenKind(kind) ? "\"".concat(kind, "\"") : kind;5340 }5341 const graphqlContext = {5342 set,5343 status,5344 delay,5345 fetch,5346 data,5347 errors,5348 };5349 function parseQuery(query, definitionOperation = 'query') {5350 var _a;5351 const ast = parse$1(query);5352 const operationDef = ast.definitions.find((def) => {5353 return (def.kind === 'OperationDefinition' &&5354 (definitionOperation === 'all' || def.operation === definitionOperation));5355 });5356 return {5357 operationType: operationDef === null || operationDef === void 0 ? void 0 : operationDef.operation,5358 operationName: (_a = operationDef === null || operationDef === void 0 ? void 0 : operationDef.name) === null || _a === void 0 ? void 0 : _a.value,5359 };5360 }5361 function graphQLRequestHandler(expectedOperationType, expectedOperationName, mask, resolver) {5362 return {5363 resolver,5364 parse(req) {5365 var _a;5366 // According to the GraphQL specification, a GraphQL request can be issued5367 // using both "GET" and "POST" methods.5368 switch (req.method) {5369 case 'GET': {5370 const query = req.url.searchParams.get('query');5371 const variablesString = req.url.searchParams.get('variables') || '';5372 if (!query) {5373 return null;5374 }5375 const variables = variablesString5376 ? jsonParse(variablesString)5377 : {};5378 const { operationType, operationName } = parseQuery(query, expectedOperationType);5379 return {5380 operationType,5381 operationName,5382 variables,5383 };5384 }5385 case 'POST': {5386 if (!((_a = req.body) === null || _a === void 0 ? void 0 : _a.query)) {5387 return null;5388 }5389 const { query, variables } = req.body;5390 const { operationType, operationName } = parseQuery(query, expectedOperationType);5391 return {5392 operationType,5393 operationName,5394 variables,5395 };5396 }5397 default:5398 return null;5399 }5400 },5401 getPublicRequest(req, parsed) {5402 return Object.assign(Object.assign({}, req), { variables: parsed.variables || {} });5403 },5404 predicate(req, parsed) {5405 if (!parsed || !parsed.operationName) {5406 return false;5407 }5408 // Match the request URL against a given mask,5409 // in case of an endpoint-specific request handler.5410 const hasMatchingMask = matchRequestUrl(req.url, mask);5411 const isMatchingOperation = expectedOperationName instanceof RegExp5412 ? expectedOperationName.test(parsed.operationName)5413 : expectedOperationName === parsed.operationName;5414 return hasMatchingMask.matches && isMatchingOperation;5415 },5416 defineContext() {5417 return graphqlContext;5418 },5419 log(req, res, handler, parsed) {5420 const { operationType, operationName } = parsed;5421 const loggedRequest = prepareRequest(req);5422 const loggedResponse = prepareResponse(res);5423 console.groupCollapsed('[MSW] %s %s (%c%s%c)', getTimestamp(), operationName, `color:${getStatusCodeColor(res.status)}`, res.status, 'color:inherit');5424 console.log('Request:', loggedRequest);5425 console.log('Handler:', {5426 operationType,5427 operationName: expectedOperationName,5428 predicate: handler.predicate,5429 });5430 console.log('Response:', loggedResponse);5431 console.groupEnd();5432 },5433 };5434 }5435 const createGraphQLScopedHandler = (expectedOperationType, mask) => {5436 return (expectedOperationName, resolver) => {5437 return graphQLRequestHandler(expectedOperationType, expectedOperationName, mask, resolver);5438 };5439 };5440 const createGraphQLOperationHandler = (mask) => {5441 return (resolver) => {5442 return graphQLRequestHandler('all', new RegExp('.*'), mask, resolver);5443 };5444 };5445 const graphqlStandardHandlers = {5446 operation: createGraphQLOperationHandler('*'),5447 query: createGraphQLScopedHandler('query', '*'),5448 mutation: createGraphQLScopedHandler('mutation', '*'),5449 };5450 function createGraphQLLink(uri) {5451 return {5452 operation: createGraphQLOperationHandler(uri),5453 query: createGraphQLScopedHandler('query', uri),5454 mutation: createGraphQLScopedHandler('mutation', uri),5455 };5456 }5457 const graphql = Object.assign(Object.assign({}, graphqlStandardHandlers), { link: createGraphQLLink });5458 exports.context = index;5459 exports.createResponseComposition = createResponseComposition;5460 exports.defaultContext = defaultContext;5461 exports.defaultResponse = defaultResponse;5462 exports.graphql = graphql;5463 exports.graphqlContext = graphqlContext;5464 exports.matchRequestUrl = matchRequestUrl;5465 exports.response = response;5466 exports.rest = rest;5467 exports.restContext = restContext;5468 exports.setupWorker = setupWorker;5469})));5470}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})5471},{"_process":3,"node-fetch":2}],2:[function(require,module,exports){5472(function (global){(function (){5473"use strict";5474// ref: https://github.com/tc39/proposal-global5475var getGlobal = function () {5476 // the only reliable means to get the global object is5477 // `Function('return this')()`5478 // However, this causes CSP violations in Chrome apps.5479 if (typeof self !== 'undefined') { return self; }5480 if (typeof window !== 'undefined') { return window; }5481 if (typeof global !== 'undefined') { return global; }5482 throw new Error('unable to locate global object');5483}5484var global = getGlobal();5485module.exports = exports = global.fetch;5486// Needed for TypeScript and Webpack.5487if (global.fetch) {5488 exports.default = global.fetch.bind(global);5489}5490exports.Headers = global.Headers;5491exports.Request = global.Request;5492exports.Response = global.Response;5493}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})5494},{}],3:[function(require,module,exports){5495// shim for using process in browser5496var process = module.exports = {};5497// cached from whatever global is present so that test runners that stub it5498// don't break things. But we need to wrap it in a try catch in case it is5499// wrapped in strict mode code which doesn't define any globals. It's inside a5500// function because try/catches deoptimize in certain engines.5501var cachedSetTimeout;5502var cachedClearTimeout;5503function defaultSetTimout() {5504 throw new Error('setTimeout has not been defined');5505}5506function defaultClearTimeout () {5507 throw new Error('clearTimeout has not been defined');5508}5509(function () {5510 try {5511 if (typeof setTimeout === 'function') {5512 cachedSetTimeout = setTimeout;5513 } else {5514 cachedSetTimeout = defaultSetTimout;5515 }5516 } catch (e) {5517 cachedSetTimeout = defaultSetTimout;5518 }5519 try {5520 if (typeof clearTimeout === 'function') {5521 cachedClearTimeout = clearTimeout;5522 } else {5523 cachedClearTimeout = defaultClearTimeout;5524 }5525 } catch (e) {5526 cachedClearTimeout = defaultClearTimeout;5527 }5528} ())5529function runTimeout(fun) {5530 if (cachedSetTimeout === setTimeout) {5531 //normal enviroments in sane situations5532 return setTimeout(fun, 0);5533 }5534 // if setTimeout wasn't available but was latter defined5535 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {5536 cachedSetTimeout = setTimeout;5537 return setTimeout(fun, 0);5538 }5539 try {5540 // when when somebody has screwed with setTimeout but no I.E. maddness5541 return cachedSetTimeout(fun, 0);5542 } catch(e){5543 try {5544 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally5545 return cachedSetTimeout.call(null, fun, 0);5546 } catch(e){5547 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error5548 return cachedSetTimeout.call(this, fun, 0);5549 }5550 }5551}5552function runClearTimeout(marker) {5553 if (cachedClearTimeout === clearTimeout) {5554 //normal enviroments in sane situations5555 return clearTimeout(marker);5556 }5557 // if clearTimeout wasn't available but was latter defined5558 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {5559 cachedClearTimeout = clearTimeout;5560 return clearTimeout(marker);5561 }5562 try {5563 // when when somebody has screwed with setTimeout but no I.E. maddness5564 return cachedClearTimeout(marker);5565 } catch (e){5566 try {5567 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally5568 return cachedClearTimeout.call(null, marker);5569 } catch (e){5570 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.5571 // Some versions of I.E. have different rules for clearTimeout vs setTimeout5572 return cachedClearTimeout.call(this, marker);5573 }5574 }5575}5576var queue = [];5577var draining = false;5578var currentQueue;5579var queueIndex = -1;5580function cleanUpNextTick() {5581 if (!draining || !currentQueue) {5582 return;5583 }5584 draining = false;5585 if (currentQueue.length) {5586 queue = currentQueue.concat(queue);5587 } else {5588 queueIndex = -1;5589 }5590 if (queue.length) {5591 drainQueue();5592 }5593}5594function drainQueue() {5595 if (draining) {5596 return;5597 }5598 var timeout = runTimeout(cleanUpNextTick);5599 draining = true;5600 var len = queue.length;5601 while(len) {5602 currentQueue = queue;5603 queue = [];5604 while (++queueIndex < len) {5605 if (currentQueue) {5606 currentQueue[queueIndex].run();5607 }5608 }5609 queueIndex = -1;5610 len = queue.length;5611 }5612 currentQueue = null;5613 draining = false;5614 runClearTimeout(timeout);5615}5616process.nextTick = function (fun) {5617 var args = new Array(arguments.length - 1);5618 if (arguments.length > 1) {5619 for (var i = 1; i < arguments.length; i++) {5620 args[i - 1] = arguments[i];5621 }5622 }5623 queue.push(new Item(fun, args));5624 if (queue.length === 1 && !draining) {5625 runTimeout(drainQueue);5626 }5627};5628// v8 likes predictible objects5629function Item(fun, array) {5630 this.fun = fun;5631 this.array = array;5632}5633Item.prototype.run = function () {5634 this.fun.apply(null, this.array);5635};5636process.title = 'browser';5637process.browser = true;5638process.env = {};5639process.argv = [];5640process.version = ''; // empty string to avoid regexp issues5641process.versions = {};5642function noop() {}5643process.on = noop;5644process.addListener = noop;5645process.once = noop;5646process.off = noop;5647process.removeListener = noop;5648process.removeAllListeners = noop;5649process.emit = noop;5650process.prependListener = noop;5651process.prependOnceListener = noop;5652process.listeners = function (name) { return [] }5653process.binding = function (name) {5654 throw new Error('process.binding is not supported');5655};5656process.cwd = function () { return '/' };5657process.chdir = function (dir) {5658 throw new Error('process.chdir is not supported');5659};5660process.umask = function() { return 0; };5661},{}],4:[function(require,module,exports){5662"use strict";5663Object.defineProperty(exports, "__esModule", {5664 value: true5665});5666exports["default"] = void 0;5667var _react = _interopRequireDefault(require("react"));5668var _ArticlePreviews = _interopRequireDefault(require("../features/articlePreviews/ArticlePreviews"));5669var _CurrentArticle = _interopRequireDefault(require("../features/currentArticle/CurrentArticle"));5670var _Comments = _interopRequireDefault(require("../features/comments/Comments"));5671function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }5672// import './App.css';5673function App() {5674 return /*#__PURE__*/_react["default"].createElement("div", {5675 className: "App"5676 }, /*#__PURE__*/_react["default"].createElement("header", {5677 className: "App-header"5678 }), /*#__PURE__*/_react["default"].createElement("main", null, /*#__PURE__*/_react["default"].createElement("div", {5679 className: "current-article"5680 }, /*#__PURE__*/_react["default"].createElement(_CurrentArticle["default"], null), /*#__PURE__*/_react["default"].createElement(_Comments["default"], null)), /*#__PURE__*/_react["default"].createElement(_ArticlePreviews["default"], null)));5681}5682var _default = App;5683exports["default"] = _default;5684},{"../features/articlePreviews/ArticlePreviews":11,"../features/comments/Comments":13,"../features/currentArticle/CurrentArticle":15,"react":undefined}],5:[function(require,module,exports){5685"use strict";5686Object.defineProperty(exports, "__esModule", {5687 value: true5688});5689exports["default"] = void 0;5690var _toolkit = require("@reduxjs/toolkit");5691var _articlePreviewsSlice = _interopRequireDefault(require("../features/articlePreviews/articlePreviewsSlice"));5692var _currentArticleSlice = _interopRequireDefault(require("../features/currentArticle/currentArticleSlice"));5693var _commentsSlice = _interopRequireDefault(require("../features/comments/commentsSlice"));5694function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }5695var _default = (0, _toolkit.configureStore)({5696 reducer: {5697 articlePreviews: _articlePreviewsSlice["default"],5698 currentArticle: _currentArticleSlice["default"],5699 comments: _commentsSlice["default"]5700 }5701});5702exports["default"] = _default;5703},{"../features/articlePreviews/articlePreviewsSlice":12,"../features/comments/commentsSlice":14,"../features/currentArticle/currentArticleSlice":16,"@reduxjs/toolkit":undefined}],6:[function(require,module,exports){5704"use strict";5705Object.defineProperty(exports, "__esModule", {5706 value: true5707});5708exports["default"] = ArticleListItem;5709var _react = _interopRequireDefault(require("react"));5710function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }5711function ArticleListItem(_ref) {5712 var article = _ref.article;5713 return /*#__PURE__*/_react["default"].createElement("button", {5714 key: article.id,5715 className: "article-container"5716 }, /*#__PURE__*/_react["default"].createElement("img", {5717 src: article.image,5718 alt: "",5719 className: "article-image"5720 }), /*#__PURE__*/_react["default"].createElement("div", {5721 className: "article-content-container"5722 }, /*#__PURE__*/_react["default"].createElement("h3", {5723 className: "article-title"5724 }, article.title), /*#__PURE__*/_react["default"].createElement("p", {5725 className: "article-preview"5726 }, article.preview)));5727}5728},{"react":undefined}],7:[function(require,module,exports){5729"use strict";5730Object.defineProperty(exports, "__esModule", {5731 value: true5732});5733exports["default"] = Comment;5734var _react = _interopRequireDefault(require("react"));5735function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }5736function Comment(_ref) {5737 var comment = _ref.comment;5738 var id = comment.id,5739 text = comment.text;5740 return /*#__PURE__*/_react["default"].createElement("li", {5741 key: id,5742 className: "comment-container"5743 }, /*#__PURE__*/_react["default"].createElement("span", null, text));5744}5745},{"react":undefined}],8:[function(require,module,exports){5746"use strict";5747function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }5748Object.defineProperty(exports, "__esModule", {5749 value: true5750});5751exports["default"] = CommentForm;5752var _react = _interopRequireWildcard(require("react"));5753var _reactRedux = require("react-redux");5754var _commentsSlice = require("../features/comments/commentsSlice");5755function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }5756function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }5757function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }5758function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }5759function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }5760function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }5761function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }5762function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }5763function CommentForm(_ref) {5764 var articleId = _ref.articleId;5765 var dispatch = (0, _reactRedux.useDispatch)();5766 var _useState = (0, _react.useState)(''),5767 _useState2 = _slicedToArray(_useState, 2),5768 comment = _useState2[0],5769 setComment = _useState2[1]; // Declare isCreatePending here.5770 var isCreatePending = (0, _reactRedux.useSelector)(_commentsSlice.createCommentIsPending);5771 var handleSubmit = function handleSubmit(e) {5772 e.preventDefault(); // dispatch your asynchronous action here!5773 dispatch((0, _commentsSlice.postCommentForArticleId)({5774 articleId: articleId,5775 comment: comment5776 }));5777 setComment('');5778 };5779 return /*#__PURE__*/_react["default"].createElement("form", {5780 onSubmit: handleSubmit5781 }, /*#__PURE__*/_react["default"].createElement("label", {5782 "for": "comment",5783 className: "label"5784 }, "Add Comment:"), /*#__PURE__*/_react["default"].createElement("div", {5785 id: "input-container"5786 }, /*#__PURE__*/_react["default"].createElement("input", {5787 id: "comment",5788 value: comment,5789 onChange: function onChange(e) {5790 return setComment(e.currentTarget.value);5791 },5792 type: "text"5793 }), /*#__PURE__*/_react["default"].createElement("button", {5794 disabled: isCreatePending,5795 className: "comment-button"5796 }, "Submit")));5797}5798},{"../features/comments/commentsSlice":14,"react":undefined,"react-redux":undefined}],9:[function(require,module,exports){5799"use strict";5800Object.defineProperty(exports, "__esModule", {5801 value: true5802});5803exports["default"] = CommentList;5804var _react = _interopRequireDefault(require("react"));5805var _Comment = _interopRequireDefault(require("./Comment"));5806function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }5807function CommentList(_ref) {5808 var comments = _ref.comments;5809 if (!comments) {5810 return null;5811 }5812 return /*#__PURE__*/_react["default"].createElement("ul", {5813 className: "comments-list"5814 }, comments.map(function (comment) {5815 return /*#__PURE__*/_react["default"].createElement(_Comment["default"], {5816 comment: comment5817 });5818 }));5819}5820},{"./Comment":7,"react":undefined}],10:[function(require,module,exports){5821"use strict";5822Object.defineProperty(exports, "__esModule", {5823 value: true5824});5825exports["default"] = FullArticle;5826var _react = _interopRequireDefault(require("react"));5827function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }5828function FullArticle(_ref) {5829 var article = _ref.article;5830 return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement("div", {5831 className: "article-full-image-container"5832 }, /*#__PURE__*/_react["default"].createElement("img", {5833 src: article.image,5834 alt: ""5835 })), /*#__PURE__*/_react["default"].createElement("div", {5836 key: article.id,5837 className: "current-article-container"5838 }, /*#__PURE__*/_react["default"].createElement("h1", {5839 className: "current-article-title"5840 }, article.title), /*#__PURE__*/_react["default"].createElement("div", {5841 className: "article-full-text"5842 }, article.fullText)));5843}5844},{"react":undefined}],11:[function(require,module,exports){5845"use strict";5846function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }5847Object.defineProperty(exports, "__esModule", {5848 value: true5849});5850exports["default"] = void 0;5851var _react = _interopRequireWildcard(require("react"));5852var _reactRedux = require("react-redux");5853var _articlePreviewsSlice = require("./articlePreviewsSlice");5854var _currentArticleSlice = require("../currentArticle/currentArticleSlice");5855var _ArticleListItem = _interopRequireDefault(require("../../components/ArticleListItem"));5856function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }5857function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }5858function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }5859var ArticlePreviews = function ArticlePreviews() {5860 var dispatch = (0, _reactRedux.useDispatch)();5861 var articlePreviews = (0, _reactRedux.useSelector)(_articlePreviewsSlice.selectAllPreviews);5862 var isLoadingPreviews = (0, _reactRedux.useSelector)(_articlePreviewsSlice.isLoading);5863 (0, _react.useEffect)(function () {5864 dispatch((0, _articlePreviewsSlice.loadAllPreviews)());5865 }, [dispatch]);5866 if (isLoadingPreviews) {5867 return /*#__PURE__*/_react["default"].createElement("div", null, "loading state");5868 }5869 return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement("section", {5870 className: "articles-container"5871 }, /*#__PURE__*/_react["default"].createElement("h2", {5872 className: "section-title"5873 }, "All Articles"), articlePreviews.map(function (article) {5874 return /*#__PURE__*/_react["default"].createElement("div", {5875 key: article.id,5876 onClick: function onClick(e) {5877 return dispatch((0, _currentArticleSlice.loadCurrentArticle)(article.id));5878 }5879 }, /*#__PURE__*/_react["default"].createElement(_ArticleListItem["default"], {5880 article: article5881 }));5882 })));5883};5884var _default = ArticlePreviews;5885exports["default"] = _default;5886},{"../../components/ArticleListItem":6,"../currentArticle/currentArticleSlice":16,"./articlePreviewsSlice":12,"react":undefined,"react-redux":undefined}],12:[function(require,module,exports){5887"use strict";5888Object.defineProperty(exports, "__esModule", {5889 value: true5890});5891exports["default"] = exports.isLoading = exports.selectAllPreviews = exports.articlePreviewsSlice = exports.loadAllPreviews = void 0;5892var _toolkit = require("@reduxjs/toolkit");5893function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }5894function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }5895var loadAllPreviews = (0, _toolkit.createAsyncThunk)('articlePreviews/loadAllPreviews', /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {5896 var data, json;5897 return regeneratorRuntime.wrap(function _callee$(_context) {5898 while (1) {5899 switch (_context.prev = _context.next) {5900 case 0:5901 _context.next = 2;5902 return fetch('api/articles');5903 case 2:5904 data = _context.sent;5905 _context.next = 5;5906 return data.json();5907 case 5:5908 json = _context.sent;5909 return _context.abrupt("return", json);5910 case 7:5911 case "end":5912 return _context.stop();5913 }5914 }5915 }, _callee);5916})));5917exports.loadAllPreviews = loadAllPreviews;5918var articlePreviewsSlice = (0, _toolkit.createSlice)({5919 name: 'articlePreviews',5920 initialState: {5921 articles: [],5922 isLoadingArticlePreviews: false,5923 hasError: false5924 },5925 extraReducers: function extraReducers(builder) {5926 builder.addCase(loadAllPreviews.pending, function (state) {5927 state.isLoadingArticlePreviews = true;5928 state.hasError = false;5929 }).addCase(loadAllPreviews.fulfilled, function (state, action) {5930 state.isLoadingArticlePreviews = false;5931 state.articles = action.payload;5932 }).addCase(loadAllPreviews.rejected, function (state, action) {5933 state.isLoadingArticlePreviews = false;5934 state.hasError = true;5935 state.articles = [];5936 });5937 }5938});5939exports.articlePreviewsSlice = articlePreviewsSlice;5940var selectAllPreviews = function selectAllPreviews(state) {5941 return state.articlePreviews.articles;5942};5943exports.selectAllPreviews = selectAllPreviews;5944var isLoading = function isLoading(state) {5945 return state.articlePreviews.isLoading;5946};5947exports.isLoading = isLoading;5948var _default = articlePreviewsSlice.reducer;5949exports["default"] = _default;5950},{"@reduxjs/toolkit":undefined}],13:[function(require,module,exports){5951"use strict";5952function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }5953Object.defineProperty(exports, "__esModule", {5954 value: true5955});5956exports["default"] = void 0;5957var _react = _interopRequireWildcard(require("react"));5958var _reactRedux = require("react-redux");5959var _commentsSlice = require("../comments/commentsSlice");5960var _currentArticleSlice = require("../currentArticle/currentArticleSlice");5961var _CommentList = _interopRequireDefault(require("../../components/CommentList"));5962var _CommentForm = _interopRequireDefault(require("../../components/CommentForm"));5963function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }5964function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }5965function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }5966var Comments = function Comments() {5967 var dispatch = (0, _reactRedux.useDispatch)();5968 var article = (0, _reactRedux.useSelector)(_currentArticleSlice.selectCurrentArticle); // Declare additional selected data here.5969 var comments = (0, _reactRedux.useSelector)(_commentsSlice.selectComments);5970 var commentsAreLoading = (0, _reactRedux.useSelector)(_commentsSlice.isLoadingComments);5971 var commentsForArticleId = article === undefined ? [] : comments[article.id]; // Dispatch loadCommentsForArticleId with useEffect here.5972 (0, _react.useEffect)(function () {5973 if (article !== undefined) {5974 dispatch((0, _commentsSlice.loadCommentsForArticleId)(article.id));5975 }5976 ;5977 }, [dispatch, article]);5978 if (commentsAreLoading) return /*#__PURE__*/_react["default"].createElement("div", null, "Loading Comments");5979 if (!article) return null;5980 return /*#__PURE__*/_react["default"].createElement("div", {5981 className: "comments-container"5982 }, /*#__PURE__*/_react["default"].createElement("h3", {5983 className: "comments-title"5984 }, "Comments"), /*#__PURE__*/_react["default"].createElement(_CommentList["default"], {5985 comments: commentsForArticleId5986 }), /*#__PURE__*/_react["default"].createElement(_CommentForm["default"], {5987 articleId: article.id5988 }));5989};5990var _default = Comments;5991exports["default"] = _default;5992},{"../../components/CommentForm":8,"../../components/CommentList":9,"../comments/commentsSlice":14,"../currentArticle/currentArticleSlice":16,"react":undefined,"react-redux":undefined}],14:[function(require,module,exports){5993"use strict";5994Object.defineProperty(exports, "__esModule", {5995 value: true5996});5997exports["default"] = exports.createCommentIsPending = exports.isLoadingComments = exports.selectComments = exports.commentsSlice = exports.postCommentForArticleId = exports.loadCommentsForArticleId = void 0;5998var _toolkit = require("@reduxjs/toolkit");5999var _extraReducers;6000function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }6001function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }6002function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }6003// Create loadCommentsForArticleId here.6004var loadCommentsForArticleId = (0, _toolkit.createAsyncThunk)('comments/loadCommentsForArticleId', /*#__PURE__*/function () {6005 var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(id) {6006 var response, json;6007 return regeneratorRuntime.wrap(function _callee$(_context) {6008 while (1) {6009 switch (_context.prev = _context.next) {6010 case 0:6011 _context.next = 2;6012 return fetch("api/articles/".concat(id, "/comments"));6013 case 2:6014 response = _context.sent;6015 _context.next = 5;6016 return response.json();6017 case 5:6018 json = _context.sent;6019 return _context.abrupt("return", json);6020 case 7:6021 case "end":6022 return _context.stop();6023 }6024 }6025 }, _callee);6026 }));6027 return function (_x) {6028 return _ref.apply(this, arguments);6029 };6030}()); // Create postCommentForArticleId here.6031exports.loadCommentsForArticleId = loadCommentsForArticleId;6032var postCommentForArticleId = (0, _toolkit.createAsyncThunk)('comments/postCommentForArticleId', /*#__PURE__*/function () {6033 var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(_ref2) {6034 var articleId, comment, requestBody, response, json;6035 return regeneratorRuntime.wrap(function _callee2$(_context2) {6036 while (1) {6037 switch (_context2.prev = _context2.next) {6038 case 0:6039 articleId = _ref2.articleId, comment = _ref2.comment;6040 requestBody = JSON.stringify({6041 comment: comment6042 });6043 _context2.next = 4;6044 return fetch("api/articles/".concat(articleId, "/comments"), {6045 method: 'POST',6046 body: requestBody6047 });6048 case 4:6049 response = _context2.sent;6050 _context2.next = 7;6051 return response.json();6052 case 7:6053 json = _context2.sent;6054 return _context2.abrupt("return", json);6055 case 9:6056 case "end":6057 return _context2.stop();6058 }6059 }6060 }, _callee2);6061 }));6062 return function (_x2) {6063 return _ref3.apply(this, arguments);6064 };6065}());6066exports.postCommentForArticleId = postCommentForArticleId;6067var commentsSlice = (0, _toolkit.createSlice)({6068 name: 'comments',6069 initialState: {6070 // Add initial state properties here.6071 byArticleId: {},6072 isLoadingComments: false,6073 failedToLoadComments: false,6074 createCommentIsPending: false,6075 failedToCreateComment: false6076 },6077 // Add extraReducers here.6078 extraReducers: (_extraReducers = {}, _defineProperty(_extraReducers, loadCommentsForArticleId.pending, function (state, action) {6079 state.isLoadingComments = true;6080 state.failedToLoadComments = false;6081 }), _defineProperty(_extraReducers, loadCommentsForArticleId.fulfilled, function (state, action) {6082 state.isLoadingComments = false;6083 state.failedToLoadComments = false;6084 state.byArticleId[action.payload.articleId] = action.payload.comments;6085 }), _defineProperty(_extraReducers, loadCommentsForArticleId.rejected, function (state, action) {6086 state.isLoadingComments = false;6087 state.failedToLoadComments = true;6088 }), _defineProperty(_extraReducers, postCommentForArticleId.pending, function (state, action) {6089 state.createCommentIsPending = true;6090 state.failedToCreateComment = false;6091 }), _defineProperty(_extraReducers, postCommentForArticleId.fulfilled, function (state, action) {6092 state.createCommentIsPending = false;6093 state.failedToCreateComment = false;6094 state.byArticleId[action.payload.articleId].push(action.payload);6095 }), _defineProperty(_extraReducers, postCommentForArticleId.rejected, function (state, action) {6096 state.createCommentIsPending = false;6097 state.failedToCreateComment = true;6098 }), _extraReducers)6099});6100exports.commentsSlice = commentsSlice;6101var selectComments = function selectComments(state) {6102 return state.comments.byArticleId;6103};6104exports.selectComments = selectComments;6105var isLoadingComments = function isLoadingComments(state) {6106 return state.comments.isLoadingComments;6107};6108exports.isLoadingComments = isLoadingComments;6109var createCommentIsPending = function createCommentIsPending(state) {6110 return state.comments.createCommentIsPending;6111};6112exports.createCommentIsPending = createCommentIsPending;6113var _default = commentsSlice.reducer;6114exports["default"] = _default;6115},{"@reduxjs/toolkit":undefined}],15:[function(require,module,exports){6116"use strict";6117function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }6118Object.defineProperty(exports, "__esModule", {6119 value: true6120});6121exports["default"] = void 0;6122var _react = _interopRequireWildcard(require("react"));6123var _reactRedux = require("react-redux");6124var _currentArticleSlice = require("../currentArticle/currentArticleSlice");6125var _FullArticle = _interopRequireDefault(require("../../components/FullArticle"));6126function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }6127function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }6128function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }6129var CurrentArticle = function CurrentArticle() {6130 var dispatch = (0, _reactRedux.useDispatch)();6131 var article = (0, _reactRedux.useSelector)(_currentArticleSlice.selectCurrentArticle);6132 var currentArticleIsLoading = (0, _reactRedux.useSelector)(_currentArticleSlice.isLoadingCurrentArticle);6133 if (currentArticleIsLoading) {6134 return /*#__PURE__*/_react["default"].createElement("div", null, "Loading");6135 } else if (!article) {6136 return null;6137 }6138 return /*#__PURE__*/_react["default"].createElement(_FullArticle["default"], {6139 article: article6140 });6141};6142var _default = CurrentArticle;6143exports["default"] = _default;6144},{"../../components/FullArticle":10,"../currentArticle/currentArticleSlice":16,"react":undefined,"react-redux":undefined}],16:[function(require,module,exports){6145"use strict";6146Object.defineProperty(exports, "__esModule", {6147 value: true6148});6149exports["default"] = exports.isLoadingCurrentArticle = exports.selectCurrentArticle = exports.currentArticleSlice = exports.loadCurrentArticle = void 0;6150var _toolkit = require("@reduxjs/toolkit");6151function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }6152function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }6153var loadCurrentArticle = (0, _toolkit.createAsyncThunk)('currentArticle/loadCurrentArticle', /*#__PURE__*/function () {6154 var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(articleId) {6155 var data, json;6156 return regeneratorRuntime.wrap(function _callee$(_context) {6157 while (1) {6158 switch (_context.prev = _context.next) {6159 case 0:6160 _context.next = 2;6161 return fetch("api/articles/".concat(articleId));6162 case 2:6163 data = _context.sent;6164 _context.next = 5;6165 return data.json();6166 case 5:6167 json = _context.sent;6168 return _context.abrupt("return", json);6169 case 7:6170 case "end":6171 return _context.stop();6172 }6173 }6174 }, _callee);6175 }));6176 return function (_x) {6177 return _ref.apply(this, arguments);6178 };6179}());6180exports.loadCurrentArticle = loadCurrentArticle;6181var currentArticleSlice = (0, _toolkit.createSlice)({6182 name: 'currentArticle',6183 initialState: {6184 article: undefined,6185 isLoadingCurrentArticle: false,6186 hasError: false6187 },6188 extraReducers: function extraReducers(builder) {6189 builder.addCase(loadCurrentArticle.pending, function (state) {6190 state.isLoadingCurrentArticle = true;6191 state.hasError = false;6192 }).addCase(loadCurrentArticle.fulfilled, function (state, action) {6193 state.isLoadingCurrentArticle = false;6194 state.hasError = false;6195 state.article = action.payload;6196 }).addCase(loadCurrentArticle.rejected, function (state) {6197 state.isLoadingCurrentArticle = false;6198 state.hasError = true;6199 state.article = {};6200 });6201 }6202});6203exports.currentArticleSlice = currentArticleSlice;6204var selectCurrentArticle = function selectCurrentArticle(state) {6205 return state.currentArticle.article;6206};6207exports.selectCurrentArticle = selectCurrentArticle;6208var isLoadingCurrentArticle = function isLoadingCurrentArticle(state) {6209 return state.currentArticle.isLoadingCurrentArticle;6210};6211exports.isLoadingCurrentArticle = isLoadingCurrentArticle;6212var _default = currentArticleSlice.reducer;6213exports["default"] = _default;6214},{"@reduxjs/toolkit":undefined}],17:[function(require,module,exports){6215"use strict";6216var _react = _interopRequireDefault(require("react"));6217var _reactDom = _interopRequireDefault(require("react-dom"));6218var _App = _interopRequireDefault(require("./app/App"));6219var _store = _interopRequireDefault(require("./app/store"));6220var _reactRedux = require("react-redux");6221function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }6222var _require = require('./mocks/browser'),6223 worker = _require.worker;6224worker.start();6225_reactDom["default"].render( /*#__PURE__*/_react["default"].createElement(_react["default"].StrictMode, null, /*#__PURE__*/_react["default"].createElement(_reactRedux.Provider, {6226 store: _store["default"]6227}, /*#__PURE__*/_react["default"].createElement(_App["default"], null))), document.getElementById('root'));6228},{"./app/App":4,"./app/store":5,"./mocks/browser":19,"react":undefined,"react-dom":undefined,"react-redux":undefined}],18:[function(require,module,exports){6229module.exports=[6230 {6231 "id": 1,6232 "title": "Biden Inaugurated as 46th President - The New York Times",6233 "preview": "Joseph Robinette Biden Jr. and Kamala Devi Harris took the oath of office at a Capitol still reeling from the attack of a violent mob at a time when a deadly pandemic is still ravaging the country.",6234 "fullText": "Joseph Robinette Biden Jr. and Kamala Devi Harris took the oath of office at a Capitol still reeling from the attack of a violent mob at a time when a deadly pandemic is still ravaging the country.",6235 "image": "https://static01.nyt.com/images/2021/01/20/us/politics/20dc-biden1-sub3/20dc-biden1-sub3-facebookJumbo.jpg"6236 },6237 {6238 "id": 2,6239 "title": "LG says it might quit the smartphone market",6240 "preview": "LG says it needs to make \"a cold judgment\" about its only money-losing division.",6241 "fullText": "LG says it needs to make \"a cold judgment\" about its only money-losing division.",6242 "image": "https://cdn.arstechnica.net/wp-content/uploads/2021/01/37-760x380.jpg"6243 },6244 {6245 "id": 3,6246 "title": "VW CEO teases Tesla’s Elon Musk in Twitter debut",6247 "preview": "VW CEO Herbert Diess is poking fun at his friendly rivalry with Tesla CEO Elon Musk in his Twitter debut as he tries to position Volkswagen as a leader in electrification.",6248 "fullText": "TVW CEO Herbert Diess is poking fun at his friendly rivalry with Tesla CEO Elon Musk in his Twitter debut as he tries to position Volkswagen as a leader in electrification.",6249 "image": "https://i1.wp.com/electrek.co/wp-content/uploads/sites/3/2020/09/VW-CEO-Hebert-Diess-Tesla-CEO-Elon-Musk-selfie-hero.jpg?resize=1200%2C628&quality=82&strip=all&ssl=1"6250 },6251 {6252 "id": 4,6253 "title": "QAnon believers struggle with inauguration.",6254 "preview": "As President Biden took office, some QAnon believers tried to rejigger their theories to accommodate a transfer of power.",6255 "fullText": "As President Biden took office, some QAnon believers tried to rejigger their theories to accommodate a transfer of power.",6256 "image": "https://static01.nyt.com/images/2021/01/20/business/20distortions-qanon/20distortions-qanon-facebookJumbo.jpg"6257 },6258 {6259 "id": 5,6260 "title": "Kamala Harris sworn into history",6261 "preview": "Harris becomes the first woman, Black woman and Asian American to serve as vice president.",6262 "fullText": "Harris becomes the first woman, Black woman and Asian American to serve as vice president.",6263 "image": "https://www.washingtonpost.com/wp-apps/imrs.php?src=https://arc-anglerfish-washpost-prod-washpost.s3.amazonaws.com/public/H4TGAGS3IEI6XKCJN6KCHJ277U.jpg&w=1440"6264 },6265 {6266 "id": 6,6267 "title": "SpaceX expands public beta test of Starlink satellite internet to Canada and the UK",6268 "preview": "Elon Musk's company is now offering early public access to its Starlink satellite internet service in Canada and the U.K.",6269 "fullText": "Elon Musk's company is now offering early public access to its Starlink satellite internet service in Canada and the U.K.",6270 "image": "https://image.cnbcfm.com/api/v1/image/106758975-1603465968180-EkzQ0UbXgAAGYVe-orig.jpg?v=1603466027"6271 },6272 {6273 "id": 7,6274 "title": "Scientists have finally worked out how butterflies fly",6275 "preview": "Experts, long puzzled by how butterflies fly, have found that the insects \"clap\" their wings together -- and their wings are perfectly evolved for better propulsion.",6276 "fullText": "Experts, long puzzled by how butterflies fly, have found that the insects \"clap\" their wings together -- and their wings are perfectly evolved for better propulsion.",6277 "image": "https://cdn.cnn.com/cnnnext/dam/assets/210120064324-restricted-butterflies-clap-intl-scli-super-tease.jpg"6278 },6279 {6280 "id": 8,6281 "title": "Navalny releases investigation into decadent billion-dollar 'Putin palace'",6282 "preview": "Even locked up in a detention center on the outskirts of Moscow, Kremlin critic Alexey Navalny continues to be a thorn in Russian President Vladimir Putin's side.",6283 "fullText": "Even locked up in a detention center on the outskirts of Moscow, Kremlin critic Alexey Navalny continues to be a thorn in Russian President Vladimir Putin's side.",6284 "image": "https://cdn.cnn.com/cnnnext/dam/assets/210120111237-restricted-05-putin-palace-navalny-russia-intl-super-tease.jpeg"6285 }6286]6287},{}],19:[function(require,module,exports){6288"use strict";6289Object.defineProperty(exports, "__esModule", {6290 value: true6291});6292exports.worker = void 0;6293var _msw = require("msw");6294var _handlers = require("./handlers");6295function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }6296function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }6297function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }6298function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); }6299function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }6300function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }6301var worker = _msw.setupWorker.apply(void 0, _toConsumableArray(_handlers.handlers));6302exports.worker = worker;6303},{"./handlers":21,"msw":1}],20:[function(require,module,exports){6304module.exports=[6305 {6306 "id": 1,6307 "articleId": 5,6308 "text": "Congratulations Kamala."6309 },6310 {6311 "id": 2,6312 "articleId": 5,6313 "text": "Wow, very cool."6314 },6315 {6316 "id": 2,6317 "articleId": 7,6318 "text": "Butterflies are so awesome!!!"6319 },6320 {6321 "id": 2,6322 "articleId": 2,6323 "text": "Sad, I love my LG phone :("6324 }6325]6326},{}],21:[function(require,module,exports){6327"use strict";6328Object.defineProperty(exports, "__esModule", {6329 value: true6330});6331exports.handlers = void 0;6332var _msw = require("msw");6333var _articles = _interopRequireDefault(require("./articles.json"));6334var _comments = _interopRequireDefault(require("./comments.json"));6335function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }6336var userComments = {};6337function mockDelay(milliseconds) {6338 var date = Date.now();6339 var currentDate = null;6340 do {6341 currentDate = Date.now();6342 } while (currentDate - date < milliseconds);6343}6344var handlers = [_msw.rest.get('/api/articles', function (req, res, ctx) {6345 mockDelay(500);6346 return res(ctx.status(200), ctx.json(_articles["default"].map(function (article) {6347 return {6348 id: article.id,6349 title: article.title,6350 preview: article.preview,6351 image: article.image6352 };6353 })));6354}), _msw.rest.get('/api/articles/:articleId', function (req, res, ctx) {6355 mockDelay(500);6356 var articleId = req.params.articleId;6357 return res(ctx.status(200), ctx.json(_articles["default"].find(function (article) {6358 return article.id === parseInt(articleId);6359 })));6360}), _msw.rest.get('/api/articles/:articleId/comments', function (req, res, ctx) {6361 mockDelay(500);6362 var articleId = req.params.articleId;6363 var userCommentsForArticle = userComments[articleId] || [];6364 return res(ctx.status(200), ctx.json({6365 articleId: parseInt(articleId),6366 comments: _comments["default"].filter(function (comment) {6367 return comment.articleId === parseInt(articleId);6368 }).concat(userCommentsForArticle)6369 }));6370}), _msw.rest.post('/api/articles/:articleId/comments', function (req, res, ctx) {6371 mockDelay(500);6372 var articleId = req.params.articleId;6373 var commentResponse = {6374 id: _comments["default"].length,6375 articleId: parseInt(articleId),6376 text: JSON.parse(req.body).comment6377 };6378 if (userComments[articleId]) {6379 userComments[articleId].push(commentResponse);6380 } else {6381 userComments[articleId] = [commentResponse];6382 }6383 return res(ctx.status(200), ctx.json(commentResponse));6384})];6385exports.handlers = handlers;...

Full Screen

Full Screen

apiMiddlewareHook.js

Source:apiMiddlewareHook.js Github

copy

Full Screen

1import { compose } from 'redux';2import { CALL_API, isValidRSAA } from 'redux-api-middleware';3import { decamelizeKeys } from 'humps';4import _ from 'ramda';5import {6 FETCH_REQUEST as CHANNEL_FETCH_REQUEST,7 BAN_REQUEST as CHANNEL_BAN_REQUEST,8 REFUSE as CHANNEL_REFUSE,9} from '../actionTypes/channel';10import {11 BAN_REQUEST as FAVORITE_BAN_REQUEST,12 REFUSE as FAVORITE_REFUSE,13} from '../actionTypes/favorite';14import {15 BAN_REQUEST as DAILY_BAN_REQUEST,16 REFUSE as DAILY_REFUSE,17} from '../actionTypes/daily';18const decamelizeBody = (action) => {19 const callAPI = action[CALL_API];20 const { body } = callAPI;21 if (!body) return action;22 return {23 ...action,24 [CALL_API]: {25 ...callAPI,26 body: decamelizeKeys(body)27 }28 };29};30const serializeFormBody = (action) => {31 const callAPI = action[CALL_API];32 const { body, headers } = callAPI;33 if (!body || headers['Content-Type'] !== 'application/x-www-form-urlencoded') return action;34 const parsedBody = _.compose(35 _.join('&'), _.map(_.join('=')), _.toPairs,36 _.mapObjIndexed((value) => encodeURIComponent(value))37 )(body);38 return {39 ...action,40 [CALL_API]: {41 ...callAPI,42 body: parsedBody,43 }44 };45};46const stringifyJsonBody = (action) => {47 const callAPI = action[CALL_API];48 const { body } = callAPI;49 if (!body || !_.is(Object, body)) return action;50 return {51 ...action,52 [CALL_API]: {53 ...callAPI,54 body: JSON.stringify(body),55 }56 };57};58const pendingRefuse = (action, store) => {59 if (!store) return action;60 const callAPI = action[CALL_API];61 if (_.contains(callAPI.types[0], [CHANNEL_FETCH_REQUEST, CHANNEL_BAN_REQUEST])) {62 if (store.getState().channel.loading) return { type: CHANNEL_REFUSE };63 }64 if (FAVORITE_BAN_REQUEST === callAPI.types[0]) {65 if (store.getState().favorite.loading) return { type: FAVORITE_REFUSE };66 }67 if (DAILY_BAN_REQUEST === callAPI.types[0]) {68 if (store.getState().favorite.loading) return { type: DAILY_REFUSE };69 }70 return action;71};72export default store => next => action => {73 let newAction = action;74 if (isValidRSAA(action)) {75 newAction = pendingRefuse(action, store);76 if (!isValidRSAA(newAction)) return next(newAction);77 newAction = compose(78 pendingRefuse, stringifyJsonBody, serializeFormBody, decamelizeBody79 )(newAction);80 }81 return next(newAction);...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.contains('type').click()4 cy.url().should('include', '/commands/actions')5 cy.get('.action-email')6 .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.request({2 body: {3 },4}).then((response) => {5 expect(response.body).to.have.property('title', 'foo');6 expect(response.body).to.have.property('body', 'bar');7 expect(response.body).to.have.property('userId', 1);8});

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.request({2 body: {3 },4}).then((response) => {5 expect(response.status).to.eq(201);6 expect(response.body).to.have.property('id', 101);7});8cy.request({9 body: {10 },11 headers: {12 'content-type': 'application/json; charset=UTF-8',13 },14}).then((response) => {15 expect(response.status).to.eq(201);16 expect(response.body).to.have.property('id', 101);17});18cy.request({19 body: {20 },21}).then((response) => {22 expect(response.status).to.eq(201);23 expect(response.body).to.have.property('id', 101);24});25cy.request({26 body: {27 },28 headers: {29 'content-type': 'application/json; charset=UTF-8',30 },31}).then((response) => {32 expect(response.status).to.eq(201);33 expect(response.body).to.have.property('id', 101);34});35cy.request({36 body: {37 },38}).then((response) => {39 expect(response.status).to.eq(201);40 expect(response.body).to.have.property('id', 101);41});

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.request({2 body: {3 }4}).then((response) => {5 cy.log(stringifyJsonBody(response.body))6})7{8}9Cypress.Commands.add('stringifyJsonBody', (body) => {10 return JSON.stringify(body, null, 4)11})12import './commands'

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.request({2 body: {3 },4}).then((response) => {5 expect(response.body).to.have.property('headers')6 expect(response.body).to.have.property('args')7 expect(response.body).to.have.property('data')8 expect(response.body).to.have.property('files')9 expect(response.body).to.have.property('form')10 expect(response.body).to.have.property('json')11 expect(response.body).to.have.property('url')12})13cy.request({14 body: {15 },16}).then((response) => {17 expect(response.body).to.have.property('headers')18 expect(response.body).to.have.property('args')19 expect(response.body).to.have.property('data')20 expect(response.body).to.have.property('files')21 expect(response.body).to.have.property('form')22 expect(response.body).to.have.property('json')23 expect(response.body).to.have.property('url')24})25cy.request({26 body: {27 },28}).then((response) => {29 expect(response.body).to.have.property('headers')30 expect(response.body).to.have.property('args')31 expect(response.body).to.have.property('data')32 expect(response.body).to.have.property('files')33 expect(response.body).to.have.property('form')34 expect(response.body).to.have.property('json')35 expect(response.body).to.have.property('url')36})37cy.request({38 body: {39 },40}).then((response) => {41 expect(response.body).to.have.property('headers')42 expect(response.body).to.have.property('args')

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test', () => {2 it('should stringify body', () => {3 cy.request({4 body: {5 },6 }).then((response) => {7 cy.log(JSON.stringify(response.body));8 });9 });10});11Cypress.Commands.add('stringifyJsonBody', (options) => {12 return cy.request(options).then((response) => {13 return JSON.stringify(response.body);14 });15});16describe('Test', () => {17 it('should stringify body', () => {18 cy.stringifyJsonBody({19 body: {20 },21 }).then((body) => {22 cy.log(body);23 });24 });25});26Cypress.Commands.add('stringifyJsonBody', (options) => {27 return cy.request(options).then((response) => {28 return JSON.stringify(response.body);29 });30});31describe('Test', () => {32 it('should stringify body', () => {33 cy.stringifyJsonBody({34 body: {35 },36 }).then((body) => {37 cy.log(body);38 });39 });40});41Cypress.Commands.add('stringifyJsonBody', (options) => {42 return cy.request(options).then((response) => {43 return JSON.stringify(response.body);44 });45});46describe('Test', () => {47 it('should stringify body', () => {48 cy.stringifyJsonBody({

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.request('/api/v1/login').then((response) => {2 cy.log(JSON.stringify(response.body));3 expect(response.status).eql(200);4})5cy.request('/api/v1/login').then((response) => {6 cy.log(response.stringifyJsonBody());7 expect(response.status).eql(200);8})9cy.request('/api/v1/login').then((response) => {10 cy.log(response.stringifyJsonBody());11 expect(response.status).eql(200);12})13cy.request('/api/v1/login').then((response) => {14 cy.log(response.stringifyJsonBody());15 expect(response.status).eql(200);16})17cy.request('/api/v1/login').then((response) => {18 cy.log(response.stringifyJsonBody());19 expect(response.status).eql(200);20})21cy.request('/api/v1/login').then((response) => {22 cy.log(response.stringifyJsonBody());23 expect(response.status).eql(200);24})25cy.request('/api/v1/login').then((response) => {26 cy.log(response.stringifyJsonBody());27 expect(response.status).eql(200);28})29cy.request('/api/v1/login').then((response) => {30 cy.log(response.stringifyJsonBody());31 expect(response.status).eql(200);32})33cy.request('/api/v1/login').then((response) => {34 cy.log(response.stringifyJsonBody());35 expect(response.status).eql(200);36})37cy.request('/api/v1/login').then((response) => {38 cy.log(response.stringifyJsonBody());39 expect(response.status).eql(200);40})41cy.request('/api/v1/login').then((response) => {42 cy.log(response.stringifyJsonBody());43 expect(response.status).eql(200);44})45cy.request('/api/v1/login').then((response) => {

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful