diff --git a/package-lock.json b/package-lock.json index 36f048d1..dd19b7c4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -2368,6 +2368,14 @@ "postcss-selector-parser": "^6.0.10" } }, + "node_modules/@emailjs/browser": { + "version": "3.11.0", + "resolved": "https://registry.npmjs.org/@emailjs/browser/-/browser-3.11.0.tgz", + "integrity": "sha512-RkY3FKZ3fPdK++OeF46mRTFpmmQWCHUVHZH209P3NE4D5sg2Atg7S2wa3gw5062Gl4clt4Wn5SyC4WhlVZC5pA==", + "engines": { + "node": ">=14.0.0" + } + }, "node_modules/@eslint-community/eslint-utils": { "version": "4.4.0", "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.0.tgz", diff --git a/package.json b/package.json index d7eb0a01..b39e3150 100644 --- a/package.json +++ b/package.json @@ -16,7 +16,7 @@ "web-vitals": "^2.1.4" }, "scripts": { - "start": "react-scripts --openssl-legacy-provider start", + "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --watchAll=false --coverage", "test:watch": "react-scripts test", diff --git a/src/App.js b/src/App.js index 662d8f96..8db76e14 100644 --- a/src/App.js +++ b/src/App.js @@ -2,6 +2,7 @@ import React from "react"; import {BrowserRouter, Routes , Route} from "react-router-dom" import Home from "./pages/Home" import Login from "./pages/Login"; +import QuemSomos from "./pages/QuemSomos"; import ChangePassword from "./pages/ChangePassword"; import NavbarSimple from "./components/NavbarSimple" import Navbar from "./components/Navbar" @@ -14,6 +15,7 @@ function App(){ }/> }/> + }/> } /> }/> }/> diff --git a/src/assets/PoliciaCivilLogo.svg b/src/assets/PoliciaCivilLogo.svg new file mode 100644 index 00000000..9ef90dea --- /dev/null +++ b/src/assets/PoliciaCivilLogo.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/src/assets/React App.html b/src/assets/React App.html new file mode 100644 index 00000000..b27c968b --- /dev/null +++ b/src/assets/React App.html @@ -0,0 +1,292 @@ + + + + + + + +

Quem Somos

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla aliquet elementum eros. Suspendisse gravida velit id vulputate laoreet. Integer ultrices, nulla at aliquam lacinia, metus ligula dapibus metus, eget ornare turpis sapien vitae lorem. Cras sed lorem nec justo pharetra commodo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam vitae erat sed felis auctor feugiat. Proin justo lorem, condimentum nec venenatis nec, malesuada vitae ex. Mauris mattis, diam vitae dictum pellentesque, lectus massa interdum augue, ut dictum ligula massa id nibh. Maecenas auctor elit non augue condimentum suscipit. Integer non luctus augue, nec tristique nunc. Integer ut commodo mi, vitae tincidunt neque.

Quisque non posuere eros, vel posuere purus. Donec vehicula est eu magna fermentum congue. Nam in mollis nisi, a congue augue. Proin vulputate laoreet ex nec interdum. Aliquam ullamcorper malesuada sem, eget eleifend ex ultrices sed. Donec elementum, turpis sit amet auctor elementum, urna erat tempus ex, fringilla elementum elit massa a arcu. Aliquam lobortis ultricies iaculis.

PessoasDois
+ + + + + + React App + + + +
+ + + +
\ No newline at end of file diff --git a/src/assets/React App_files/2.chunk.js b/src/assets/React App_files/2.chunk.js new file mode 100644 index 00000000..2eb1b739 --- /dev/null +++ b/src/assets/React App_files/2.chunk.js @@ -0,0 +1,50093 @@ +(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[2],{ + +/***/ "./node_modules/@remix-run/router/dist/router.js": +/*!*******************************************************!*\ + !*** ./node_modules/@remix-run/router/dist/router.js ***! + \*******************************************************/ +/*! exports provided: AbortedDeferredError, Action, IDLE_BLOCKER, IDLE_FETCHER, IDLE_NAVIGATION, UNSAFE_DEFERRED_SYMBOL, UNSAFE_DeferredData, UNSAFE_ErrorResponseImpl, UNSAFE_convertRouteMatchToUiMatch, UNSAFE_convertRoutesToDataRoutes, UNSAFE_getPathContributingMatches, UNSAFE_invariant, UNSAFE_warning, createBrowserHistory, createHashHistory, createMemoryHistory, createPath, createRouter, createStaticHandler, defer, generatePath, getStaticContextFromError, getToPathname, isDeferredData, isRouteErrorResponse, joinPaths, json, matchPath, matchRoutes, normalizePathname, parsePath, redirect, redirectDocument, resolvePath, resolveTo, stripBasename */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AbortedDeferredError", function() { return AbortedDeferredError; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Action", function() { return Action; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IDLE_BLOCKER", function() { return IDLE_BLOCKER; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IDLE_FETCHER", function() { return IDLE_FETCHER; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IDLE_NAVIGATION", function() { return IDLE_NAVIGATION; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UNSAFE_DEFERRED_SYMBOL", function() { return UNSAFE_DEFERRED_SYMBOL; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UNSAFE_DeferredData", function() { return DeferredData; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UNSAFE_ErrorResponseImpl", function() { return ErrorResponseImpl; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UNSAFE_convertRouteMatchToUiMatch", function() { return convertRouteMatchToUiMatch; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UNSAFE_convertRoutesToDataRoutes", function() { return convertRoutesToDataRoutes; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UNSAFE_getPathContributingMatches", function() { return getPathContributingMatches; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UNSAFE_invariant", function() { return invariant; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UNSAFE_warning", function() { return warning; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createBrowserHistory", function() { return createBrowserHistory; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createHashHistory", function() { return createHashHistory; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createMemoryHistory", function() { return createMemoryHistory; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createPath", function() { return createPath; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createRouter", function() { return createRouter; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createStaticHandler", function() { return createStaticHandler; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defer", function() { return defer; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "generatePath", function() { return generatePath; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getStaticContextFromError", function() { return getStaticContextFromError; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getToPathname", function() { return getToPathname; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isDeferredData", function() { return isDeferredData; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isRouteErrorResponse", function() { return isRouteErrorResponse; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "joinPaths", function() { return joinPaths; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "json", function() { return json; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "matchPath", function() { return matchPath; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "matchRoutes", function() { return matchRoutes; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "normalizePathname", function() { return normalizePathname; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parsePath", function() { return parsePath; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "redirect", function() { return redirect; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "redirectDocument", function() { return redirectDocument; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "resolvePath", function() { return resolvePath; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "resolveTo", function() { return resolveTo; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripBasename", function() { return stripBasename; }); +/** + * @remix-run/router v1.10.0 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */ +function _extends() { + _extends = Object.assign ? Object.assign.bind() : function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + return target; + }; + return _extends.apply(this, arguments); +} + +//////////////////////////////////////////////////////////////////////////////// +//#region Types and Constants +//////////////////////////////////////////////////////////////////////////////// +/** + * Actions represent the type of change to a location value. + */ +var Action; +(function (Action) { + /** + * A POP indicates a change to an arbitrary index in the history stack, such + * as a back or forward navigation. It does not describe the direction of the + * navigation, only that the current index changed. + * + * Note: This is the default action for newly created history objects. + */ + Action["Pop"] = "POP"; + /** + * A PUSH indicates a new entry being added to the history stack, such as when + * a link is clicked and a new page loads. When this happens, all subsequent + * entries in the stack are lost. + */ + Action["Push"] = "PUSH"; + /** + * A REPLACE indicates the entry at the current index in the history stack + * being replaced by a new one. + */ + Action["Replace"] = "REPLACE"; +})(Action || (Action = {})); +const PopStateEventType = "popstate"; +/** + * Memory history stores the current location in memory. It is designed for use + * in stateful non-browser environments like tests and React Native. + */ +function createMemoryHistory(options) { + if (options === void 0) { + options = {}; + } + let { + initialEntries = ["/"], + initialIndex, + v5Compat = false + } = options; + let entries; // Declare so we can access from createMemoryLocation + entries = initialEntries.map((entry, index) => createMemoryLocation(entry, typeof entry === "string" ? null : entry.state, index === 0 ? "default" : undefined)); + let index = clampIndex(initialIndex == null ? entries.length - 1 : initialIndex); + let action = Action.Pop; + let listener = null; + function clampIndex(n) { + return Math.min(Math.max(n, 0), entries.length - 1); + } + function getCurrentLocation() { + return entries[index]; + } + function createMemoryLocation(to, state, key) { + if (state === void 0) { + state = null; + } + let location = createLocation(entries ? getCurrentLocation().pathname : "/", to, state, key); + warning(location.pathname.charAt(0) === "/", "relative pathnames are not supported in memory history: " + JSON.stringify(to)); + return location; + } + function createHref(to) { + return typeof to === "string" ? to : createPath(to); + } + let history = { + get index() { + return index; + }, + get action() { + return action; + }, + get location() { + return getCurrentLocation(); + }, + createHref, + createURL(to) { + return new URL(createHref(to), "http://localhost"); + }, + encodeLocation(to) { + let path = typeof to === "string" ? parsePath(to) : to; + return { + pathname: path.pathname || "", + search: path.search || "", + hash: path.hash || "" + }; + }, + push(to, state) { + action = Action.Push; + let nextLocation = createMemoryLocation(to, state); + index += 1; + entries.splice(index, entries.length, nextLocation); + if (v5Compat && listener) { + listener({ + action, + location: nextLocation, + delta: 1 + }); + } + }, + replace(to, state) { + action = Action.Replace; + let nextLocation = createMemoryLocation(to, state); + entries[index] = nextLocation; + if (v5Compat && listener) { + listener({ + action, + location: nextLocation, + delta: 0 + }); + } + }, + go(delta) { + action = Action.Pop; + let nextIndex = clampIndex(index + delta); + let nextLocation = entries[nextIndex]; + index = nextIndex; + if (listener) { + listener({ + action, + location: nextLocation, + delta + }); + } + }, + listen(fn) { + listener = fn; + return () => { + listener = null; + }; + } + }; + return history; +} +/** + * Browser history stores the location in regular URLs. This is the standard for + * most web apps, but it requires some configuration on the server to ensure you + * serve the same app at multiple URLs. + * + * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory + */ +function createBrowserHistory(options) { + if (options === void 0) { + options = {}; + } + function createBrowserLocation(window, globalHistory) { + let { + pathname, + search, + hash + } = window.location; + return createLocation("", { + pathname, + search, + hash + }, + // state defaults to `null` because `window.history.state` does + globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default"); + } + function createBrowserHref(window, to) { + return typeof to === "string" ? to : createPath(to); + } + return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options); +} +/** + * Hash history stores the location in window.location.hash. This makes it ideal + * for situations where you don't want to send the location to the server for + * some reason, either because you do cannot configure it or the URL space is + * reserved for something else. + * + * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory + */ +function createHashHistory(options) { + if (options === void 0) { + options = {}; + } + function createHashLocation(window, globalHistory) { + let { + pathname = "/", + search = "", + hash = "" + } = parsePath(window.location.hash.substr(1)); + // Hash URL should always have a leading / just like window.location.pathname + // does, so if an app ends up at a route like /#something then we add a + // leading slash so all of our path-matching behaves the same as if it would + // in a browser router. This is particularly important when there exists a + // root splat route () since that matches internally against + // "/*" and we'd expect /#something to 404 in a hash router app. + if (!pathname.startsWith("/") && !pathname.startsWith(".")) { + pathname = "/" + pathname; + } + return createLocation("", { + pathname, + search, + hash + }, + // state defaults to `null` because `window.history.state` does + globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default"); + } + function createHashHref(window, to) { + let base = window.document.querySelector("base"); + let href = ""; + if (base && base.getAttribute("href")) { + let url = window.location.href; + let hashIndex = url.indexOf("#"); + href = hashIndex === -1 ? url : url.slice(0, hashIndex); + } + return href + "#" + (typeof to === "string" ? to : createPath(to)); + } + function validateHashLocation(location, to) { + warning(location.pathname.charAt(0) === "/", "relative pathnames are not supported in hash history.push(" + JSON.stringify(to) + ")"); + } + return getUrlBasedHistory(createHashLocation, createHashHref, validateHashLocation, options); +} +function invariant(value, message) { + if (value === false || value === null || typeof value === "undefined") { + throw new Error(message); + } +} +function warning(cond, message) { + if (!cond) { + // eslint-disable-next-line no-console + if (typeof console !== "undefined") console.warn(message); + try { + // Welcome to debugging history! + // + // This error is thrown as a convenience, so you can more easily + // find the source for a warning that appears in the console by + // enabling "pause on exceptions" in your JavaScript debugger. + throw new Error(message); + // eslint-disable-next-line no-empty + } catch (e) {} + } +} +function createKey() { + return Math.random().toString(36).substr(2, 8); +} +/** + * For browser-based histories, we combine the state and key into an object + */ +function getHistoryState(location, index) { + return { + usr: location.state, + key: location.key, + idx: index + }; +} +/** + * Creates a Location object with a unique key from the given Path + */ +function createLocation(current, to, state, key) { + if (state === void 0) { + state = null; + } + let location = _extends({ + pathname: typeof current === "string" ? current : current.pathname, + search: "", + hash: "" + }, typeof to === "string" ? parsePath(to) : to, { + state, + // TODO: This could be cleaned up. push/replace should probably just take + // full Locations now and avoid the need to run through this flow at all + // But that's a pretty big refactor to the current test suite so going to + // keep as is for the time being and just let any incoming keys take precedence + key: to && to.key || key || createKey() + }); + return location; +} +/** + * Creates a string URL path from the given pathname, search, and hash components. + */ +function createPath(_ref) { + let { + pathname = "/", + search = "", + hash = "" + } = _ref; + if (search && search !== "?") pathname += search.charAt(0) === "?" ? search : "?" + search; + if (hash && hash !== "#") pathname += hash.charAt(0) === "#" ? hash : "#" + hash; + return pathname; +} +/** + * Parses a string URL path into its separate pathname, search, and hash components. + */ +function parsePath(path) { + let parsedPath = {}; + if (path) { + let hashIndex = path.indexOf("#"); + if (hashIndex >= 0) { + parsedPath.hash = path.substr(hashIndex); + path = path.substr(0, hashIndex); + } + let searchIndex = path.indexOf("?"); + if (searchIndex >= 0) { + parsedPath.search = path.substr(searchIndex); + path = path.substr(0, searchIndex); + } + if (path) { + parsedPath.pathname = path; + } + } + return parsedPath; +} +function getUrlBasedHistory(getLocation, createHref, validateLocation, options) { + if (options === void 0) { + options = {}; + } + let { + window = document.defaultView, + v5Compat = false + } = options; + let globalHistory = window.history; + let action = Action.Pop; + let listener = null; + let index = getIndex(); + // Index should only be null when we initialize. If not, it's because the + // user called history.pushState or history.replaceState directly, in which + // case we should log a warning as it will result in bugs. + if (index == null) { + index = 0; + globalHistory.replaceState(_extends({}, globalHistory.state, { + idx: index + }), ""); + } + function getIndex() { + let state = globalHistory.state || { + idx: null + }; + return state.idx; + } + function handlePop() { + action = Action.Pop; + let nextIndex = getIndex(); + let delta = nextIndex == null ? null : nextIndex - index; + index = nextIndex; + if (listener) { + listener({ + action, + location: history.location, + delta + }); + } + } + function push(to, state) { + action = Action.Push; + let location = createLocation(history.location, to, state); + if (validateLocation) validateLocation(location, to); + index = getIndex() + 1; + let historyState = getHistoryState(location, index); + let url = history.createHref(location); + // try...catch because iOS limits us to 100 pushState calls :/ + try { + globalHistory.pushState(historyState, "", url); + } catch (error) { + // If the exception is because `state` can't be serialized, let that throw + // outwards just like a replace call would so the dev knows the cause + // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps + // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal + if (error instanceof DOMException && error.name === "DataCloneError") { + throw error; + } + // They are going to lose state here, but there is no real + // way to warn them about it since the page will refresh... + window.location.assign(url); + } + if (v5Compat && listener) { + listener({ + action, + location: history.location, + delta: 1 + }); + } + } + function replace(to, state) { + action = Action.Replace; + let location = createLocation(history.location, to, state); + if (validateLocation) validateLocation(location, to); + index = getIndex(); + let historyState = getHistoryState(location, index); + let url = history.createHref(location); + globalHistory.replaceState(historyState, "", url); + if (v5Compat && listener) { + listener({ + action, + location: history.location, + delta: 0 + }); + } + } + function createURL(to) { + // window.location.origin is "null" (the literal string value) in Firefox + // under certain conditions, notably when serving from a local HTML file + // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297 + let base = window.location.origin !== "null" ? window.location.origin : window.location.href; + let href = typeof to === "string" ? to : createPath(to); + invariant(base, "No window.location.(origin|href) available to create URL for href: " + href); + return new URL(href, base); + } + let history = { + get action() { + return action; + }, + get location() { + return getLocation(window, globalHistory); + }, + listen(fn) { + if (listener) { + throw new Error("A history only accepts one active listener"); + } + window.addEventListener(PopStateEventType, handlePop); + listener = fn; + return () => { + window.removeEventListener(PopStateEventType, handlePop); + listener = null; + }; + }, + createHref(to) { + return createHref(window, to); + }, + createURL, + encodeLocation(to) { + // Encode a Location the same way window.location would + let url = createURL(to); + return { + pathname: url.pathname, + search: url.search, + hash: url.hash + }; + }, + push, + replace, + go(n) { + return globalHistory.go(n); + } + }; + return history; +} +//#endregion + +var ResultType; +(function (ResultType) { + ResultType["data"] = "data"; + ResultType["deferred"] = "deferred"; + ResultType["redirect"] = "redirect"; + ResultType["error"] = "error"; +})(ResultType || (ResultType = {})); +const immutableRouteKeys = new Set(["lazy", "caseSensitive", "path", "id", "index", "children"]); +function isIndexRoute(route) { + return route.index === true; +} +// Walk the route tree generating unique IDs where necessary, so we are working +// solely with AgnosticDataRouteObject's within the Router +function convertRoutesToDataRoutes(routes, mapRouteProperties, parentPath, manifest) { + if (parentPath === void 0) { + parentPath = []; + } + if (manifest === void 0) { + manifest = {}; + } + return routes.map((route, index) => { + let treePath = [...parentPath, index]; + let id = typeof route.id === "string" ? route.id : treePath.join("-"); + invariant(route.index !== true || !route.children, "Cannot specify children on an index route"); + invariant(!manifest[id], "Found a route id collision on id \"" + id + "\". Route " + "id's must be globally unique within Data Router usages"); + if (isIndexRoute(route)) { + let indexRoute = _extends({}, route, mapRouteProperties(route), { + id + }); + manifest[id] = indexRoute; + return indexRoute; + } else { + let pathOrLayoutRoute = _extends({}, route, mapRouteProperties(route), { + id, + children: undefined + }); + manifest[id] = pathOrLayoutRoute; + if (route.children) { + pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, mapRouteProperties, treePath, manifest); + } + return pathOrLayoutRoute; + } + }); +} +/** + * Matches the given routes to a location and returns the match data. + * + * @see https://reactrouter.com/utils/match-routes + */ +function matchRoutes(routes, locationArg, basename) { + if (basename === void 0) { + basename = "/"; + } + let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg; + let pathname = stripBasename(location.pathname || "/", basename); + if (pathname == null) { + return null; + } + let branches = flattenRoutes(routes); + rankRouteBranches(branches); + let matches = null; + for (let i = 0; matches == null && i < branches.length; ++i) { + matches = matchRouteBranch(branches[i], + // Incoming pathnames are generally encoded from either window.location + // or from router.navigate, but we want to match against the unencoded + // paths in the route definitions. Memory router locations won't be + // encoded here but there also shouldn't be anything to decode so this + // should be a safe operation. This avoids needing matchRoutes to be + // history-aware. + safelyDecodeURI(pathname)); + } + return matches; +} +function convertRouteMatchToUiMatch(match, loaderData) { + let { + route, + pathname, + params + } = match; + return { + id: route.id, + pathname, + params, + data: loaderData[route.id], + handle: route.handle + }; +} +function flattenRoutes(routes, branches, parentsMeta, parentPath) { + if (branches === void 0) { + branches = []; + } + if (parentsMeta === void 0) { + parentsMeta = []; + } + if (parentPath === void 0) { + parentPath = ""; + } + let flattenRoute = (route, index, relativePath) => { + let meta = { + relativePath: relativePath === undefined ? route.path || "" : relativePath, + caseSensitive: route.caseSensitive === true, + childrenIndex: index, + route + }; + if (meta.relativePath.startsWith("/")) { + invariant(meta.relativePath.startsWith(parentPath), "Absolute route path \"" + meta.relativePath + "\" nested under path " + ("\"" + parentPath + "\" is not valid. An absolute child route path ") + "must start with the combined path of all its parent routes."); + meta.relativePath = meta.relativePath.slice(parentPath.length); + } + let path = joinPaths([parentPath, meta.relativePath]); + let routesMeta = parentsMeta.concat(meta); + // Add the children before adding this route to the array, so we traverse the + // route tree depth-first and child routes appear before their parents in + // the "flattened" version. + if (route.children && route.children.length > 0) { + invariant( + // Our types know better, but runtime JS may not! + // @ts-expect-error + route.index !== true, "Index routes must not have child routes. Please remove " + ("all child routes from route path \"" + path + "\".")); + flattenRoutes(route.children, branches, routesMeta, path); + } + // Routes without a path shouldn't ever match by themselves unless they are + // index routes, so don't add them to the list of possible branches. + if (route.path == null && !route.index) { + return; + } + branches.push({ + path, + score: computeScore(path, route.index), + routesMeta + }); + }; + routes.forEach((route, index) => { + var _route$path; + // coarse-grain check for optional params + if (route.path === "" || !((_route$path = route.path) != null && _route$path.includes("?"))) { + flattenRoute(route, index); + } else { + for (let exploded of explodeOptionalSegments(route.path)) { + flattenRoute(route, index, exploded); + } + } + }); + return branches; +} +/** + * Computes all combinations of optional path segments for a given path, + * excluding combinations that are ambiguous and of lower priority. + * + * For example, `/one/:two?/three/:four?/:five?` explodes to: + * - `/one/three` + * - `/one/:two/three` + * - `/one/three/:four` + * - `/one/three/:five` + * - `/one/:two/three/:four` + * - `/one/:two/three/:five` + * - `/one/three/:four/:five` + * - `/one/:two/three/:four/:five` + */ +function explodeOptionalSegments(path) { + let segments = path.split("/"); + if (segments.length === 0) return []; + let [first, ...rest] = segments; + // Optional path segments are denoted by a trailing `?` + let isOptional = first.endsWith("?"); + // Compute the corresponding required segment: `foo?` -> `foo` + let required = first.replace(/\?$/, ""); + if (rest.length === 0) { + // Intepret empty string as omitting an optional segment + // `["one", "", "three"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three` + return isOptional ? [required, ""] : [required]; + } + let restExploded = explodeOptionalSegments(rest.join("/")); + let result = []; + // All child paths with the prefix. Do this for all children before the + // optional version for all children, so we get consistent ordering where the + // parent optional aspect is preferred as required. Otherwise, we can get + // child sections interspersed where deeper optional segments are higher than + // parent optional segments, where for example, /:two would explode _earlier_ + // then /:one. By always including the parent as required _for all children_ + // first, we avoid this issue + result.push(...restExploded.map(subpath => subpath === "" ? required : [required, subpath].join("/"))); + // Then, if this is an optional value, add all child versions without + if (isOptional) { + result.push(...restExploded); + } + // for absolute paths, ensure `/` instead of empty segment + return result.map(exploded => path.startsWith("/") && exploded === "" ? "/" : exploded); +} +function rankRouteBranches(branches) { + branches.sort((a, b) => a.score !== b.score ? b.score - a.score // Higher score first + : compareIndexes(a.routesMeta.map(meta => meta.childrenIndex), b.routesMeta.map(meta => meta.childrenIndex))); +} +const paramRe = /^:\w+$/; +const dynamicSegmentValue = 3; +const indexRouteValue = 2; +const emptySegmentValue = 1; +const staticSegmentValue = 10; +const splatPenalty = -2; +const isSplat = s => s === "*"; +function computeScore(path, index) { + let segments = path.split("/"); + let initialScore = segments.length; + if (segments.some(isSplat)) { + initialScore += splatPenalty; + } + if (index) { + initialScore += indexRouteValue; + } + return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore); +} +function compareIndexes(a, b) { + let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]); + return siblings ? + // If two routes are siblings, we should try to match the earlier sibling + // first. This allows people to have fine-grained control over the matching + // behavior by simply putting routes with identical paths in the order they + // want them tried. + a[a.length - 1] - b[b.length - 1] : + // Otherwise, it doesn't really make sense to rank non-siblings by index, + // so they sort equally. + 0; +} +function matchRouteBranch(branch, pathname) { + let { + routesMeta + } = branch; + let matchedParams = {}; + let matchedPathname = "/"; + let matches = []; + for (let i = 0; i < routesMeta.length; ++i) { + let meta = routesMeta[i]; + let end = i === routesMeta.length - 1; + let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/"; + let match = matchPath({ + path: meta.relativePath, + caseSensitive: meta.caseSensitive, + end + }, remainingPathname); + if (!match) return null; + Object.assign(matchedParams, match.params); + let route = meta.route; + matches.push({ + // TODO: Can this as be avoided? + params: matchedParams, + pathname: joinPaths([matchedPathname, match.pathname]), + pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])), + route + }); + if (match.pathnameBase !== "/") { + matchedPathname = joinPaths([matchedPathname, match.pathnameBase]); + } + } + return matches; +} +/** + * Returns a path with params interpolated. + * + * @see https://reactrouter.com/utils/generate-path + */ +function generatePath(originalPath, params) { + if (params === void 0) { + params = {}; + } + let path = originalPath; + if (path.endsWith("*") && path !== "*" && !path.endsWith("/*")) { + warning(false, "Route path \"" + path + "\" will be treated as if it were " + ("\"" + path.replace(/\*$/, "/*") + "\" because the `*` character must ") + "always follow a `/` in the pattern. To get rid of this warning, " + ("please change the route path to \"" + path.replace(/\*$/, "/*") + "\".")); + path = path.replace(/\*$/, "/*"); + } + // ensure `/` is added at the beginning if the path is absolute + const prefix = path.startsWith("/") ? "/" : ""; + const stringify = p => p == null ? "" : typeof p === "string" ? p : String(p); + const segments = path.split(/\/+/).map((segment, index, array) => { + const isLastSegment = index === array.length - 1; + // only apply the splat if it's the last segment + if (isLastSegment && segment === "*") { + const star = "*"; + // Apply the splat + return stringify(params[star]); + } + const keyMatch = segment.match(/^:(\w+)(\??)$/); + if (keyMatch) { + const [, key, optional] = keyMatch; + let param = params[key]; + invariant(optional === "?" || param != null, "Missing \":" + key + "\" param"); + return stringify(param); + } + // Remove any optional markers from optional static segments + return segment.replace(/\?$/g, ""); + }) + // Remove empty segments + .filter(segment => !!segment); + return prefix + segments.join("/"); +} +/** + * Performs pattern matching on a URL pathname and returns information about + * the match. + * + * @see https://reactrouter.com/utils/match-path + */ +function matchPath(pattern, pathname) { + if (typeof pattern === "string") { + pattern = { + path: pattern, + caseSensitive: false, + end: true + }; + } + let [matcher, paramNames] = compilePath(pattern.path, pattern.caseSensitive, pattern.end); + let match = pathname.match(matcher); + if (!match) return null; + let matchedPathname = match[0]; + let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1"); + let captureGroups = match.slice(1); + let params = paramNames.reduce((memo, paramName, index) => { + // We need to compute the pathnameBase here using the raw splat value + // instead of using params["*"] later because it will be decoded then + if (paramName === "*") { + let splatValue = captureGroups[index] || ""; + pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1"); + } + memo[paramName] = safelyDecodeURIComponent(captureGroups[index] || "", paramName); + return memo; + }, {}); + return { + params, + pathname: matchedPathname, + pathnameBase, + pattern + }; +} +function compilePath(path, caseSensitive, end) { + if (caseSensitive === void 0) { + caseSensitive = false; + } + if (end === void 0) { + end = true; + } + warning(path === "*" || !path.endsWith("*") || path.endsWith("/*"), "Route path \"" + path + "\" will be treated as if it were " + ("\"" + path.replace(/\*$/, "/*") + "\" because the `*` character must ") + "always follow a `/` in the pattern. To get rid of this warning, " + ("please change the route path to \"" + path.replace(/\*$/, "/*") + "\".")); + let paramNames = []; + let regexpSource = "^" + path.replace(/\/*\*?$/, "") // Ignore trailing / and /*, we'll handle it below + .replace(/^\/*/, "/") // Make sure it has a leading / + .replace(/[\\.*+^$?{}|()[\]]/g, "\\$&") // Escape special regex chars + .replace(/\/:(\w+)/g, (_, paramName) => { + paramNames.push(paramName); + return "/([^\\/]+)"; + }); + if (path.endsWith("*")) { + paramNames.push("*"); + regexpSource += path === "*" || path === "/*" ? "(.*)$" // Already matched the initial /, just match the rest + : "(?:\\/(.+)|\\/*)$"; // Don't include the / in params["*"] + } else if (end) { + // When matching to the end, ignore trailing slashes + regexpSource += "\\/*$"; + } else if (path !== "" && path !== "/") { + // If our path is non-empty and contains anything beyond an initial slash, + // then we have _some_ form of path in our regex, so we should expect to + // match only if we find the end of this path segment. Look for an optional + // non-captured trailing slash (to match a portion of the URL) or the end + // of the path (if we've matched to the end). We used to do this with a + // word boundary but that gives false positives on routes like + // /user-preferences since `-` counts as a word boundary. + regexpSource += "(?:(?=\\/|$))"; + } else ; + let matcher = new RegExp(regexpSource, caseSensitive ? undefined : "i"); + return [matcher, paramNames]; +} +function safelyDecodeURI(value) { + try { + return decodeURI(value); + } catch (error) { + warning(false, "The URL path \"" + value + "\" could not be decoded because it is is a " + "malformed URL segment. This is probably due to a bad percent " + ("encoding (" + error + ").")); + return value; + } +} +function safelyDecodeURIComponent(value, paramName) { + try { + return decodeURIComponent(value); + } catch (error) { + warning(false, "The value for the URL param \"" + paramName + "\" will not be decoded because" + (" the string \"" + value + "\" is a malformed URL segment. This is probably") + (" due to a bad percent encoding (" + error + ").")); + return value; + } +} +/** + * @private + */ +function stripBasename(pathname, basename) { + if (basename === "/") return pathname; + if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) { + return null; + } + // We want to leave trailing slash behavior in the user's control, so if they + // specify a basename with a trailing slash, we should support it + let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length; + let nextChar = pathname.charAt(startIndex); + if (nextChar && nextChar !== "/") { + // pathname does not start with basename/ + return null; + } + return pathname.slice(startIndex) || "/"; +} +/** + * Returns a resolved path object relative to the given pathname. + * + * @see https://reactrouter.com/utils/resolve-path + */ +function resolvePath(to, fromPathname) { + if (fromPathname === void 0) { + fromPathname = "/"; + } + let { + pathname: toPathname, + search = "", + hash = "" + } = typeof to === "string" ? parsePath(to) : to; + let pathname = toPathname ? toPathname.startsWith("/") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname; + return { + pathname, + search: normalizeSearch(search), + hash: normalizeHash(hash) + }; +} +function resolvePathname(relativePath, fromPathname) { + let segments = fromPathname.replace(/\/+$/, "").split("/"); + let relativeSegments = relativePath.split("/"); + relativeSegments.forEach(segment => { + if (segment === "..") { + // Keep the root "" segment so the pathname starts at / + if (segments.length > 1) segments.pop(); + } else if (segment !== ".") { + segments.push(segment); + } + }); + return segments.length > 1 ? segments.join("/") : "/"; +} +function getInvalidPathError(char, field, dest, path) { + return "Cannot include a '" + char + "' character in a manually specified " + ("`to." + field + "` field [" + JSON.stringify(path) + "]. Please separate it out to the ") + ("`to." + dest + "` field. Alternatively you may provide the full path as ") + "a string in and the router will parse it for you."; +} +/** + * @private + * + * When processing relative navigation we want to ignore ancestor routes that + * do not contribute to the path, such that index/pathless layout routes don't + * interfere. + * + * For example, when moving a route element into an index route and/or a + * pathless layout route, relative link behavior contained within should stay + * the same. Both of the following examples should link back to the root: + * + * + * + * + * + * + * + * }> // <-- Does not contribute + * // <-- Does not contribute + * + * + */ +function getPathContributingMatches(matches) { + return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0); +} +/** + * @private + */ +function resolveTo(toArg, routePathnames, locationPathname, isPathRelative) { + if (isPathRelative === void 0) { + isPathRelative = false; + } + let to; + if (typeof toArg === "string") { + to = parsePath(toArg); + } else { + to = _extends({}, toArg); + invariant(!to.pathname || !to.pathname.includes("?"), getInvalidPathError("?", "pathname", "search", to)); + invariant(!to.pathname || !to.pathname.includes("#"), getInvalidPathError("#", "pathname", "hash", to)); + invariant(!to.search || !to.search.includes("#"), getInvalidPathError("#", "search", "hash", to)); + } + let isEmptyPath = toArg === "" || to.pathname === ""; + let toPathname = isEmptyPath ? "/" : to.pathname; + let from; + // Routing is relative to the current pathname if explicitly requested. + // + // If a pathname is explicitly provided in `to`, it should be relative to the + // route context. This is explained in `Note on `` values` in our + // migration guide from v5 as a means of disambiguation between `to` values + // that begin with `/` and those that do not. However, this is problematic for + // `to` values that do not provide a pathname. `to` can simply be a search or + // hash string, in which case we should assume that the navigation is relative + // to the current location's pathname and *not* the route pathname. + if (isPathRelative || toPathname == null) { + from = locationPathname; + } else { + let routePathnameIndex = routePathnames.length - 1; + if (toPathname.startsWith("..")) { + let toSegments = toPathname.split("/"); + // Each leading .. segment means "go up one route" instead of "go up one + // URL segment". This is a key difference from how works and a + // major reason we call this a "to" value instead of a "href". + while (toSegments[0] === "..") { + toSegments.shift(); + routePathnameIndex -= 1; + } + to.pathname = toSegments.join("/"); + } + // If there are more ".." segments than parent routes, resolve relative to + // the root / URL. + from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/"; + } + let path = resolvePath(to, from); + // Ensure the pathname has a trailing slash if the original "to" had one + let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/"); + // Or if this was a link to the current path which has a trailing slash + let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/"); + if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) { + path.pathname += "/"; + } + return path; +} +/** + * @private + */ +function getToPathname(to) { + // Empty strings should be treated the same as / paths + return to === "" || to.pathname === "" ? "/" : typeof to === "string" ? parsePath(to).pathname : to.pathname; +} +/** + * @private + */ +const joinPaths = paths => paths.join("/").replace(/\/\/+/g, "/"); +/** + * @private + */ +const normalizePathname = pathname => pathname.replace(/\/+$/, "").replace(/^\/*/, "/"); +/** + * @private + */ +const normalizeSearch = search => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search; +/** + * @private + */ +const normalizeHash = hash => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash; +/** + * This is a shortcut for creating `application/json` responses. Converts `data` + * to JSON and sets the `Content-Type` header. + */ +const json = function json(data, init) { + if (init === void 0) { + init = {}; + } + let responseInit = typeof init === "number" ? { + status: init + } : init; + let headers = new Headers(responseInit.headers); + if (!headers.has("Content-Type")) { + headers.set("Content-Type", "application/json; charset=utf-8"); + } + return new Response(JSON.stringify(data), _extends({}, responseInit, { + headers + })); +}; +class AbortedDeferredError extends Error {} +class DeferredData { + constructor(data, responseInit) { + this.pendingKeysSet = new Set(); + this.subscribers = new Set(); + this.deferredKeys = []; + invariant(data && typeof data === "object" && !Array.isArray(data), "defer() only accepts plain objects"); + // Set up an AbortController + Promise we can race against to exit early + // cancellation + let reject; + this.abortPromise = new Promise((_, r) => reject = r); + this.controller = new AbortController(); + let onAbort = () => reject(new AbortedDeferredError("Deferred data aborted")); + this.unlistenAbortSignal = () => this.controller.signal.removeEventListener("abort", onAbort); + this.controller.signal.addEventListener("abort", onAbort); + this.data = Object.entries(data).reduce((acc, _ref) => { + let [key, value] = _ref; + return Object.assign(acc, { + [key]: this.trackPromise(key, value) + }); + }, {}); + if (this.done) { + // All incoming values were resolved + this.unlistenAbortSignal(); + } + this.init = responseInit; + } + trackPromise(key, value) { + if (!(value instanceof Promise)) { + return value; + } + this.deferredKeys.push(key); + this.pendingKeysSet.add(key); + // We store a little wrapper promise that will be extended with + // _data/_error props upon resolve/reject + let promise = Promise.race([value, this.abortPromise]).then(data => this.onSettle(promise, key, undefined, data), error => this.onSettle(promise, key, error)); + // Register rejection listeners to avoid uncaught promise rejections on + // errors or aborted deferred values + promise.catch(() => {}); + Object.defineProperty(promise, "_tracked", { + get: () => true + }); + return promise; + } + onSettle(promise, key, error, data) { + if (this.controller.signal.aborted && error instanceof AbortedDeferredError) { + this.unlistenAbortSignal(); + Object.defineProperty(promise, "_error", { + get: () => error + }); + return Promise.reject(error); + } + this.pendingKeysSet.delete(key); + if (this.done) { + // Nothing left to abort! + this.unlistenAbortSignal(); + } + // If the promise was resolved/rejected with undefined, we'll throw an error as you + // should always resolve with a value or null + if (error === undefined && data === undefined) { + let undefinedError = new Error("Deferred data for key \"" + key + "\" resolved/rejected with `undefined`, " + "you must resolve/reject with a value or `null`."); + Object.defineProperty(promise, "_error", { + get: () => undefinedError + }); + this.emit(false, key); + return Promise.reject(undefinedError); + } + if (data === undefined) { + Object.defineProperty(promise, "_error", { + get: () => error + }); + this.emit(false, key); + return Promise.reject(error); + } + Object.defineProperty(promise, "_data", { + get: () => data + }); + this.emit(false, key); + return data; + } + emit(aborted, settledKey) { + this.subscribers.forEach(subscriber => subscriber(aborted, settledKey)); + } + subscribe(fn) { + this.subscribers.add(fn); + return () => this.subscribers.delete(fn); + } + cancel() { + this.controller.abort(); + this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k)); + this.emit(true); + } + async resolveData(signal) { + let aborted = false; + if (!this.done) { + let onAbort = () => this.cancel(); + signal.addEventListener("abort", onAbort); + aborted = await new Promise(resolve => { + this.subscribe(aborted => { + signal.removeEventListener("abort", onAbort); + if (aborted || this.done) { + resolve(aborted); + } + }); + }); + } + return aborted; + } + get done() { + return this.pendingKeysSet.size === 0; + } + get unwrappedData() { + invariant(this.data !== null && this.done, "Can only unwrap data on initialized and settled deferreds"); + return Object.entries(this.data).reduce((acc, _ref2) => { + let [key, value] = _ref2; + return Object.assign(acc, { + [key]: unwrapTrackedPromise(value) + }); + }, {}); + } + get pendingKeys() { + return Array.from(this.pendingKeysSet); + } +} +function isTrackedPromise(value) { + return value instanceof Promise && value._tracked === true; +} +function unwrapTrackedPromise(value) { + if (!isTrackedPromise(value)) { + return value; + } + if (value._error) { + throw value._error; + } + return value._data; +} +const defer = function defer(data, init) { + if (init === void 0) { + init = {}; + } + let responseInit = typeof init === "number" ? { + status: init + } : init; + return new DeferredData(data, responseInit); +}; +/** + * A redirect response. Sets the status code and the `Location` header. + * Defaults to "302 Found". + */ +const redirect = function redirect(url, init) { + if (init === void 0) { + init = 302; + } + let responseInit = init; + if (typeof responseInit === "number") { + responseInit = { + status: responseInit + }; + } else if (typeof responseInit.status === "undefined") { + responseInit.status = 302; + } + let headers = new Headers(responseInit.headers); + headers.set("Location", url); + return new Response(null, _extends({}, responseInit, { + headers + })); +}; +/** + * A redirect response that will force a document reload to the new location. + * Sets the status code and the `Location` header. + * Defaults to "302 Found". + */ +const redirectDocument = (url, init) => { + let response = redirect(url, init); + response.headers.set("X-Remix-Reload-Document", "true"); + return response; +}; +/** + * @private + * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies + * + * We don't export the class for public use since it's an implementation + * detail, but we export the interface above so folks can build their own + * abstractions around instances via isRouteErrorResponse() + */ +class ErrorResponseImpl { + constructor(status, statusText, data, internal) { + if (internal === void 0) { + internal = false; + } + this.status = status; + this.statusText = statusText || ""; + this.internal = internal; + if (data instanceof Error) { + this.data = data.toString(); + this.error = data; + } else { + this.data = data; + } + } +} +/** + * Check if the given error is an ErrorResponse generated from a 4xx/5xx + * Response thrown from an action/loader + */ +function isRouteErrorResponse(error) { + return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error; +} +const validMutationMethodsArr = ["post", "put", "patch", "delete"]; +const validMutationMethods = new Set(validMutationMethodsArr); +const validRequestMethodsArr = ["get", ...validMutationMethodsArr]; +const validRequestMethods = new Set(validRequestMethodsArr); +const redirectStatusCodes = new Set([301, 302, 303, 307, 308]); +const redirectPreserveMethodStatusCodes = new Set([307, 308]); +const IDLE_NAVIGATION = { + state: "idle", + location: undefined, + formMethod: undefined, + formAction: undefined, + formEncType: undefined, + formData: undefined, + json: undefined, + text: undefined +}; +const IDLE_FETCHER = { + state: "idle", + data: undefined, + formMethod: undefined, + formAction: undefined, + formEncType: undefined, + formData: undefined, + json: undefined, + text: undefined +}; +const IDLE_BLOCKER = { + state: "unblocked", + proceed: undefined, + reset: undefined, + location: undefined +}; +const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i; +const defaultMapRouteProperties = route => ({ + hasErrorBoundary: Boolean(route.hasErrorBoundary) +}); +const TRANSITIONS_STORAGE_KEY = "remix-router-transitions"; +//#endregion +//////////////////////////////////////////////////////////////////////////////// +//#region createRouter +//////////////////////////////////////////////////////////////////////////////// +/** + * Create a router and listen to history POP navigations + */ +function createRouter(init) { + const routerWindow = init.window ? init.window : typeof window !== "undefined" ? window : undefined; + const isBrowser = typeof routerWindow !== "undefined" && typeof routerWindow.document !== "undefined" && typeof routerWindow.document.createElement !== "undefined"; + const isServer = !isBrowser; + invariant(init.routes.length > 0, "You must provide a non-empty routes array to createRouter"); + let mapRouteProperties; + if (init.mapRouteProperties) { + mapRouteProperties = init.mapRouteProperties; + } else if (init.detectErrorBoundary) { + // If they are still using the deprecated version, wrap it with the new API + let detectErrorBoundary = init.detectErrorBoundary; + mapRouteProperties = route => ({ + hasErrorBoundary: detectErrorBoundary(route) + }); + } else { + mapRouteProperties = defaultMapRouteProperties; + } + // Routes keyed by ID + let manifest = {}; + // Routes in tree format for matching + let dataRoutes = convertRoutesToDataRoutes(init.routes, mapRouteProperties, undefined, manifest); + let inFlightDataRoutes; + let basename = init.basename || "/"; + // Config driven behavior flags + let future = _extends({ + v7_normalizeFormMethod: false, + v7_prependBasename: false + }, init.future); + // Cleanup function for history + let unlistenHistory = null; + // Externally-provided functions to call on all state changes + let subscribers = new Set(); + // Externally-provided object to hold scroll restoration locations during routing + let savedScrollPositions = null; + // Externally-provided function to get scroll restoration keys + let getScrollRestorationKey = null; + // Externally-provided function to get current scroll position + let getScrollPosition = null; + // One-time flag to control the initial hydration scroll restoration. Because + // we don't get the saved positions from until _after_ + // the initial render, we need to manually trigger a separate updateState to + // send along the restoreScrollPosition + // Set to true if we have `hydrationData` since we assume we were SSR'd and that + // SSR did the initial scroll restoration. + let initialScrollRestored = init.hydrationData != null; + let initialMatches = matchRoutes(dataRoutes, init.history.location, basename); + let initialErrors = null; + if (initialMatches == null) { + // If we do not match a user-provided-route, fall back to the root + // to allow the error boundary to take over + let error = getInternalRouterError(404, { + pathname: init.history.location.pathname + }); + let { + matches, + route + } = getShortCircuitMatches(dataRoutes); + initialMatches = matches; + initialErrors = { + [route.id]: error + }; + } + let initialized = + // All initialMatches need to be loaded before we're ready. If we have lazy + // functions around still then we'll need to run them in initialize() + !initialMatches.some(m => m.route.lazy) && ( + // And we have to either have no loaders or have been provided hydrationData + !initialMatches.some(m => m.route.loader) || init.hydrationData != null); + let router; + let state = { + historyAction: init.history.action, + location: init.history.location, + matches: initialMatches, + initialized, + navigation: IDLE_NAVIGATION, + // Don't restore on initial updateState() if we were SSR'd + restoreScrollPosition: init.hydrationData != null ? false : null, + preventScrollReset: false, + revalidation: "idle", + loaderData: init.hydrationData && init.hydrationData.loaderData || {}, + actionData: init.hydrationData && init.hydrationData.actionData || null, + errors: init.hydrationData && init.hydrationData.errors || initialErrors, + fetchers: new Map(), + blockers: new Map() + }; + // -- Stateful internal variables to manage navigations -- + // Current navigation in progress (to be committed in completeNavigation) + let pendingAction = Action.Pop; + // Should the current navigation prevent the scroll reset if scroll cannot + // be restored? + let pendingPreventScrollReset = false; + // AbortController for the active navigation + let pendingNavigationController; + // Should the current navigation enable document.startViewTransition? + let pendingViewTransitionEnabled = false; + // Store applied view transitions so we can apply them on POP + let appliedViewTransitions = new Map(); + // Cleanup function for persisting applied transitions to sessionStorage + let removePageHideEventListener = null; + // We use this to avoid touching history in completeNavigation if a + // revalidation is entirely uninterrupted + let isUninterruptedRevalidation = false; + // Use this internal flag to force revalidation of all loaders: + // - submissions (completed or interrupted) + // - useRevalidator() + // - X-Remix-Revalidate (from redirect) + let isRevalidationRequired = false; + // Use this internal array to capture routes that require revalidation due + // to a cancelled deferred on action submission + let cancelledDeferredRoutes = []; + // Use this internal array to capture fetcher loads that were cancelled by an + // action navigation and require revalidation + let cancelledFetcherLoads = []; + // AbortControllers for any in-flight fetchers + let fetchControllers = new Map(); + // Track loads based on the order in which they started + let incrementingLoadId = 0; + // Track the outstanding pending navigation data load to be compared against + // the globally incrementing load when a fetcher load lands after a completed + // navigation + let pendingNavigationLoadId = -1; + // Fetchers that triggered data reloads as a result of their actions + let fetchReloadIds = new Map(); + // Fetchers that triggered redirect navigations + let fetchRedirectIds = new Set(); + // Most recent href/match for fetcher.load calls for fetchers + let fetchLoadMatches = new Map(); + // Store DeferredData instances for active route matches. When a + // route loader returns defer() we stick one in here. Then, when a nested + // promise resolves we update loaderData. If a new navigation starts we + // cancel active deferreds for eliminated routes. + let activeDeferreds = new Map(); + // Store blocker functions in a separate Map outside of router state since + // we don't need to update UI state if they change + let blockerFunctions = new Map(); + // Flag to ignore the next history update, so we can revert the URL change on + // a POP navigation that was blocked by the user without touching router state + let ignoreNextHistoryUpdate = false; + // Initialize the router, all side effects should be kicked off from here. + // Implemented as a Fluent API for ease of: + // let router = createRouter(init).initialize(); + function initialize() { + // If history informs us of a POP navigation, start the navigation but do not update + // state. We'll update our own state once the navigation completes + unlistenHistory = init.history.listen(_ref => { + let { + action: historyAction, + location, + delta + } = _ref; + // Ignore this event if it was just us resetting the URL from a + // blocked POP navigation + if (ignoreNextHistoryUpdate) { + ignoreNextHistoryUpdate = false; + return; + } + warning(blockerFunctions.size === 0 || delta != null, "You are trying to use a blocker on a POP navigation to a location " + "that was not created by @remix-run/router. This will fail silently in " + "production. This can happen if you are navigating outside the router " + "via `window.history.pushState`/`window.location.hash` instead of using " + "router navigation APIs. This can also happen if you are using " + "createHashRouter and the user manually changes the URL."); + let blockerKey = shouldBlockNavigation({ + currentLocation: state.location, + nextLocation: location, + historyAction + }); + if (blockerKey && delta != null) { + // Restore the URL to match the current UI, but don't update router state + ignoreNextHistoryUpdate = true; + init.history.go(delta * -1); + // Put the blocker into a blocked state + updateBlocker(blockerKey, { + state: "blocked", + location, + proceed() { + updateBlocker(blockerKey, { + state: "proceeding", + proceed: undefined, + reset: undefined, + location + }); + // Re-do the same POP navigation we just blocked + init.history.go(delta); + }, + reset() { + let blockers = new Map(state.blockers); + blockers.set(blockerKey, IDLE_BLOCKER); + updateState({ + blockers + }); + } + }); + return; + } + return startNavigation(historyAction, location); + }); + if (isBrowser) { + // FIXME: This feels gross. How can we cleanup the lines between + // scrollRestoration/appliedTransitions persistance? + restoreAppliedTransitions(routerWindow, appliedViewTransitions); + let _saveAppliedTransitions = () => persistAppliedTransitions(routerWindow, appliedViewTransitions); + routerWindow.addEventListener("pagehide", _saveAppliedTransitions); + removePageHideEventListener = () => routerWindow.removeEventListener("pagehide", _saveAppliedTransitions); + } + // Kick off initial data load if needed. Use Pop to avoid modifying history + // Note we don't do any handling of lazy here. For SPA's it'll get handled + // in the normal navigation flow. For SSR it's expected that lazy modules are + // resolved prior to router creation since we can't go into a fallbackElement + // UI for SSR'd apps + if (!state.initialized) { + startNavigation(Action.Pop, state.location); + } + return router; + } + // Clean up a router and it's side effects + function dispose() { + if (unlistenHistory) { + unlistenHistory(); + } + if (removePageHideEventListener) { + removePageHideEventListener(); + } + subscribers.clear(); + pendingNavigationController && pendingNavigationController.abort(); + state.fetchers.forEach((_, key) => deleteFetcher(key)); + state.blockers.forEach((_, key) => deleteBlocker(key)); + } + // Subscribe to state updates for the router + function subscribe(fn) { + subscribers.add(fn); + return () => subscribers.delete(fn); + } + // Update our state and notify the calling context of the change + function updateState(newState, viewTransitionOpts) { + state = _extends({}, state, newState); + subscribers.forEach(subscriber => subscriber(state, { + unstable_viewTransitionOpts: viewTransitionOpts + })); + } + // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION + // and setting state.[historyAction/location/matches] to the new route. + // - Location is a required param + // - Navigation will always be set to IDLE_NAVIGATION + // - Can pass any other state in newState + function completeNavigation(location, newState) { + var _location$state, _location$state2; + // Deduce if we're in a loading/actionReload state: + // - We have committed actionData in the store + // - The current navigation was a mutation submission + // - We're past the submitting state and into the loading state + // - The location being loaded is not the result of a redirect + let isActionReload = state.actionData != null && state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && state.navigation.state === "loading" && ((_location$state = location.state) == null ? void 0 : _location$state._isRedirect) !== true; + let actionData; + if (newState.actionData) { + if (Object.keys(newState.actionData).length > 0) { + actionData = newState.actionData; + } else { + // Empty actionData -> clear prior actionData due to an action error + actionData = null; + } + } else if (isActionReload) { + // Keep the current data if we're wrapping up the action reload + actionData = state.actionData; + } else { + // Clear actionData on any other completed navigations + actionData = null; + } + // Always preserve any existing loaderData from re-used routes + let loaderData = newState.loaderData ? mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [], newState.errors) : state.loaderData; + // On a successful navigation we can assume we got through all blockers + // so we can start fresh + let blockers = state.blockers; + if (blockers.size > 0) { + blockers = new Map(blockers); + blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER)); + } + // Always respect the user flag. Otherwise don't reset on mutation + // submission navigations unless they redirect + let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && ((_location$state2 = location.state) == null ? void 0 : _location$state2._isRedirect) !== true; + if (inFlightDataRoutes) { + dataRoutes = inFlightDataRoutes; + inFlightDataRoutes = undefined; + } + if (isUninterruptedRevalidation) ;else if (pendingAction === Action.Pop) ;else if (pendingAction === Action.Push) { + init.history.push(location, location.state); + } else if (pendingAction === Action.Replace) { + init.history.replace(location, location.state); + } + let viewTransitionOpts; + // On POP, enable transitions if they were enabled on the original navigation + if (pendingAction === Action.Pop) { + // Forward takes precedence so they behave like the original navigation + let priorPaths = appliedViewTransitions.get(state.location.pathname); + if (priorPaths && priorPaths.has(location.pathname)) { + viewTransitionOpts = { + currentLocation: state.location, + nextLocation: location + }; + } else if (appliedViewTransitions.has(location.pathname)) { + // If we don't have a previous forward nav, assume we're popping back to + // the new location and enable if that location previously enabled + viewTransitionOpts = { + currentLocation: location, + nextLocation: state.location + }; + } + } else if (pendingViewTransitionEnabled) { + // Store the applied transition on PUSH/REPLACE + let toPaths = appliedViewTransitions.get(state.location.pathname); + if (toPaths) { + toPaths.add(location.pathname); + } else { + toPaths = new Set([location.pathname]); + appliedViewTransitions.set(state.location.pathname, toPaths); + } + viewTransitionOpts = { + currentLocation: state.location, + nextLocation: location + }; + } + updateState(_extends({}, newState, { + actionData, + loaderData, + historyAction: pendingAction, + location, + initialized: true, + navigation: IDLE_NAVIGATION, + revalidation: "idle", + restoreScrollPosition: getSavedScrollPosition(location, newState.matches || state.matches), + preventScrollReset, + blockers + }), viewTransitionOpts); + // Reset stateful navigation vars + pendingAction = Action.Pop; + pendingPreventScrollReset = false; + pendingViewTransitionEnabled = false; + isUninterruptedRevalidation = false; + isRevalidationRequired = false; + cancelledDeferredRoutes = []; + cancelledFetcherLoads = []; + } + // Trigger a navigation event, which can either be a numerical POP or a PUSH + // replace with an optional submission + async function navigate(to, opts) { + if (typeof to === "number") { + init.history.go(to); + return; + } + let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, to, opts == null ? void 0 : opts.fromRouteId, opts == null ? void 0 : opts.relative); + let { + path, + submission, + error + } = normalizeNavigateOptions(future.v7_normalizeFormMethod, false, normalizedPath, opts); + let currentLocation = state.location; + let nextLocation = createLocation(state.location, path, opts && opts.state); + // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded + // URL from window.location, so we need to encode it here so the behavior + // remains the same as POP and non-data-router usages. new URL() does all + // the same encoding we'd get from a history.pushState/window.location read + // without having to touch history + nextLocation = _extends({}, nextLocation, init.history.encodeLocation(nextLocation)); + let userReplace = opts && opts.replace != null ? opts.replace : undefined; + let historyAction = Action.Push; + if (userReplace === true) { + historyAction = Action.Replace; + } else if (userReplace === false) ;else if (submission != null && isMutationMethod(submission.formMethod) && submission.formAction === state.location.pathname + state.location.search) { + // By default on submissions to the current location we REPLACE so that + // users don't have to double-click the back button to get to the prior + // location. If the user redirects to a different location from the + // action/loader this will be ignored and the redirect will be a PUSH + historyAction = Action.Replace; + } + let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : undefined; + let blockerKey = shouldBlockNavigation({ + currentLocation, + nextLocation, + historyAction + }); + if (blockerKey) { + // Put the blocker into a blocked state + updateBlocker(blockerKey, { + state: "blocked", + location: nextLocation, + proceed() { + updateBlocker(blockerKey, { + state: "proceeding", + proceed: undefined, + reset: undefined, + location: nextLocation + }); + // Send the same navigation through + navigate(to, opts); + }, + reset() { + let blockers = new Map(state.blockers); + blockers.set(blockerKey, IDLE_BLOCKER); + updateState({ + blockers + }); + } + }); + return; + } + return await startNavigation(historyAction, nextLocation, { + submission, + // Send through the formData serialization error if we have one so we can + // render at the right error boundary after we match routes + pendingError: error, + preventScrollReset, + replace: opts && opts.replace, + enableViewTransition: opts && opts.unstable_viewTransition + }); + } + // Revalidate all current loaders. If a navigation is in progress or if this + // is interrupted by a navigation, allow this to "succeed" by calling all + // loaders during the next loader round + function revalidate() { + interruptActiveLoads(); + updateState({ + revalidation: "loading" + }); + // If we're currently submitting an action, we don't need to start a new + // navigation, we'll just let the follow up loader execution call all loaders + if (state.navigation.state === "submitting") { + return; + } + // If we're currently in an idle state, start a new navigation for the current + // action/location and mark it as uninterrupted, which will skip the history + // update in completeNavigation + if (state.navigation.state === "idle") { + startNavigation(state.historyAction, state.location, { + startUninterruptedRevalidation: true + }); + return; + } + // Otherwise, if we're currently in a loading state, just start a new + // navigation to the navigation.location but do not trigger an uninterrupted + // revalidation so that history correctly updates once the navigation completes + startNavigation(pendingAction || state.historyAction, state.navigation.location, { + overrideNavigation: state.navigation + }); + } + // Start a navigation to the given action/location. Can optionally provide a + // overrideNavigation which will override the normalLoad in the case of a redirect + // navigation + async function startNavigation(historyAction, location, opts) { + // Abort any in-progress navigations and start a new one. Unset any ongoing + // uninterrupted revalidations unless told otherwise, since we want this + // new navigation to update history normally + pendingNavigationController && pendingNavigationController.abort(); + pendingNavigationController = null; + pendingAction = historyAction; + isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true; + // Save the current scroll position every time we start a new navigation, + // and track whether we should reset scroll on completion + saveScrollPosition(state.location, state.matches); + pendingPreventScrollReset = (opts && opts.preventScrollReset) === true; + pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true; + let routesToUse = inFlightDataRoutes || dataRoutes; + let loadingNavigation = opts && opts.overrideNavigation; + let matches = matchRoutes(routesToUse, location, basename); + // Short circuit with a 404 on the root error boundary if we match nothing + if (!matches) { + let error = getInternalRouterError(404, { + pathname: location.pathname + }); + let { + matches: notFoundMatches, + route + } = getShortCircuitMatches(routesToUse); + // Cancel all pending deferred on 404s since we don't keep any routes + cancelActiveDeferreds(); + completeNavigation(location, { + matches: notFoundMatches, + loaderData: {}, + errors: { + [route.id]: error + } + }); + return; + } + // Short circuit if it's only a hash change and not a revalidation or + // mutation submission. + // + // Ignore on initial page loads because since the initial load will always + // be "same hash". For example, on /page#hash and submit a
+ // which will default to a navigation to /page + if (state.initialized && !isRevalidationRequired && isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) { + completeNavigation(location, { + matches + }); + return; + } + // Create a controller/Request for this navigation + pendingNavigationController = new AbortController(); + let request = createClientSideRequest(init.history, location, pendingNavigationController.signal, opts && opts.submission); + let pendingActionData; + let pendingError; + if (opts && opts.pendingError) { + // If we have a pendingError, it means the user attempted a GET submission + // with binary FormData so assign here and skip to handleLoaders. That + // way we handle calling loaders above the boundary etc. It's not really + // different from an actionError in that sense. + pendingError = { + [findNearestBoundary(matches).route.id]: opts.pendingError + }; + } else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) { + // Call action if we received an action submission + let actionOutput = await handleAction(request, location, opts.submission, matches, { + replace: opts.replace + }); + if (actionOutput.shortCircuited) { + return; + } + pendingActionData = actionOutput.pendingActionData; + pendingError = actionOutput.pendingActionError; + loadingNavigation = getLoadingNavigation(location, opts.submission); + // Create a GET request for the loaders + request = new Request(request.url, { + signal: request.signal + }); + } + // Call loaders + let { + shortCircuited, + loaderData, + errors + } = await handleLoaders(request, location, matches, loadingNavigation, opts && opts.submission, opts && opts.fetcherSubmission, opts && opts.replace, pendingActionData, pendingError); + if (shortCircuited) { + return; + } + // Clean up now that the action/loaders have completed. Don't clean up if + // we short circuited because pendingNavigationController will have already + // been assigned to a new controller for the next navigation + pendingNavigationController = null; + completeNavigation(location, _extends({ + matches + }, pendingActionData ? { + actionData: pendingActionData + } : {}, { + loaderData, + errors + })); + } + // Call the action matched by the leaf route for this navigation and handle + // redirects/errors + async function handleAction(request, location, submission, matches, opts) { + if (opts === void 0) { + opts = {}; + } + interruptActiveLoads(); + // Put us in a submitting state + let navigation = getSubmittingNavigation(location, submission); + updateState({ + navigation + }); + // Call our action and get the result + let result; + let actionMatch = getTargetMatch(matches, location); + if (!actionMatch.route.action && !actionMatch.route.lazy) { + result = { + type: ResultType.error, + error: getInternalRouterError(405, { + method: request.method, + pathname: location.pathname, + routeId: actionMatch.route.id + }) + }; + } else { + result = await callLoaderOrAction("action", request, actionMatch, matches, manifest, mapRouteProperties, basename); + if (request.signal.aborted) { + return { + shortCircuited: true + }; + } + } + if (isRedirectResult(result)) { + let replace; + if (opts && opts.replace != null) { + replace = opts.replace; + } else { + // If the user didn't explicity indicate replace behavior, replace if + // we redirected to the exact same location we're currently at to avoid + // double back-buttons + replace = result.location === state.location.pathname + state.location.search; + } + await startRedirectNavigation(state, result, { + submission, + replace + }); + return { + shortCircuited: true + }; + } + if (isErrorResult(result)) { + // Store off the pending error - we use it to determine which loaders + // to call and will commit it when we complete the navigation + let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id); + // By default, all submissions are REPLACE navigations, but if the + // action threw an error that'll be rendered in an errorElement, we fall + // back to PUSH so that the user can use the back button to get back to + // the pre-submission form location to try again + if ((opts && opts.replace) !== true) { + pendingAction = Action.Push; + } + return { + // Send back an empty object we can use to clear out any prior actionData + pendingActionData: {}, + pendingActionError: { + [boundaryMatch.route.id]: result.error + } + }; + } + if (isDeferredResult(result)) { + throw getInternalRouterError(400, { + type: "defer-action" + }); + } + return { + pendingActionData: { + [actionMatch.route.id]: result.data + } + }; + } + // Call all applicable loaders for the given matches, handling redirects, + // errors, etc. + async function handleLoaders(request, location, matches, overrideNavigation, submission, fetcherSubmission, replace, pendingActionData, pendingError) { + // Figure out the right navigation we want to use for data loading + let loadingNavigation = overrideNavigation || getLoadingNavigation(location, submission); + // If this was a redirect from an action we don't have a "submission" but + // we have it on the loading navigation so use that if available + let activeSubmission = submission || fetcherSubmission || getSubmissionFromNavigation(loadingNavigation); + let routesToUse = inFlightDataRoutes || dataRoutes; + let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, activeSubmission, location, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionData, pendingError); + // Cancel pending deferreds for no-longer-matched routes or routes we're + // about to reload. Note that if this is an action reload we would have + // already cancelled all pending deferreds so this would be a no-op + cancelActiveDeferreds(routeId => !(matches && matches.some(m => m.route.id === routeId)) || matchesToLoad && matchesToLoad.some(m => m.route.id === routeId)); + pendingNavigationLoadId = ++incrementingLoadId; + // Short circuit if we have no loaders to run + if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) { + let updatedFetchers = markFetchRedirectsDone(); + completeNavigation(location, _extends({ + matches, + loaderData: {}, + // Commit pending error if we're short circuiting + errors: pendingError || null + }, pendingActionData ? { + actionData: pendingActionData + } : {}, updatedFetchers ? { + fetchers: new Map(state.fetchers) + } : {})); + return { + shortCircuited: true + }; + } + // If this is an uninterrupted revalidation, we remain in our current idle + // state. If not, we need to switch to our loading state and load data, + // preserving any new action data or existing action data (in the case of + // a revalidation interrupting an actionReload) + if (!isUninterruptedRevalidation) { + revalidatingFetchers.forEach(rf => { + let fetcher = state.fetchers.get(rf.key); + let revalidatingFetcher = getLoadingFetcher(undefined, fetcher ? fetcher.data : undefined); + state.fetchers.set(rf.key, revalidatingFetcher); + }); + let actionData = pendingActionData || state.actionData; + updateState(_extends({ + navigation: loadingNavigation + }, actionData ? Object.keys(actionData).length === 0 ? { + actionData: null + } : { + actionData + } : {}, revalidatingFetchers.length > 0 ? { + fetchers: new Map(state.fetchers) + } : {})); + } + revalidatingFetchers.forEach(rf => { + if (fetchControllers.has(rf.key)) { + abortFetcher(rf.key); + } + if (rf.controller) { + // Fetchers use an independent AbortController so that aborting a fetcher + // (via deleteFetcher) does not abort the triggering navigation that + // triggered the revalidation + fetchControllers.set(rf.key, rf.controller); + } + }); + // Proxy navigation abort through to revalidation fetchers + let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(f => abortFetcher(f.key)); + if (pendingNavigationController) { + pendingNavigationController.signal.addEventListener("abort", abortPendingFetchRevalidations); + } + let { + results, + loaderResults, + fetcherResults + } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, request); + if (request.signal.aborted) { + return { + shortCircuited: true + }; + } + // Clean up _after_ loaders have completed. Don't clean up if we short + // circuited because fetchControllers would have been aborted and + // reassigned to new controllers for the next navigation + if (pendingNavigationController) { + pendingNavigationController.signal.removeEventListener("abort", abortPendingFetchRevalidations); + } + revalidatingFetchers.forEach(rf => fetchControllers.delete(rf.key)); + // If any loaders returned a redirect Response, start a new REPLACE navigation + let redirect = findRedirect(results); + if (redirect) { + if (redirect.idx >= matchesToLoad.length) { + // If this redirect came from a fetcher make sure we mark it in + // fetchRedirectIds so it doesn't get revalidated on the next set of + // loader executions + let fetcherKey = revalidatingFetchers[redirect.idx - matchesToLoad.length].key; + fetchRedirectIds.add(fetcherKey); + } + await startRedirectNavigation(state, redirect.result, { + replace + }); + return { + shortCircuited: true + }; + } + // Process and commit output from loaders + let { + loaderData, + errors + } = processLoaderData(state, matches, matchesToLoad, loaderResults, pendingError, revalidatingFetchers, fetcherResults, activeDeferreds); + // Wire up subscribers to update loaderData as promises settle + activeDeferreds.forEach((deferredData, routeId) => { + deferredData.subscribe(aborted => { + // Note: No need to updateState here since the TrackedPromise on + // loaderData is stable across resolve/reject + // Remove this instance if we were aborted or if promises have settled + if (aborted || deferredData.done) { + activeDeferreds.delete(routeId); + } + }); + }); + let updatedFetchers = markFetchRedirectsDone(); + let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId); + let shouldUpdateFetchers = updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0; + return _extends({ + loaderData, + errors + }, shouldUpdateFetchers ? { + fetchers: new Map(state.fetchers) + } : {}); + } + function getFetcher(key) { + return state.fetchers.get(key) || IDLE_FETCHER; + } + // Trigger a fetcher load/submit for the given fetcher key + function fetch(key, routeId, href, opts) { + if (isServer) { + throw new Error("router.fetch() was called during the server render, but it shouldn't be. " + "You are likely calling a useFetcher() method in the body of your component. " + "Try moving it to a useEffect or a callback."); + } + if (fetchControllers.has(key)) abortFetcher(key); + let routesToUse = inFlightDataRoutes || dataRoutes; + let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, href, routeId, opts == null ? void 0 : opts.relative); + let matches = matchRoutes(routesToUse, normalizedPath, basename); + if (!matches) { + setFetcherError(key, routeId, getInternalRouterError(404, { + pathname: normalizedPath + })); + return; + } + let { + path, + submission, + error + } = normalizeNavigateOptions(future.v7_normalizeFormMethod, true, normalizedPath, opts); + if (error) { + setFetcherError(key, routeId, error); + return; + } + let match = getTargetMatch(matches, path); + pendingPreventScrollReset = (opts && opts.preventScrollReset) === true; + if (submission && isMutationMethod(submission.formMethod)) { + handleFetcherAction(key, routeId, path, match, matches, submission); + return; + } + // Store off the match so we can call it's shouldRevalidate on subsequent + // revalidations + fetchLoadMatches.set(key, { + routeId, + path + }); + handleFetcherLoader(key, routeId, path, match, matches, submission); + } + // Call the action for the matched fetcher.submit(), and then handle redirects, + // errors, and revalidation + async function handleFetcherAction(key, routeId, path, match, requestMatches, submission) { + interruptActiveLoads(); + fetchLoadMatches.delete(key); + if (!match.route.action && !match.route.lazy) { + let error = getInternalRouterError(405, { + method: submission.formMethod, + pathname: path, + routeId: routeId + }); + setFetcherError(key, routeId, error); + return; + } + // Put this fetcher into it's submitting state + let existingFetcher = state.fetchers.get(key); + let fetcher = getSubmittingFetcher(submission, existingFetcher); + state.fetchers.set(key, fetcher); + updateState({ + fetchers: new Map(state.fetchers) + }); + // Call the action for the fetcher + let abortController = new AbortController(); + let fetchRequest = createClientSideRequest(init.history, path, abortController.signal, submission); + fetchControllers.set(key, abortController); + let originatingLoadId = incrementingLoadId; + let actionResult = await callLoaderOrAction("action", fetchRequest, match, requestMatches, manifest, mapRouteProperties, basename); + if (fetchRequest.signal.aborted) { + // We can delete this so long as we weren't aborted by ou our own fetcher + // re-submit which would have put _new_ controller is in fetchControllers + if (fetchControllers.get(key) === abortController) { + fetchControllers.delete(key); + } + return; + } + if (isRedirectResult(actionResult)) { + fetchControllers.delete(key); + if (pendingNavigationLoadId > originatingLoadId) { + // A new navigation was kicked off after our action started, so that + // should take precedence over this redirect navigation. We already + // set isRevalidationRequired so all loaders for the new route should + // fire unless opted out via shouldRevalidate + let doneFetcher = getDoneFetcher(undefined); + state.fetchers.set(key, doneFetcher); + updateState({ + fetchers: new Map(state.fetchers) + }); + return; + } else { + fetchRedirectIds.add(key); + let loadingFetcher = getLoadingFetcher(submission); + state.fetchers.set(key, loadingFetcher); + updateState({ + fetchers: new Map(state.fetchers) + }); + return startRedirectNavigation(state, actionResult, { + fetcherSubmission: submission + }); + } + } + // Process any non-redirect errors thrown + if (isErrorResult(actionResult)) { + setFetcherError(key, routeId, actionResult.error); + return; + } + if (isDeferredResult(actionResult)) { + throw getInternalRouterError(400, { + type: "defer-action" + }); + } + // Start the data load for current matches, or the next location if we're + // in the middle of a navigation + let nextLocation = state.navigation.location || state.location; + let revalidationRequest = createClientSideRequest(init.history, nextLocation, abortController.signal); + let routesToUse = inFlightDataRoutes || dataRoutes; + let matches = state.navigation.state !== "idle" ? matchRoutes(routesToUse, state.navigation.location, basename) : state.matches; + invariant(matches, "Didn't find any matches after fetcher action"); + let loadId = ++incrementingLoadId; + fetchReloadIds.set(key, loadId); + let loadFetcher = getLoadingFetcher(submission, actionResult.data); + state.fetchers.set(key, loadFetcher); + let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, submission, nextLocation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, { + [match.route.id]: actionResult.data + }, undefined // No need to send through errors since we short circuit above + ); + // Put all revalidating fetchers into the loading state, except for the + // current fetcher which we want to keep in it's current loading state which + // contains it's action submission info + action data + revalidatingFetchers.filter(rf => rf.key !== key).forEach(rf => { + let staleKey = rf.key; + let existingFetcher = state.fetchers.get(staleKey); + let revalidatingFetcher = getLoadingFetcher(undefined, existingFetcher ? existingFetcher.data : undefined); + state.fetchers.set(staleKey, revalidatingFetcher); + if (fetchControllers.has(staleKey)) { + abortFetcher(staleKey); + } + if (rf.controller) { + fetchControllers.set(staleKey, rf.controller); + } + }); + updateState({ + fetchers: new Map(state.fetchers) + }); + let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(rf => abortFetcher(rf.key)); + abortController.signal.addEventListener("abort", abortPendingFetchRevalidations); + let { + results, + loaderResults, + fetcherResults + } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, revalidationRequest); + if (abortController.signal.aborted) { + return; + } + abortController.signal.removeEventListener("abort", abortPendingFetchRevalidations); + fetchReloadIds.delete(key); + fetchControllers.delete(key); + revalidatingFetchers.forEach(r => fetchControllers.delete(r.key)); + let redirect = findRedirect(results); + if (redirect) { + if (redirect.idx >= matchesToLoad.length) { + // If this redirect came from a fetcher make sure we mark it in + // fetchRedirectIds so it doesn't get revalidated on the next set of + // loader executions + let fetcherKey = revalidatingFetchers[redirect.idx - matchesToLoad.length].key; + fetchRedirectIds.add(fetcherKey); + } + return startRedirectNavigation(state, redirect.result); + } + // Process and commit output from loaders + let { + loaderData, + errors + } = processLoaderData(state, state.matches, matchesToLoad, loaderResults, undefined, revalidatingFetchers, fetcherResults, activeDeferreds); + // Since we let revalidations complete even if the submitting fetcher was + // deleted, only put it back to idle if it hasn't been deleted + if (state.fetchers.has(key)) { + let doneFetcher = getDoneFetcher(actionResult.data); + state.fetchers.set(key, doneFetcher); + } + let didAbortFetchLoads = abortStaleFetchLoads(loadId); + // If we are currently in a navigation loading state and this fetcher is + // more recent than the navigation, we want the newer data so abort the + // navigation and complete it with the fetcher data + if (state.navigation.state === "loading" && loadId > pendingNavigationLoadId) { + invariant(pendingAction, "Expected pending action"); + pendingNavigationController && pendingNavigationController.abort(); + completeNavigation(state.navigation.location, { + matches, + loaderData, + errors, + fetchers: new Map(state.fetchers) + }); + } else { + // otherwise just update with the fetcher data, preserving any existing + // loaderData for loaders that did not need to reload. We have to + // manually merge here since we aren't going through completeNavigation + updateState(_extends({ + errors, + loaderData: mergeLoaderData(state.loaderData, loaderData, matches, errors) + }, didAbortFetchLoads || revalidatingFetchers.length > 0 ? { + fetchers: new Map(state.fetchers) + } : {})); + isRevalidationRequired = false; + } + } + // Call the matched loader for fetcher.load(), handling redirects, errors, etc. + async function handleFetcherLoader(key, routeId, path, match, matches, submission) { + let existingFetcher = state.fetchers.get(key); + // Put this fetcher into it's loading state + let loadingFetcher = getLoadingFetcher(submission, existingFetcher ? existingFetcher.data : undefined); + state.fetchers.set(key, loadingFetcher); + updateState({ + fetchers: new Map(state.fetchers) + }); + // Call the loader for this fetcher route match + let abortController = new AbortController(); + let fetchRequest = createClientSideRequest(init.history, path, abortController.signal); + fetchControllers.set(key, abortController); + let originatingLoadId = incrementingLoadId; + let result = await callLoaderOrAction("loader", fetchRequest, match, matches, manifest, mapRouteProperties, basename); + // Deferred isn't supported for fetcher loads, await everything and treat it + // as a normal load. resolveDeferredData will return undefined if this + // fetcher gets aborted, so we just leave result untouched and short circuit + // below if that happens + if (isDeferredResult(result)) { + result = (await resolveDeferredData(result, fetchRequest.signal, true)) || result; + } + // We can delete this so long as we weren't aborted by our our own fetcher + // re-load which would have put _new_ controller is in fetchControllers + if (fetchControllers.get(key) === abortController) { + fetchControllers.delete(key); + } + if (fetchRequest.signal.aborted) { + return; + } + // If the loader threw a redirect Response, start a new REPLACE navigation + if (isRedirectResult(result)) { + if (pendingNavigationLoadId > originatingLoadId) { + // A new navigation was kicked off after our loader started, so that + // should take precedence over this redirect navigation + let doneFetcher = getDoneFetcher(undefined); + state.fetchers.set(key, doneFetcher); + updateState({ + fetchers: new Map(state.fetchers) + }); + return; + } else { + fetchRedirectIds.add(key); + await startRedirectNavigation(state, result); + return; + } + } + // Process any non-redirect errors thrown + if (isErrorResult(result)) { + let boundaryMatch = findNearestBoundary(state.matches, routeId); + state.fetchers.delete(key); + // TODO: In remix, this would reset to IDLE_NAVIGATION if it was a catch - + // do we need to behave any differently with our non-redirect errors? + // What if it was a non-redirect Response? + updateState({ + fetchers: new Map(state.fetchers), + errors: { + [boundaryMatch.route.id]: result.error + } + }); + return; + } + invariant(!isDeferredResult(result), "Unhandled fetcher deferred data"); + // Put the fetcher back into an idle state + let doneFetcher = getDoneFetcher(result.data); + state.fetchers.set(key, doneFetcher); + updateState({ + fetchers: new Map(state.fetchers) + }); + } + /** + * Utility function to handle redirects returned from an action or loader. + * Normally, a redirect "replaces" the navigation that triggered it. So, for + * example: + * + * - user is on /a + * - user clicks a link to /b + * - loader for /b redirects to /c + * + * In a non-JS app the browser would track the in-flight navigation to /b and + * then replace it with /c when it encountered the redirect response. In + * the end it would only ever update the URL bar with /c. + * + * In client-side routing using pushState/replaceState, we aim to emulate + * this behavior and we also do not update history until the end of the + * navigation (including processed redirects). This means that we never + * actually touch history until we've processed redirects, so we just use + * the history action from the original navigation (PUSH or REPLACE). + */ + async function startRedirectNavigation(state, redirect, _temp) { + let { + submission, + fetcherSubmission, + replace + } = _temp === void 0 ? {} : _temp; + if (redirect.revalidate) { + isRevalidationRequired = true; + } + let redirectLocation = createLocation(state.location, redirect.location, { + _isRedirect: true + }); + invariant(redirectLocation, "Expected a location on the redirect navigation"); + if (isBrowser) { + let isDocumentReload = false; + if (redirect.reloadDocument) { + // Hard reload if the response contained X-Remix-Reload-Document + isDocumentReload = true; + } else if (ABSOLUTE_URL_REGEX.test(redirect.location)) { + const url = init.history.createURL(redirect.location); + isDocumentReload = + // Hard reload if it's an absolute URL to a new origin + url.origin !== routerWindow.location.origin || + // Hard reload if it's an absolute URL that does not match our basename + stripBasename(url.pathname, basename) == null; + } + if (isDocumentReload) { + if (replace) { + routerWindow.location.replace(redirect.location); + } else { + routerWindow.location.assign(redirect.location); + } + return; + } + } + // There's no need to abort on redirects, since we don't detect the + // redirect until the action/loaders have settled + pendingNavigationController = null; + let redirectHistoryAction = replace === true ? Action.Replace : Action.Push; + // Use the incoming submission if provided, fallback on the active one in + // state.navigation + let { + formMethod, + formAction, + formEncType + } = state.navigation; + if (!submission && !fetcherSubmission && formMethod && formAction && formEncType) { + submission = getSubmissionFromNavigation(state.navigation); + } + // If this was a 307/308 submission we want to preserve the HTTP method and + // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the + // redirected location + let activeSubmission = submission || fetcherSubmission; + if (redirectPreserveMethodStatusCodes.has(redirect.status) && activeSubmission && isMutationMethod(activeSubmission.formMethod)) { + await startNavigation(redirectHistoryAction, redirectLocation, { + submission: _extends({}, activeSubmission, { + formAction: redirect.location + }), + // Preserve this flag across redirects + preventScrollReset: pendingPreventScrollReset + }); + } else { + // If we have a navigation submission, we will preserve it through the + // redirect navigation + let overrideNavigation = getLoadingNavigation(redirectLocation, submission); + await startNavigation(redirectHistoryAction, redirectLocation, { + overrideNavigation, + // Send fetcher submissions through for shouldRevalidate + fetcherSubmission, + // Preserve this flag across redirects + preventScrollReset: pendingPreventScrollReset + }); + } + } + async function callLoadersAndMaybeResolveData(currentMatches, matches, matchesToLoad, fetchersToLoad, request) { + // Call all navigation loaders and revalidating fetcher loaders in parallel, + // then slice off the results into separate arrays so we can handle them + // accordingly + let results = await Promise.all([...matchesToLoad.map(match => callLoaderOrAction("loader", request, match, matches, manifest, mapRouteProperties, basename)), ...fetchersToLoad.map(f => { + if (f.matches && f.match && f.controller) { + return callLoaderOrAction("loader", createClientSideRequest(init.history, f.path, f.controller.signal), f.match, f.matches, manifest, mapRouteProperties, basename); + } else { + let error = { + type: ResultType.error, + error: getInternalRouterError(404, { + pathname: f.path + }) + }; + return error; + } + })]); + let loaderResults = results.slice(0, matchesToLoad.length); + let fetcherResults = results.slice(matchesToLoad.length); + await Promise.all([resolveDeferredResults(currentMatches, matchesToLoad, loaderResults, loaderResults.map(() => request.signal), false, state.loaderData), resolveDeferredResults(currentMatches, fetchersToLoad.map(f => f.match), fetcherResults, fetchersToLoad.map(f => f.controller ? f.controller.signal : null), true)]); + return { + results, + loaderResults, + fetcherResults + }; + } + function interruptActiveLoads() { + // Every interruption triggers a revalidation + isRevalidationRequired = true; + // Cancel pending route-level deferreds and mark cancelled routes for + // revalidation + cancelledDeferredRoutes.push(...cancelActiveDeferreds()); + // Abort in-flight fetcher loads + fetchLoadMatches.forEach((_, key) => { + if (fetchControllers.has(key)) { + cancelledFetcherLoads.push(key); + abortFetcher(key); + } + }); + } + function setFetcherError(key, routeId, error) { + let boundaryMatch = findNearestBoundary(state.matches, routeId); + deleteFetcher(key); + updateState({ + errors: { + [boundaryMatch.route.id]: error + }, + fetchers: new Map(state.fetchers) + }); + } + function deleteFetcher(key) { + let fetcher = state.fetchers.get(key); + // Don't abort the controller if this is a deletion of a fetcher.submit() + // in it's loading phase since - we don't want to abort the corresponding + // revalidation and want them to complete and land + if (fetchControllers.has(key) && !(fetcher && fetcher.state === "loading" && fetchReloadIds.has(key))) { + abortFetcher(key); + } + fetchLoadMatches.delete(key); + fetchReloadIds.delete(key); + fetchRedirectIds.delete(key); + state.fetchers.delete(key); + } + function abortFetcher(key) { + let controller = fetchControllers.get(key); + invariant(controller, "Expected fetch controller: " + key); + controller.abort(); + fetchControllers.delete(key); + } + function markFetchersDone(keys) { + for (let key of keys) { + let fetcher = getFetcher(key); + let doneFetcher = getDoneFetcher(fetcher.data); + state.fetchers.set(key, doneFetcher); + } + } + function markFetchRedirectsDone() { + let doneKeys = []; + let updatedFetchers = false; + for (let key of fetchRedirectIds) { + let fetcher = state.fetchers.get(key); + invariant(fetcher, "Expected fetcher: " + key); + if (fetcher.state === "loading") { + fetchRedirectIds.delete(key); + doneKeys.push(key); + updatedFetchers = true; + } + } + markFetchersDone(doneKeys); + return updatedFetchers; + } + function abortStaleFetchLoads(landedId) { + let yeetedKeys = []; + for (let [key, id] of fetchReloadIds) { + if (id < landedId) { + let fetcher = state.fetchers.get(key); + invariant(fetcher, "Expected fetcher: " + key); + if (fetcher.state === "loading") { + abortFetcher(key); + fetchReloadIds.delete(key); + yeetedKeys.push(key); + } + } + } + markFetchersDone(yeetedKeys); + return yeetedKeys.length > 0; + } + function getBlocker(key, fn) { + let blocker = state.blockers.get(key) || IDLE_BLOCKER; + if (blockerFunctions.get(key) !== fn) { + blockerFunctions.set(key, fn); + } + return blocker; + } + function deleteBlocker(key) { + state.blockers.delete(key); + blockerFunctions.delete(key); + } + // Utility function to update blockers, ensuring valid state transitions + function updateBlocker(key, newBlocker) { + let blocker = state.blockers.get(key) || IDLE_BLOCKER; + // Poor mans state machine :) + // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM + invariant(blocker.state === "unblocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "proceeding" || blocker.state === "blocked" && newBlocker.state === "unblocked" || blocker.state === "proceeding" && newBlocker.state === "unblocked", "Invalid blocker state transition: " + blocker.state + " -> " + newBlocker.state); + let blockers = new Map(state.blockers); + blockers.set(key, newBlocker); + updateState({ + blockers + }); + } + function shouldBlockNavigation(_ref2) { + let { + currentLocation, + nextLocation, + historyAction + } = _ref2; + if (blockerFunctions.size === 0) { + return; + } + // We ony support a single active blocker at the moment since we don't have + // any compelling use cases for multi-blocker yet + if (blockerFunctions.size > 1) { + warning(false, "A router only supports one blocker at a time"); + } + let entries = Array.from(blockerFunctions.entries()); + let [blockerKey, blockerFunction] = entries[entries.length - 1]; + let blocker = state.blockers.get(blockerKey); + if (blocker && blocker.state === "proceeding") { + // If the blocker is currently proceeding, we don't need to re-check + // it and can let this navigation continue + return; + } + // At this point, we know we're unblocked/blocked so we need to check the + // user-provided blocker function + if (blockerFunction({ + currentLocation, + nextLocation, + historyAction + })) { + return blockerKey; + } + } + function cancelActiveDeferreds(predicate) { + let cancelledRouteIds = []; + activeDeferreds.forEach((dfd, routeId) => { + if (!predicate || predicate(routeId)) { + // Cancel the deferred - but do not remove from activeDeferreds here - + // we rely on the subscribers to do that so our tests can assert proper + // cleanup via _internalActiveDeferreds + dfd.cancel(); + cancelledRouteIds.push(routeId); + activeDeferreds.delete(routeId); + } + }); + return cancelledRouteIds; + } + // Opt in to capturing and reporting scroll positions during navigations, + // used by the component + function enableScrollRestoration(positions, getPosition, getKey) { + savedScrollPositions = positions; + getScrollPosition = getPosition; + getScrollRestorationKey = getKey || null; + // Perform initial hydration scroll restoration, since we miss the boat on + // the initial updateState() because we've not yet rendered + // and therefore have no savedScrollPositions available + if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) { + initialScrollRestored = true; + let y = getSavedScrollPosition(state.location, state.matches); + if (y != null) { + updateState({ + restoreScrollPosition: y + }); + } + } + return () => { + savedScrollPositions = null; + getScrollPosition = null; + getScrollRestorationKey = null; + }; + } + function getScrollKey(location, matches) { + if (getScrollRestorationKey) { + let key = getScrollRestorationKey(location, matches.map(m => convertRouteMatchToUiMatch(m, state.loaderData))); + return key || location.key; + } + return location.key; + } + function saveScrollPosition(location, matches) { + if (savedScrollPositions && getScrollPosition) { + let key = getScrollKey(location, matches); + savedScrollPositions[key] = getScrollPosition(); + } + } + function getSavedScrollPosition(location, matches) { + if (savedScrollPositions) { + let key = getScrollKey(location, matches); + let y = savedScrollPositions[key]; + if (typeof y === "number") { + return y; + } + } + return null; + } + function _internalSetRoutes(newRoutes) { + manifest = {}; + inFlightDataRoutes = convertRoutesToDataRoutes(newRoutes, mapRouteProperties, undefined, manifest); + } + router = { + get basename() { + return basename; + }, + get state() { + return state; + }, + get routes() { + return dataRoutes; + }, + get window() { + return routerWindow; + }, + initialize, + subscribe, + enableScrollRestoration, + navigate, + fetch, + revalidate, + // Passthrough to history-aware createHref used by useHref so we get proper + // hash-aware URLs in DOM paths + createHref: to => init.history.createHref(to), + encodeLocation: to => init.history.encodeLocation(to), + getFetcher, + deleteFetcher, + dispose, + getBlocker, + deleteBlocker, + _internalFetchControllers: fetchControllers, + _internalActiveDeferreds: activeDeferreds, + // TODO: Remove setRoutes, it's temporary to avoid dealing with + // updating the tree while validating the update algorithm. + _internalSetRoutes + }; + return router; +} +//#endregion +//////////////////////////////////////////////////////////////////////////////// +//#region createStaticHandler +//////////////////////////////////////////////////////////////////////////////// +const UNSAFE_DEFERRED_SYMBOL = Symbol("deferred"); +function createStaticHandler(routes, opts) { + invariant(routes.length > 0, "You must provide a non-empty routes array to createStaticHandler"); + let manifest = {}; + let basename = (opts ? opts.basename : null) || "/"; + let mapRouteProperties; + if (opts != null && opts.mapRouteProperties) { + mapRouteProperties = opts.mapRouteProperties; + } else if (opts != null && opts.detectErrorBoundary) { + // If they are still using the deprecated version, wrap it with the new API + let detectErrorBoundary = opts.detectErrorBoundary; + mapRouteProperties = route => ({ + hasErrorBoundary: detectErrorBoundary(route) + }); + } else { + mapRouteProperties = defaultMapRouteProperties; + } + let dataRoutes = convertRoutesToDataRoutes(routes, mapRouteProperties, undefined, manifest); + /** + * The query() method is intended for document requests, in which we want to + * call an optional action and potentially multiple loaders for all nested + * routes. It returns a StaticHandlerContext object, which is very similar + * to the router state (location, loaderData, actionData, errors, etc.) and + * also adds SSR-specific information such as the statusCode and headers + * from action/loaders Responses. + * + * It _should_ never throw and should report all errors through the + * returned context.errors object, properly associating errors to their error + * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be + * used to emulate React error boundaries during SSr by performing a second + * pass only down to the boundaryId. + * + * The one exception where we do not return a StaticHandlerContext is when a + * redirect response is returned or thrown from any action/loader. We + * propagate that out and return the raw Response so the HTTP server can + * return it directly. + */ + async function query(request, _temp2) { + let { + requestContext + } = _temp2 === void 0 ? {} : _temp2; + let url = new URL(request.url); + let method = request.method; + let location = createLocation("", createPath(url), null, "default"); + let matches = matchRoutes(dataRoutes, location, basename); + // SSR supports HEAD requests while SPA doesn't + if (!isValidMethod(method) && method !== "HEAD") { + let error = getInternalRouterError(405, { + method + }); + let { + matches: methodNotAllowedMatches, + route + } = getShortCircuitMatches(dataRoutes); + return { + basename, + location, + matches: methodNotAllowedMatches, + loaderData: {}, + actionData: null, + errors: { + [route.id]: error + }, + statusCode: error.status, + loaderHeaders: {}, + actionHeaders: {}, + activeDeferreds: null + }; + } else if (!matches) { + let error = getInternalRouterError(404, { + pathname: location.pathname + }); + let { + matches: notFoundMatches, + route + } = getShortCircuitMatches(dataRoutes); + return { + basename, + location, + matches: notFoundMatches, + loaderData: {}, + actionData: null, + errors: { + [route.id]: error + }, + statusCode: error.status, + loaderHeaders: {}, + actionHeaders: {}, + activeDeferreds: null + }; + } + let result = await queryImpl(request, location, matches, requestContext); + if (isResponse(result)) { + return result; + } + // When returning StaticHandlerContext, we patch back in the location here + // since we need it for React Context. But this helps keep our submit and + // loadRouteData operating on a Request instead of a Location + return _extends({ + location, + basename + }, result); + } + /** + * The queryRoute() method is intended for targeted route requests, either + * for fetch ?_data requests or resource route requests. In this case, we + * are only ever calling a single action or loader, and we are returning the + * returned value directly. In most cases, this will be a Response returned + * from the action/loader, but it may be a primitive or other value as well - + * and in such cases the calling context should handle that accordingly. + * + * We do respect the throw/return differentiation, so if an action/loader + * throws, then this method will throw the value. This is important so we + * can do proper boundary identification in Remix where a thrown Response + * must go to the Catch Boundary but a returned Response is happy-path. + * + * One thing to note is that any Router-initiated Errors that make sense + * to associate with a status code will be thrown as an ErrorResponse + * instance which include the raw Error, such that the calling context can + * serialize the error as they see fit while including the proper response + * code. Examples here are 404 and 405 errors that occur prior to reaching + * any user-defined loaders. + */ + async function queryRoute(request, _temp3) { + let { + routeId, + requestContext + } = _temp3 === void 0 ? {} : _temp3; + let url = new URL(request.url); + let method = request.method; + let location = createLocation("", createPath(url), null, "default"); + let matches = matchRoutes(dataRoutes, location, basename); + // SSR supports HEAD requests while SPA doesn't + if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") { + throw getInternalRouterError(405, { + method + }); + } else if (!matches) { + throw getInternalRouterError(404, { + pathname: location.pathname + }); + } + let match = routeId ? matches.find(m => m.route.id === routeId) : getTargetMatch(matches, location); + if (routeId && !match) { + throw getInternalRouterError(403, { + pathname: location.pathname, + routeId + }); + } else if (!match) { + // This should never hit I don't think? + throw getInternalRouterError(404, { + pathname: location.pathname + }); + } + let result = await queryImpl(request, location, matches, requestContext, match); + if (isResponse(result)) { + return result; + } + let error = result.errors ? Object.values(result.errors)[0] : undefined; + if (error !== undefined) { + // If we got back result.errors, that means the loader/action threw + // _something_ that wasn't a Response, but it's not guaranteed/required + // to be an `instanceof Error` either, so we have to use throw here to + // preserve the "error" state outside of queryImpl. + throw error; + } + // Pick off the right state value to return + if (result.actionData) { + return Object.values(result.actionData)[0]; + } + if (result.loaderData) { + var _result$activeDeferre; + let data = Object.values(result.loaderData)[0]; + if ((_result$activeDeferre = result.activeDeferreds) != null && _result$activeDeferre[match.route.id]) { + data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id]; + } + return data; + } + return undefined; + } + async function queryImpl(request, location, matches, requestContext, routeMatch) { + invariant(request.signal, "query()/queryRoute() requests must contain an AbortController signal"); + try { + if (isMutationMethod(request.method.toLowerCase())) { + let result = await submit(request, matches, routeMatch || getTargetMatch(matches, location), requestContext, routeMatch != null); + return result; + } + let result = await loadRouteData(request, matches, requestContext, routeMatch); + return isResponse(result) ? result : _extends({}, result, { + actionData: null, + actionHeaders: {} + }); + } catch (e) { + // If the user threw/returned a Response in callLoaderOrAction, we throw + // it to bail out and then return or throw here based on whether the user + // returned or threw + if (isQueryRouteResponse(e)) { + if (e.type === ResultType.error) { + throw e.response; + } + return e.response; + } + // Redirects are always returned since they don't propagate to catch + // boundaries + if (isRedirectResponse(e)) { + return e; + } + throw e; + } + } + async function submit(request, matches, actionMatch, requestContext, isRouteRequest) { + let result; + if (!actionMatch.route.action && !actionMatch.route.lazy) { + let error = getInternalRouterError(405, { + method: request.method, + pathname: new URL(request.url).pathname, + routeId: actionMatch.route.id + }); + if (isRouteRequest) { + throw error; + } + result = { + type: ResultType.error, + error + }; + } else { + result = await callLoaderOrAction("action", request, actionMatch, matches, manifest, mapRouteProperties, basename, { + isStaticRequest: true, + isRouteRequest, + requestContext + }); + if (request.signal.aborted) { + let method = isRouteRequest ? "queryRoute" : "query"; + throw new Error(method + "() call aborted: " + request.method + " " + request.url); + } + } + if (isRedirectResult(result)) { + // Uhhhh - this should never happen, we should always throw these from + // callLoaderOrAction, but the type narrowing here keeps TS happy and we + // can get back on the "throw all redirect responses" train here should + // this ever happen :/ + throw new Response(null, { + status: result.status, + headers: { + Location: result.location + } + }); + } + if (isDeferredResult(result)) { + let error = getInternalRouterError(400, { + type: "defer-action" + }); + if (isRouteRequest) { + throw error; + } + result = { + type: ResultType.error, + error + }; + } + if (isRouteRequest) { + // Note: This should only be non-Response values if we get here, since + // isRouteRequest should throw any Response received in callLoaderOrAction + if (isErrorResult(result)) { + throw result.error; + } + return { + matches: [actionMatch], + loaderData: {}, + actionData: { + [actionMatch.route.id]: result.data + }, + errors: null, + // Note: statusCode + headers are unused here since queryRoute will + // return the raw Response or value + statusCode: 200, + loaderHeaders: {}, + actionHeaders: {}, + activeDeferreds: null + }; + } + if (isErrorResult(result)) { + // Store off the pending error - we use it to determine which loaders + // to call and will commit it when we complete the navigation + let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id); + let context = await loadRouteData(request, matches, requestContext, undefined, { + [boundaryMatch.route.id]: result.error + }); + // action status codes take precedence over loader status codes + return _extends({}, context, { + statusCode: isRouteErrorResponse(result.error) ? result.error.status : 500, + actionData: null, + actionHeaders: _extends({}, result.headers ? { + [actionMatch.route.id]: result.headers + } : {}) + }); + } + // Create a GET request for the loaders + let loaderRequest = new Request(request.url, { + headers: request.headers, + redirect: request.redirect, + signal: request.signal + }); + let context = await loadRouteData(loaderRequest, matches, requestContext); + return _extends({}, context, result.statusCode ? { + statusCode: result.statusCode + } : {}, { + actionData: { + [actionMatch.route.id]: result.data + }, + actionHeaders: _extends({}, result.headers ? { + [actionMatch.route.id]: result.headers + } : {}) + }); + } + async function loadRouteData(request, matches, requestContext, routeMatch, pendingActionError) { + let isRouteRequest = routeMatch != null; + // Short circuit if we have no loaders to run (queryRoute()) + if (isRouteRequest && !(routeMatch != null && routeMatch.route.loader) && !(routeMatch != null && routeMatch.route.lazy)) { + throw getInternalRouterError(400, { + method: request.method, + pathname: new URL(request.url).pathname, + routeId: routeMatch == null ? void 0 : routeMatch.route.id + }); + } + let requestMatches = routeMatch ? [routeMatch] : getLoaderMatchesUntilBoundary(matches, Object.keys(pendingActionError || {})[0]); + let matchesToLoad = requestMatches.filter(m => m.route.loader || m.route.lazy); + // Short circuit if we have no loaders to run (query()) + if (matchesToLoad.length === 0) { + return { + matches, + // Add a null for all matched routes for proper revalidation on the client + loaderData: matches.reduce((acc, m) => Object.assign(acc, { + [m.route.id]: null + }), {}), + errors: pendingActionError || null, + statusCode: 200, + loaderHeaders: {}, + activeDeferreds: null + }; + } + let results = await Promise.all([...matchesToLoad.map(match => callLoaderOrAction("loader", request, match, matches, manifest, mapRouteProperties, basename, { + isStaticRequest: true, + isRouteRequest, + requestContext + }))]); + if (request.signal.aborted) { + let method = isRouteRequest ? "queryRoute" : "query"; + throw new Error(method + "() call aborted: " + request.method + " " + request.url); + } + // Process and commit output from loaders + let activeDeferreds = new Map(); + let context = processRouteLoaderData(matches, matchesToLoad, results, pendingActionError, activeDeferreds); + // Add a null for any non-loader matches for proper revalidation on the client + let executedLoaders = new Set(matchesToLoad.map(match => match.route.id)); + matches.forEach(match => { + if (!executedLoaders.has(match.route.id)) { + context.loaderData[match.route.id] = null; + } + }); + return _extends({}, context, { + matches, + activeDeferreds: activeDeferreds.size > 0 ? Object.fromEntries(activeDeferreds.entries()) : null + }); + } + return { + dataRoutes, + query, + queryRoute + }; +} +//#endregion +//////////////////////////////////////////////////////////////////////////////// +//#region Helpers +//////////////////////////////////////////////////////////////////////////////// +/** + * Given an existing StaticHandlerContext and an error thrown at render time, + * provide an updated StaticHandlerContext suitable for a second SSR render + */ +function getStaticContextFromError(routes, context, error) { + let newContext = _extends({}, context, { + statusCode: 500, + errors: { + [context._deepestRenderedBoundaryId || routes[0].id]: error + } + }); + return newContext; +} +function isSubmissionNavigation(opts) { + return opts != null && ("formData" in opts && opts.formData != null || "body" in opts && opts.body !== undefined); +} +function normalizeTo(location, matches, basename, prependBasename, to, fromRouteId, relative) { + let contextualMatches; + let activeRouteMatch; + if (fromRouteId != null && relative !== "path") { + // Grab matches up to the calling route so our route-relative logic is + // relative to the correct source route. When using relative:path, + // fromRouteId is ignored since that is always relative to the current + // location path + contextualMatches = []; + for (let match of matches) { + contextualMatches.push(match); + if (match.route.id === fromRouteId) { + activeRouteMatch = match; + break; + } + } + } else { + contextualMatches = matches; + activeRouteMatch = matches[matches.length - 1]; + } + // Resolve the relative path + let path = resolveTo(to ? to : ".", getPathContributingMatches(contextualMatches).map(m => m.pathnameBase), stripBasename(location.pathname, basename) || location.pathname, relative === "path"); + // When `to` is not specified we inherit search/hash from the current + // location, unlike when to="." and we just inherit the path. + // See https://github.com/remix-run/remix/issues/927 + if (to == null) { + path.search = location.search; + path.hash = location.hash; + } + // Add an ?index param for matched index routes if we don't already have one + if ((to == null || to === "" || to === ".") && activeRouteMatch && activeRouteMatch.route.index && !hasNakedIndexQuery(path.search)) { + path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index"; + } + // If we're operating within a basename, prepend it to the pathname. If + // this is a root navigation, then just use the raw basename which allows + // the basename to have full control over the presence of a trailing slash + // on root actions + if (prependBasename && basename !== "/") { + path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]); + } + return createPath(path); +} +// Normalize navigation options by converting formMethod=GET formData objects to +// URLSearchParams so they behave identically to links with query params +function normalizeNavigateOptions(normalizeFormMethod, isFetcher, path, opts) { + // Return location verbatim on non-submission navigations + if (!opts || !isSubmissionNavigation(opts)) { + return { + path + }; + } + if (opts.formMethod && !isValidMethod(opts.formMethod)) { + return { + path, + error: getInternalRouterError(405, { + method: opts.formMethod + }) + }; + } + let getInvalidBodyError = () => ({ + path, + error: getInternalRouterError(400, { + type: "invalid-body" + }) + }); + // Create a Submission on non-GET navigations + let rawFormMethod = opts.formMethod || "get"; + let formMethod = normalizeFormMethod ? rawFormMethod.toUpperCase() : rawFormMethod.toLowerCase(); + let formAction = stripHashFromPath(path); + if (opts.body !== undefined) { + if (opts.formEncType === "text/plain") { + // text only support POST/PUT/PATCH/DELETE submissions + if (!isMutationMethod(formMethod)) { + return getInvalidBodyError(); + } + let text = typeof opts.body === "string" ? opts.body : opts.body instanceof FormData || opts.body instanceof URLSearchParams ? + // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data + Array.from(opts.body.entries()).reduce((acc, _ref3) => { + let [name, value] = _ref3; + return "" + acc + name + "=" + value + "\n"; + }, "") : String(opts.body); + return { + path, + submission: { + formMethod, + formAction, + formEncType: opts.formEncType, + formData: undefined, + json: undefined, + text + } + }; + } else if (opts.formEncType === "application/json") { + // json only supports POST/PUT/PATCH/DELETE submissions + if (!isMutationMethod(formMethod)) { + return getInvalidBodyError(); + } + try { + let json = typeof opts.body === "string" ? JSON.parse(opts.body) : opts.body; + return { + path, + submission: { + formMethod, + formAction, + formEncType: opts.formEncType, + formData: undefined, + json, + text: undefined + } + }; + } catch (e) { + return getInvalidBodyError(); + } + } + } + invariant(typeof FormData === "function", "FormData is not available in this environment"); + let searchParams; + let formData; + if (opts.formData) { + searchParams = convertFormDataToSearchParams(opts.formData); + formData = opts.formData; + } else if (opts.body instanceof FormData) { + searchParams = convertFormDataToSearchParams(opts.body); + formData = opts.body; + } else if (opts.body instanceof URLSearchParams) { + searchParams = opts.body; + formData = convertSearchParamsToFormData(searchParams); + } else if (opts.body == null) { + searchParams = new URLSearchParams(); + formData = new FormData(); + } else { + try { + searchParams = new URLSearchParams(opts.body); + formData = convertSearchParamsToFormData(searchParams); + } catch (e) { + return getInvalidBodyError(); + } + } + let submission = { + formMethod, + formAction, + formEncType: opts && opts.formEncType || "application/x-www-form-urlencoded", + formData, + json: undefined, + text: undefined + }; + if (isMutationMethod(submission.formMethod)) { + return { + path, + submission + }; + } + // Flatten submission onto URLSearchParams for GET submissions + let parsedPath = parsePath(path); + // On GET navigation submissions we can drop the ?index param from the + // resulting location since all loaders will run. But fetcher GET submissions + // only run a single loader so we need to preserve any incoming ?index params + if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) { + searchParams.append("index", ""); + } + parsedPath.search = "?" + searchParams; + return { + path: createPath(parsedPath), + submission + }; +} +// Filter out all routes below any caught error as they aren't going to +// render so we don't need to load them +function getLoaderMatchesUntilBoundary(matches, boundaryId) { + let boundaryMatches = matches; + if (boundaryId) { + let index = matches.findIndex(m => m.route.id === boundaryId); + if (index >= 0) { + boundaryMatches = matches.slice(0, index); + } + } + return boundaryMatches; +} +function getMatchesToLoad(history, state, matches, submission, location, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionData, pendingError) { + let actionResult = pendingError ? Object.values(pendingError)[0] : pendingActionData ? Object.values(pendingActionData)[0] : undefined; + let currentUrl = history.createURL(state.location); + let nextUrl = history.createURL(location); + // Pick navigation matches that are net-new or qualify for revalidation + let boundaryId = pendingError ? Object.keys(pendingError)[0] : undefined; + let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId); + let navigationMatches = boundaryMatches.filter((match, index) => { + if (match.route.lazy) { + // We haven't loaded this route yet so we don't know if it's got a loader! + return true; + } + if (match.route.loader == null) { + return false; + } + // Always call the loader on new route instances and pending defer cancellations + if (isNewLoader(state.loaderData, state.matches[index], match) || cancelledDeferredRoutes.some(id => id === match.route.id)) { + return true; + } + // This is the default implementation for when we revalidate. If the route + // provides it's own implementation, then we give them full control but + // provide this value so they can leverage it if needed after they check + // their own specific use cases + let currentRouteMatch = state.matches[index]; + let nextRouteMatch = match; + return shouldRevalidateLoader(match, _extends({ + currentUrl, + currentParams: currentRouteMatch.params, + nextUrl, + nextParams: nextRouteMatch.params + }, submission, { + actionResult, + defaultShouldRevalidate: + // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate + isRevalidationRequired || + // Clicked the same link, resubmitted a GET form + currentUrl.pathname + currentUrl.search === nextUrl.pathname + nextUrl.search || + // Search params affect all loaders + currentUrl.search !== nextUrl.search || isNewRouteInstance(currentRouteMatch, nextRouteMatch) + })); + }); + // Pick fetcher.loads that need to be revalidated + let revalidatingFetchers = []; + fetchLoadMatches.forEach((f, key) => { + // Don't revalidate if fetcher won't be present in the subsequent render + if (!matches.some(m => m.route.id === f.routeId)) { + return; + } + let fetcherMatches = matchRoutes(routesToUse, f.path, basename); + // If the fetcher path no longer matches, push it in with null matches so + // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is + // currently only a use-case for Remix HMR where the route tree can change + // at runtime and remove a route previously loaded via a fetcher + if (!fetcherMatches) { + revalidatingFetchers.push({ + key, + routeId: f.routeId, + path: f.path, + matches: null, + match: null, + controller: null + }); + return; + } + // Revalidating fetchers are decoupled from the route matches since they + // load from a static href. They revalidate based on explicit revalidation + // (submission, useRevalidator, or X-Remix-Revalidate) + let fetcher = state.fetchers.get(key); + let fetcherMatch = getTargetMatch(fetcherMatches, f.path); + let shouldRevalidate = false; + if (fetchRedirectIds.has(key)) { + // Never trigger a revalidation of an actively redirecting fetcher + shouldRevalidate = false; + } else if (cancelledFetcherLoads.includes(key)) { + // Always revalidate if the fetcher was cancelled + shouldRevalidate = true; + } else if (fetcher && fetcher.state !== "idle" && fetcher.data === undefined) { + // If the fetcher hasn't ever completed loading yet, then this isn't a + // revalidation, it would just be a brand new load if an explicit + // revalidation is required + shouldRevalidate = isRevalidationRequired; + } else { + // Otherwise fall back on any user-defined shouldRevalidate, defaulting + // to explicit revalidations only + shouldRevalidate = shouldRevalidateLoader(fetcherMatch, _extends({ + currentUrl, + currentParams: state.matches[state.matches.length - 1].params, + nextUrl, + nextParams: matches[matches.length - 1].params + }, submission, { + actionResult, + defaultShouldRevalidate: isRevalidationRequired + })); + } + if (shouldRevalidate) { + revalidatingFetchers.push({ + key, + routeId: f.routeId, + path: f.path, + matches: fetcherMatches, + match: fetcherMatch, + controller: new AbortController() + }); + } + }); + return [navigationMatches, revalidatingFetchers]; +} +function isNewLoader(currentLoaderData, currentMatch, match) { + let isNew = + // [a] -> [a, b] + !currentMatch || + // [a, b] -> [a, c] + match.route.id !== currentMatch.route.id; + // Handle the case that we don't have data for a re-used route, potentially + // from a prior error or from a cancelled pending deferred + let isMissingData = currentLoaderData[match.route.id] === undefined; + // Always load if this is a net-new route or we don't yet have data + return isNew || isMissingData; +} +function isNewRouteInstance(currentMatch, match) { + let currentPath = currentMatch.route.path; + return ( + // param change for this match, /users/123 -> /users/456 + currentMatch.pathname !== match.pathname || + // splat param changed, which is not present in match.path + // e.g. /files/images/avatar.jpg -> files/finances.xls + currentPath != null && currentPath.endsWith("*") && currentMatch.params["*"] !== match.params["*"] + ); +} +function shouldRevalidateLoader(loaderMatch, arg) { + if (loaderMatch.route.shouldRevalidate) { + let routeChoice = loaderMatch.route.shouldRevalidate(arg); + if (typeof routeChoice === "boolean") { + return routeChoice; + } + } + return arg.defaultShouldRevalidate; +} +/** + * Execute route.lazy() methods to lazily load route modules (loader, action, + * shouldRevalidate) and update the routeManifest in place which shares objects + * with dataRoutes so those get updated as well. + */ +async function loadLazyRouteModule(route, mapRouteProperties, manifest) { + if (!route.lazy) { + return; + } + let lazyRoute = await route.lazy(); + // If the lazy route function was executed and removed by another parallel + // call then we can return - first lazy() to finish wins because the return + // value of lazy is expected to be static + if (!route.lazy) { + return; + } + let routeToUpdate = manifest[route.id]; + invariant(routeToUpdate, "No route found in manifest"); + // Update the route in place. This should be safe because there's no way + // we could yet be sitting on this route as we can't get there without + // resolving lazy() first. + // + // This is different than the HMR "update" use-case where we may actively be + // on the route being updated. The main concern boils down to "does this + // mutation affect any ongoing navigations or any current state.matches + // values?". If not, it should be safe to update in place. + let routeUpdates = {}; + for (let lazyRouteProperty in lazyRoute) { + let staticRouteValue = routeToUpdate[lazyRouteProperty]; + let isPropertyStaticallyDefined = staticRouteValue !== undefined && + // This property isn't static since it should always be updated based + // on the route updates + lazyRouteProperty !== "hasErrorBoundary"; + warning(!isPropertyStaticallyDefined, "Route \"" + routeToUpdate.id + "\" has a static property \"" + lazyRouteProperty + "\" " + "defined but its lazy function is also returning a value for this property. " + ("The lazy route property \"" + lazyRouteProperty + "\" will be ignored.")); + if (!isPropertyStaticallyDefined && !immutableRouteKeys.has(lazyRouteProperty)) { + routeUpdates[lazyRouteProperty] = lazyRoute[lazyRouteProperty]; + } + } + // Mutate the route with the provided updates. Do this first so we pass + // the updated version to mapRouteProperties + Object.assign(routeToUpdate, routeUpdates); + // Mutate the `hasErrorBoundary` property on the route based on the route + // updates and remove the `lazy` function so we don't resolve the lazy + // route again. + Object.assign(routeToUpdate, _extends({}, mapRouteProperties(routeToUpdate), { + lazy: undefined + })); +} +async function callLoaderOrAction(type, request, match, matches, manifest, mapRouteProperties, basename, opts) { + if (opts === void 0) { + opts = {}; + } + let resultType; + let result; + let onReject; + let runHandler = handler => { + // Setup a promise we can race against so that abort signals short circuit + let reject; + let abortPromise = new Promise((_, r) => reject = r); + onReject = () => reject(); + request.signal.addEventListener("abort", onReject); + return Promise.race([handler({ + request, + params: match.params, + context: opts.requestContext + }), abortPromise]); + }; + try { + let handler = match.route[type]; + if (match.route.lazy) { + if (handler) { + // Run statically defined handler in parallel with lazy() + let handlerError; + let values = await Promise.all([ + // If the handler throws, don't let it immediately bubble out, + // since we need to let the lazy() execution finish so we know if this + // route has a boundary that can handle the error + runHandler(handler).catch(e => { + handlerError = e; + }), loadLazyRouteModule(match.route, mapRouteProperties, manifest)]); + if (handlerError) { + throw handlerError; + } + result = values[0]; + } else { + // Load lazy route module, then run any returned handler + await loadLazyRouteModule(match.route, mapRouteProperties, manifest); + handler = match.route[type]; + if (handler) { + // Handler still run even if we got interrupted to maintain consistency + // with un-abortable behavior of handler execution on non-lazy or + // previously-lazy-loaded routes + result = await runHandler(handler); + } else if (type === "action") { + let url = new URL(request.url); + let pathname = url.pathname + url.search; + throw getInternalRouterError(405, { + method: request.method, + pathname, + routeId: match.route.id + }); + } else { + // lazy() route has no loader to run. Short circuit here so we don't + // hit the invariant below that errors on returning undefined. + return { + type: ResultType.data, + data: undefined + }; + } + } + } else if (!handler) { + let url = new URL(request.url); + let pathname = url.pathname + url.search; + throw getInternalRouterError(404, { + pathname + }); + } else { + result = await runHandler(handler); + } + invariant(result !== undefined, "You defined " + (type === "action" ? "an action" : "a loader") + " for route " + ("\"" + match.route.id + "\" but didn't return anything from your `" + type + "` ") + "function. Please return a value or `null`."); + } catch (e) { + resultType = ResultType.error; + result = e; + } finally { + if (onReject) { + request.signal.removeEventListener("abort", onReject); + } + } + if (isResponse(result)) { + let status = result.status; + // Process redirects + if (redirectStatusCodes.has(status)) { + let location = result.headers.get("Location"); + invariant(location, "Redirects returned/thrown from loaders/actions must have a Location header"); + // Support relative routing in internal redirects + if (!ABSOLUTE_URL_REGEX.test(location)) { + location = normalizeTo(new URL(request.url), matches.slice(0, matches.indexOf(match) + 1), basename, true, location); + } else if (!opts.isStaticRequest) { + // Strip off the protocol+origin for same-origin + same-basename absolute + // redirects. If this is a static request, we can let it go back to the + // browser as-is + let currentUrl = new URL(request.url); + let url = location.startsWith("//") ? new URL(currentUrl.protocol + location) : new URL(location); + let isSameBasename = stripBasename(url.pathname, basename) != null; + if (url.origin === currentUrl.origin && isSameBasename) { + location = url.pathname + url.search + url.hash; + } + } + // Don't process redirects in the router during static requests requests. + // Instead, throw the Response and let the server handle it with an HTTP + // redirect. We also update the Location header in place in this flow so + // basename and relative routing is taken into account + if (opts.isStaticRequest) { + result.headers.set("Location", location); + throw result; + } + return { + type: ResultType.redirect, + status, + location, + revalidate: result.headers.get("X-Remix-Revalidate") !== null, + reloadDocument: result.headers.get("X-Remix-Reload-Document") !== null + }; + } + // For SSR single-route requests, we want to hand Responses back directly + // without unwrapping. We do this with the QueryRouteResponse wrapper + // interface so we can know whether it was returned or thrown + if (opts.isRouteRequest) { + let queryRouteResponse = { + type: resultType === ResultType.error ? ResultType.error : ResultType.data, + response: result + }; + throw queryRouteResponse; + } + let data; + let contentType = result.headers.get("Content-Type"); + // Check between word boundaries instead of startsWith() due to the last + // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type + if (contentType && /\bapplication\/json\b/.test(contentType)) { + data = await result.json(); + } else { + data = await result.text(); + } + if (resultType === ResultType.error) { + return { + type: resultType, + error: new ErrorResponseImpl(status, result.statusText, data), + headers: result.headers + }; + } + return { + type: ResultType.data, + data, + statusCode: result.status, + headers: result.headers + }; + } + if (resultType === ResultType.error) { + return { + type: resultType, + error: result + }; + } + if (isDeferredData(result)) { + var _result$init, _result$init2; + return { + type: ResultType.deferred, + deferredData: result, + statusCode: (_result$init = result.init) == null ? void 0 : _result$init.status, + headers: ((_result$init2 = result.init) == null ? void 0 : _result$init2.headers) && new Headers(result.init.headers) + }; + } + return { + type: ResultType.data, + data: result + }; +} +// Utility method for creating the Request instances for loaders/actions during +// client-side navigations and fetches. During SSR we will always have a +// Request instance from the static handler (query/queryRoute) +function createClientSideRequest(history, location, signal, submission) { + let url = history.createURL(stripHashFromPath(location)).toString(); + let init = { + signal + }; + if (submission && isMutationMethod(submission.formMethod)) { + let { + formMethod, + formEncType + } = submission; + // Didn't think we needed this but it turns out unlike other methods, patch + // won't be properly normalized to uppercase and results in a 405 error. + // See: https://fetch.spec.whatwg.org/#concept-method + init.method = formMethod.toUpperCase(); + if (formEncType === "application/json") { + init.headers = new Headers({ + "Content-Type": formEncType + }); + init.body = JSON.stringify(submission.json); + } else if (formEncType === "text/plain") { + // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request) + init.body = submission.text; + } else if (formEncType === "application/x-www-form-urlencoded" && submission.formData) { + // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request) + init.body = convertFormDataToSearchParams(submission.formData); + } else { + // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request) + init.body = submission.formData; + } + } + return new Request(url, init); +} +function convertFormDataToSearchParams(formData) { + let searchParams = new URLSearchParams(); + for (let [key, value] of formData.entries()) { + // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs + searchParams.append(key, typeof value === "string" ? value : value.name); + } + return searchParams; +} +function convertSearchParamsToFormData(searchParams) { + let formData = new FormData(); + for (let [key, value] of searchParams.entries()) { + formData.append(key, value); + } + return formData; +} +function processRouteLoaderData(matches, matchesToLoad, results, pendingError, activeDeferreds) { + // Fill in loaderData/errors from our loaders + let loaderData = {}; + let errors = null; + let statusCode; + let foundError = false; + let loaderHeaders = {}; + // Process loader results into state.loaderData/state.errors + results.forEach((result, index) => { + let id = matchesToLoad[index].route.id; + invariant(!isRedirectResult(result), "Cannot handle redirect results in processLoaderData"); + if (isErrorResult(result)) { + // Look upwards from the matched route for the closest ancestor + // error boundary, defaulting to the root match + let boundaryMatch = findNearestBoundary(matches, id); + let error = result.error; + // If we have a pending action error, we report it at the highest-route + // that throws a loader error, and then clear it out to indicate that + // it was consumed + if (pendingError) { + error = Object.values(pendingError)[0]; + pendingError = undefined; + } + errors = errors || {}; + // Prefer higher error values if lower errors bubble to the same boundary + if (errors[boundaryMatch.route.id] == null) { + errors[boundaryMatch.route.id] = error; + } + // Clear our any prior loaderData for the throwing route + loaderData[id] = undefined; + // Once we find our first (highest) error, we set the status code and + // prevent deeper status codes from overriding + if (!foundError) { + foundError = true; + statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500; + } + if (result.headers) { + loaderHeaders[id] = result.headers; + } + } else { + if (isDeferredResult(result)) { + activeDeferreds.set(id, result.deferredData); + loaderData[id] = result.deferredData.data; + } else { + loaderData[id] = result.data; + } + // Error status codes always override success status codes, but if all + // loaders are successful we take the deepest status code. + if (result.statusCode != null && result.statusCode !== 200 && !foundError) { + statusCode = result.statusCode; + } + if (result.headers) { + loaderHeaders[id] = result.headers; + } + } + }); + // If we didn't consume the pending action error (i.e., all loaders + // resolved), then consume it here. Also clear out any loaderData for the + // throwing route + if (pendingError) { + errors = pendingError; + loaderData[Object.keys(pendingError)[0]] = undefined; + } + return { + loaderData, + errors, + statusCode: statusCode || 200, + loaderHeaders + }; +} +function processLoaderData(state, matches, matchesToLoad, results, pendingError, revalidatingFetchers, fetcherResults, activeDeferreds) { + let { + loaderData, + errors + } = processRouteLoaderData(matches, matchesToLoad, results, pendingError, activeDeferreds); + // Process results from our revalidating fetchers + for (let index = 0; index < revalidatingFetchers.length; index++) { + let { + key, + match, + controller + } = revalidatingFetchers[index]; + invariant(fetcherResults !== undefined && fetcherResults[index] !== undefined, "Did not find corresponding fetcher result"); + let result = fetcherResults[index]; + // Process fetcher non-redirect errors + if (controller && controller.signal.aborted) { + // Nothing to do for aborted fetchers + continue; + } else if (isErrorResult(result)) { + let boundaryMatch = findNearestBoundary(state.matches, match == null ? void 0 : match.route.id); + if (!(errors && errors[boundaryMatch.route.id])) { + errors = _extends({}, errors, { + [boundaryMatch.route.id]: result.error + }); + } + state.fetchers.delete(key); + } else if (isRedirectResult(result)) { + // Should never get here, redirects should get processed above, but we + // keep this to type narrow to a success result in the else + invariant(false, "Unhandled fetcher revalidation redirect"); + } else if (isDeferredResult(result)) { + // Should never get here, deferred data should be awaited for fetchers + // in resolveDeferredResults + invariant(false, "Unhandled fetcher deferred data"); + } else { + let doneFetcher = getDoneFetcher(result.data); + state.fetchers.set(key, doneFetcher); + } + } + return { + loaderData, + errors + }; +} +function mergeLoaderData(loaderData, newLoaderData, matches, errors) { + let mergedLoaderData = _extends({}, newLoaderData); + for (let match of matches) { + let id = match.route.id; + if (newLoaderData.hasOwnProperty(id)) { + if (newLoaderData[id] !== undefined) { + mergedLoaderData[id] = newLoaderData[id]; + } + } else if (loaderData[id] !== undefined && match.route.loader) { + // Preserve existing keys not included in newLoaderData and where a loader + // wasn't removed by HMR + mergedLoaderData[id] = loaderData[id]; + } + if (errors && errors.hasOwnProperty(id)) { + // Don't keep any loader data below the boundary + break; + } + } + return mergedLoaderData; +} +// Find the nearest error boundary, looking upwards from the leaf route (or the +// route specified by routeId) for the closest ancestor error boundary, +// defaulting to the root match +function findNearestBoundary(matches, routeId) { + let eligibleMatches = routeId ? matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1) : [...matches]; + return eligibleMatches.reverse().find(m => m.route.hasErrorBoundary === true) || matches[0]; +} +function getShortCircuitMatches(routes) { + // Prefer a root layout route if present, otherwise shim in a route object + let route = routes.length === 1 ? routes[0] : routes.find(r => r.index || !r.path || r.path === "/") || { + id: "__shim-error-route__" + }; + return { + matches: [{ + params: {}, + pathname: "", + pathnameBase: "", + route + }], + route + }; +} +function getInternalRouterError(status, _temp4) { + let { + pathname, + routeId, + method, + type + } = _temp4 === void 0 ? {} : _temp4; + let statusText = "Unknown Server Error"; + let errorMessage = "Unknown @remix-run/router error"; + if (status === 400) { + statusText = "Bad Request"; + if (method && pathname && routeId) { + errorMessage = "You made a " + method + " request to \"" + pathname + "\" but " + ("did not provide a `loader` for route \"" + routeId + "\", ") + "so there is no way to handle the request."; + } else if (type === "defer-action") { + errorMessage = "defer() is not supported in actions"; + } else if (type === "invalid-body") { + errorMessage = "Unable to encode submission body"; + } + } else if (status === 403) { + statusText = "Forbidden"; + errorMessage = "Route \"" + routeId + "\" does not match URL \"" + pathname + "\""; + } else if (status === 404) { + statusText = "Not Found"; + errorMessage = "No route matches URL \"" + pathname + "\""; + } else if (status === 405) { + statusText = "Method Not Allowed"; + if (method && pathname && routeId) { + errorMessage = "You made a " + method.toUpperCase() + " request to \"" + pathname + "\" but " + ("did not provide an `action` for route \"" + routeId + "\", ") + "so there is no way to handle the request."; + } else if (method) { + errorMessage = "Invalid request method \"" + method.toUpperCase() + "\""; + } + } + return new ErrorResponseImpl(status || 500, statusText, new Error(errorMessage), true); +} +// Find any returned redirect errors, starting from the lowest match +function findRedirect(results) { + for (let i = results.length - 1; i >= 0; i--) { + let result = results[i]; + if (isRedirectResult(result)) { + return { + result, + idx: i + }; + } + } +} +function stripHashFromPath(path) { + let parsedPath = typeof path === "string" ? parsePath(path) : path; + return createPath(_extends({}, parsedPath, { + hash: "" + })); +} +function isHashChangeOnly(a, b) { + if (a.pathname !== b.pathname || a.search !== b.search) { + return false; + } + if (a.hash === "") { + // /page -> /page#hash + return b.hash !== ""; + } else if (a.hash === b.hash) { + // /page#hash -> /page#hash + return true; + } else if (b.hash !== "") { + // /page#hash -> /page#other + return true; + } + // If the hash is removed the browser will re-perform a request to the server + // /page#hash -> /page + return false; +} +function isDeferredResult(result) { + return result.type === ResultType.deferred; +} +function isErrorResult(result) { + return result.type === ResultType.error; +} +function isRedirectResult(result) { + return (result && result.type) === ResultType.redirect; +} +function isDeferredData(value) { + let deferred = value; + return deferred && typeof deferred === "object" && typeof deferred.data === "object" && typeof deferred.subscribe === "function" && typeof deferred.cancel === "function" && typeof deferred.resolveData === "function"; +} +function isResponse(value) { + return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined"; +} +function isRedirectResponse(result) { + if (!isResponse(result)) { + return false; + } + let status = result.status; + let location = result.headers.get("Location"); + return status >= 300 && status <= 399 && location != null; +} +function isQueryRouteResponse(obj) { + return obj && isResponse(obj.response) && (obj.type === ResultType.data || obj.type === ResultType.error); +} +function isValidMethod(method) { + return validRequestMethods.has(method.toLowerCase()); +} +function isMutationMethod(method) { + return validMutationMethods.has(method.toLowerCase()); +} +async function resolveDeferredResults(currentMatches, matchesToLoad, results, signals, isFetcher, currentLoaderData) { + for (let index = 0; index < results.length; index++) { + let result = results[index]; + let match = matchesToLoad[index]; + // If we don't have a match, then we can have a deferred result to do + // anything with. This is for revalidating fetchers where the route was + // removed during HMR + if (!match) { + continue; + } + let currentMatch = currentMatches.find(m => m.route.id === match.route.id); + let isRevalidatingLoader = currentMatch != null && !isNewRouteInstance(currentMatch, match) && (currentLoaderData && currentLoaderData[match.route.id]) !== undefined; + if (isDeferredResult(result) && (isFetcher || isRevalidatingLoader)) { + // Note: we do not have to touch activeDeferreds here since we race them + // against the signal in resolveDeferredData and they'll get aborted + // there if needed + let signal = signals[index]; + invariant(signal, "Expected an AbortSignal for revalidating fetcher deferred result"); + await resolveDeferredData(result, signal, isFetcher).then(result => { + if (result) { + results[index] = result || results[index]; + } + }); + } + } +} +async function resolveDeferredData(result, signal, unwrap) { + if (unwrap === void 0) { + unwrap = false; + } + let aborted = await result.deferredData.resolveData(signal); + if (aborted) { + return; + } + if (unwrap) { + try { + return { + type: ResultType.data, + data: result.deferredData.unwrappedData + }; + } catch (e) { + // Handle any TrackedPromise._error values encountered while unwrapping + return { + type: ResultType.error, + error: e + }; + } + } + return { + type: ResultType.data, + data: result.deferredData.data + }; +} +function hasNakedIndexQuery(search) { + return new URLSearchParams(search).getAll("index").some(v => v === ""); +} +function getTargetMatch(matches, location) { + let search = typeof location === "string" ? parsePath(location).search : location.search; + if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) { + // Return the leaf index route when index is present + return matches[matches.length - 1]; + } + // Otherwise grab the deepest "path contributing" match (ignoring index and + // pathless layout routes) + let pathMatches = getPathContributingMatches(matches); + return pathMatches[pathMatches.length - 1]; +} +function getSubmissionFromNavigation(navigation) { + let { + formMethod, + formAction, + formEncType, + text, + formData, + json + } = navigation; + if (!formMethod || !formAction || !formEncType) { + return; + } + if (text != null) { + return { + formMethod, + formAction, + formEncType, + formData: undefined, + json: undefined, + text + }; + } else if (formData != null) { + return { + formMethod, + formAction, + formEncType, + formData, + json: undefined, + text: undefined + }; + } else if (json !== undefined) { + return { + formMethod, + formAction, + formEncType, + formData: undefined, + json, + text: undefined + }; + } +} +function getLoadingNavigation(location, submission) { + if (submission) { + let navigation = { + state: "loading", + location, + formMethod: submission.formMethod, + formAction: submission.formAction, + formEncType: submission.formEncType, + formData: submission.formData, + json: submission.json, + text: submission.text + }; + return navigation; + } else { + let navigation = { + state: "loading", + location, + formMethod: undefined, + formAction: undefined, + formEncType: undefined, + formData: undefined, + json: undefined, + text: undefined + }; + return navigation; + } +} +function getSubmittingNavigation(location, submission) { + let navigation = { + state: "submitting", + location, + formMethod: submission.formMethod, + formAction: submission.formAction, + formEncType: submission.formEncType, + formData: submission.formData, + json: submission.json, + text: submission.text + }; + return navigation; +} +function getLoadingFetcher(submission, data) { + if (submission) { + let fetcher = { + state: "loading", + formMethod: submission.formMethod, + formAction: submission.formAction, + formEncType: submission.formEncType, + formData: submission.formData, + json: submission.json, + text: submission.text, + data + }; + return fetcher; + } else { + let fetcher = { + state: "loading", + formMethod: undefined, + formAction: undefined, + formEncType: undefined, + formData: undefined, + json: undefined, + text: undefined, + data + }; + return fetcher; + } +} +function getSubmittingFetcher(submission, existingFetcher) { + let fetcher = { + state: "submitting", + formMethod: submission.formMethod, + formAction: submission.formAction, + formEncType: submission.formEncType, + formData: submission.formData, + json: submission.json, + text: submission.text, + data: existingFetcher ? existingFetcher.data : undefined + }; + return fetcher; +} +function getDoneFetcher(data) { + let fetcher = { + state: "idle", + formMethod: undefined, + formAction: undefined, + formEncType: undefined, + formData: undefined, + json: undefined, + text: undefined, + data + }; + return fetcher; +} +function restoreAppliedTransitions(_window, transitions) { + try { + let sessionPositions = _window.sessionStorage.getItem(TRANSITIONS_STORAGE_KEY); + if (sessionPositions) { + let json = JSON.parse(sessionPositions); + for (let [k, v] of Object.entries(json || {})) { + if (v && Array.isArray(v)) { + transitions.set(k, new Set(v || [])); + } + } + } + } catch (e) { + // no-op, use default empty object + } +} +function persistAppliedTransitions(_window, transitions) { + if (transitions.size > 0) { + let json = {}; + for (let [k, v] of transitions) { + json[k] = [...v]; + } + try { + _window.sessionStorage.setItem(TRANSITIONS_STORAGE_KEY, JSON.stringify(json)); + } catch (error) { + warning(false, "Failed to save applied view transitions in sessionStorage (" + error + ")."); + } + } +} +//#endregion + + + +/***/ }), + +/***/ "./node_modules/ansi-styles/index.js": +/*!*******************************************!*\ + !*** ./node_modules/ansi-styles/index.js ***! + \*******************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(module) { + +const colorConvert = __webpack_require__(/*! color-convert */ "./node_modules/color-convert/index.js"); +const wrapAnsi16 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${code + offset}m`; +}; +const wrapAnsi256 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};5;${code}m`; +}; +const wrapAnsi16m = (fn, offset) => function () { + const rgb = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; +}; +function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39], + // Bright color + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; + + // Fix humans + styles.color.grey = styles.color.gray; + for (const groupName of Object.keys(styles)) { + const group = styles[groupName]; + for (const styleName of Object.keys(group)) { + const style = group[styleName]; + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m` + }; + group[styleName] = styles[styleName]; + codes.set(style[0], style[1]); + } + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + } + const ansi2ansi = n => n; + const rgb2rgb = (r, g, b) => [r, g, b]; + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + styles.color.ansi = { + ansi: wrapAnsi16(ansi2ansi, 0) + }; + styles.color.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 0) + }; + styles.color.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 0) + }; + styles.bgColor.ansi = { + ansi: wrapAnsi16(ansi2ansi, 10) + }; + styles.bgColor.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 10) + }; + styles.bgColor.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 10) + }; + for (let key of Object.keys(colorConvert)) { + if (typeof colorConvert[key] !== 'object') { + continue; + } + const suite = colorConvert[key]; + if (key === 'ansi16') { + key = 'ansi'; + } + if ('ansi16' in suite) { + styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); + styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); + } + if ('ansi256' in suite) { + styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); + styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); + } + if ('rgb' in suite) { + styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); + styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); + } + } + return styles; +} + +// Make the export immutable +Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles +}); +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/module.js */ "./node_modules/webpack/buildin/module.js")(module))) + +/***/ }), + +/***/ "./node_modules/call-bind/callBound.js": +/*!*********************************************!*\ + !*** ./node_modules/call-bind/callBound.js ***! + \*********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js"); +var callBind = __webpack_require__(/*! ./ */ "./node_modules/call-bind/index.js"); +var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); +module.exports = function callBoundIntrinsic(name, allowMissing) { + var intrinsic = GetIntrinsic(name, !!allowMissing); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBind(intrinsic); + } + return intrinsic; +}; + +/***/ }), + +/***/ "./node_modules/call-bind/index.js": +/*!*****************************************!*\ + !*** ./node_modules/call-bind/index.js ***! + \*****************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var bind = __webpack_require__(/*! function-bind */ "./node_modules/function-bind/index.js"); +var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js"); +var $apply = GetIntrinsic('%Function.prototype.apply%'); +var $call = GetIntrinsic('%Function.prototype.call%'); +var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); +var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); +var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); +var $max = GetIntrinsic('%Math.max%'); +if ($defineProperty) { + try { + $defineProperty({}, 'a', { + value: 1 + }); + } catch (e) { + // IE 8 has a broken defineProperty + $defineProperty = null; + } +} +module.exports = function callBind(originalFunction) { + var func = $reflectApply(bind, $call, arguments); + if ($gOPD && $defineProperty) { + var desc = $gOPD(func, 'length'); + if (desc.configurable) { + // original length, plus the receiver, minus any additional arguments (after the receiver) + $defineProperty(func, 'length', { + value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) + }); + } + } + return func; +}; +var applyBind = function applyBind() { + return $reflectApply(bind, $apply, arguments); +}; +if ($defineProperty) { + $defineProperty(module.exports, 'apply', { + value: applyBind + }); +} else { + module.exports.apply = applyBind; +} + +/***/ }), + +/***/ "./node_modules/chalk/index.js": +/*!*************************************!*\ + !*** ./node_modules/chalk/index.js ***! + \*************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) { + +const escapeStringRegexp = __webpack_require__(/*! escape-string-regexp */ "./node_modules/escape-string-regexp/index.js"); +const ansiStyles = __webpack_require__(/*! ansi-styles */ "./node_modules/ansi-styles/index.js"); +const stdoutColor = __webpack_require__(/*! supports-color */ "./node_modules/supports-color/browser.js").stdout; +const template = __webpack_require__(/*! ./templates.js */ "./node_modules/chalk/templates.js"); +const isSimpleWindowsTerm = process.platform === 'win32' && !(Object({"NODE_ENV":"development","PUBLIC_URL":""}).TERM || '').toLowerCase().startsWith('xterm'); + +// `supportsColor.level` → `ansiStyles.color[name]` mapping +const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; + +// `color-convert` models to exclude from the Chalk API due to conflicts and such +const skipModels = new Set(['gray']); +const styles = Object.create(null); +function applyOptions(obj, options) { + options = options || {}; + + // Detect level if not set manually + const scLevel = stdoutColor ? stdoutColor.level : 0; + obj.level = options.level === undefined ? scLevel : options.level; + obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; +} +function Chalk(options) { + // We check for this.template here since calling `chalk.constructor()` + // by itself will have a `this` of a previously constructed chalk object + if (!this || !(this instanceof Chalk) || this.template) { + const chalk = {}; + applyOptions(chalk, options); + chalk.template = function () { + const args = [].slice.call(arguments); + return chalkTag.apply(null, [chalk.template].concat(args)); + }; + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); + chalk.template.constructor = Chalk; + return chalk.template; + } + applyOptions(this, options); +} + +// Use bright blue on Windows as the normal blue color is illegible +if (isSimpleWindowsTerm) { + ansiStyles.blue.open = '\u001B[94m'; +} +for (const key of Object.keys(ansiStyles)) { + ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); + styles[key] = { + get() { + const codes = ansiStyles[key]; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); + } + }; +} +styles.visible = { + get() { + return build.call(this, this._styles || [], true, 'visible'); + } +}; +ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); +for (const model of Object.keys(ansiStyles.color.ansi)) { + if (skipModels.has(model)) { + continue; + } + styles[model] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.color.close, + closeRe: ansiStyles.color.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; +} +ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); +for (const model of Object.keys(ansiStyles.bgColor.ansi)) { + if (skipModels.has(model)) { + continue; + } + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.bgColor.close, + closeRe: ansiStyles.bgColor.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; +} +const proto = Object.defineProperties(() => {}, styles); +function build(_styles, _empty, key) { + const builder = function () { + return applyStyle.apply(builder, arguments); + }; + builder._styles = _styles; + builder._empty = _empty; + const self = this; + Object.defineProperty(builder, 'level', { + enumerable: true, + get() { + return self.level; + }, + set(level) { + self.level = level; + } + }); + Object.defineProperty(builder, 'enabled', { + enumerable: true, + get() { + return self.enabled; + }, + set(enabled) { + self.enabled = enabled; + } + }); + + // See below for fix regarding invisible grey/dim combination on Windows + builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; + + // `__proto__` is used because we must return a function, but there is + // no way to create a function with a different prototype + builder.__proto__ = proto; // eslint-disable-line no-proto + + return builder; +} +function applyStyle() { + // Support varags, but simply cast to string in case there's only one arg + const args = arguments; + const argsLen = args.length; + let str = String(arguments[0]); + if (argsLen === 0) { + return ''; + } + if (argsLen > 1) { + // Don't slice `arguments`, it prevents V8 optimizations + for (let a = 1; a < argsLen; a++) { + str += ' ' + args[a]; + } + } + if (!this.enabled || this.level <= 0 || !str) { + return this._empty ? '' : str; + } + + // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, + // see https://github.com/chalk/chalk/issues/58 + // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. + const originalDim = ansiStyles.dim.open; + if (isSimpleWindowsTerm && this.hasGrey) { + ansiStyles.dim.open = ''; + } + for (const code of this._styles.slice().reverse()) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + str = code.open + str.replace(code.closeRe, code.open) + code.close; + + // Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS + // https://github.com/chalk/chalk/pull/92 + str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); + } + + // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue + ansiStyles.dim.open = originalDim; + return str; +} +function chalkTag(chalk, strings) { + if (!Array.isArray(strings)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return [].slice.call(arguments, 1).join(' '); + } + const args = [].slice.call(arguments, 2); + const parts = [strings.raw[0]]; + for (let i = 1; i < strings.length; i++) { + parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); + parts.push(String(strings.raw[i])); + } + return template(chalk, parts.join('')); +} +Object.defineProperties(Chalk.prototype, styles); +module.exports = Chalk(); // eslint-disable-line new-cap +module.exports.supportsColor = stdoutColor; +module.exports.default = module.exports; // For TypeScript +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../process/browser.js */ "./node_modules/process/browser.js"))) + +/***/ }), + +/***/ "./node_modules/chalk/templates.js": +/*!*****************************************!*\ + !*** ./node_modules/chalk/templates.js ***! + \*****************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; +const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; +const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; +const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; +const ESCAPES = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]); +function unescape(c) { + if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) { + return String.fromCharCode(parseInt(c.slice(1), 16)); + } + return ESCAPES.get(c) || c; +} +function parseArguments(name, args) { + const results = []; + const chunks = args.trim().split(/\s*,\s*/g); + let matches; + for (const chunk of chunks) { + if (!isNaN(chunk)) { + results.push(Number(chunk)); + } else if (matches = chunk.match(STRING_REGEX)) { + results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr)); + } else { + throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); + } + } + return results; +} +function parseStyle(style) { + STYLE_REGEX.lastIndex = 0; + const results = []; + let matches; + while ((matches = STYLE_REGEX.exec(style)) !== null) { + const name = matches[1]; + if (matches[2]) { + const args = parseArguments(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); + } + } + return results; +} +function buildStyle(chalk, styles) { + const enabled = {}; + for (const layer of styles) { + for (const style of layer.styles) { + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } + let current = chalk; + for (const styleName of Object.keys(enabled)) { + if (Array.isArray(enabled[styleName])) { + if (!(styleName in current)) { + throw new Error(`Unknown Chalk style: ${styleName}`); + } + if (enabled[styleName].length > 0) { + current = current[styleName].apply(current, enabled[styleName]); + } else { + current = current[styleName]; + } + } + } + return current; +} +module.exports = (chalk, tmp) => { + const styles = []; + const chunks = []; + let chunk = []; + + // eslint-disable-next-line max-params + tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => { + if (escapeChar) { + chunk.push(unescape(escapeChar)); + } else if (style) { + const str = chunk.join(''); + chunk = []; + chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); + styles.push({ + inverse, + styles: parseStyle(style) + }); + } else if (close) { + if (styles.length === 0) { + throw new Error('Found extraneous } in Chalk template literal'); + } + chunks.push(buildStyle(chalk, styles)(chunk.join(''))); + chunk = []; + styles.pop(); + } else { + chunk.push(chr); + } + }); + chunks.push(chunk.join('')); + if (styles.length > 0) { + const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; + throw new Error(errMsg); + } + return chunks.join(''); +}; + +/***/ }), + +/***/ "./node_modules/color-convert/conversions.js": +/*!***************************************************!*\ + !*** ./node_modules/color-convert/conversions.js ***! + \***************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +/* MIT license */ +var cssKeywords = __webpack_require__(/*! color-name */ "./node_modules/color-name/index.js"); + +// NOTE: conversions should only return primitive values (i.e. arrays, or +// values that give correct `typeof` results). +// do not use box values types (i.e. Number(), String(), etc.) + +var reverseKeywords = {}; +for (var key in cssKeywords) { + if (cssKeywords.hasOwnProperty(key)) { + reverseKeywords[cssKeywords[key]] = key; + } +} +var convert = module.exports = { + rgb: { + channels: 3, + labels: 'rgb' + }, + hsl: { + channels: 3, + labels: 'hsl' + }, + hsv: { + channels: 3, + labels: 'hsv' + }, + hwb: { + channels: 3, + labels: 'hwb' + }, + cmyk: { + channels: 4, + labels: 'cmyk' + }, + xyz: { + channels: 3, + labels: 'xyz' + }, + lab: { + channels: 3, + labels: 'lab' + }, + lch: { + channels: 3, + labels: 'lch' + }, + hex: { + channels: 1, + labels: ['hex'] + }, + keyword: { + channels: 1, + labels: ['keyword'] + }, + ansi16: { + channels: 1, + labels: ['ansi16'] + }, + ansi256: { + channels: 1, + labels: ['ansi256'] + }, + hcg: { + channels: 3, + labels: ['h', 'c', 'g'] + }, + apple: { + channels: 3, + labels: ['r16', 'g16', 'b16'] + }, + gray: { + channels: 1, + labels: ['gray'] + } +}; + +// hide .channels and .labels properties +for (var model in convert) { + if (convert.hasOwnProperty(model)) { + if (!('channels' in convert[model])) { + throw new Error('missing channels property: ' + model); + } + if (!('labels' in convert[model])) { + throw new Error('missing channel labels property: ' + model); + } + if (convert[model].labels.length !== convert[model].channels) { + throw new Error('channel and label counts mismatch: ' + model); + } + var channels = convert[model].channels; + var labels = convert[model].labels; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], 'channels', { + value: channels + }); + Object.defineProperty(convert[model], 'labels', { + value: labels + }); + } +} +convert.rgb.hsl = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var delta = max - min; + var h; + var s; + var l; + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } + h = Math.min(h * 60, 360); + if (h < 0) { + h += 360; + } + l = (min + max) / 2; + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } + return [h, s * 100, l * 100]; +}; +convert.rgb.hsv = function (rgb) { + var rdif; + var gdif; + var bdif; + var h; + var s; + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var v = Math.max(r, g, b); + var diff = v - Math.min(r, g, b); + var diffc = function (c) { + return (v - c) / 6 / diff + 1 / 2; + }; + if (diff === 0) { + h = s = 0; + } else { + s = diff / v; + rdif = diffc(r); + gdif = diffc(g); + bdif = diffc(b); + if (r === v) { + h = bdif - gdif; + } else if (g === v) { + h = 1 / 3 + rdif - bdif; + } else if (b === v) { + h = 2 / 3 + gdif - rdif; + } + if (h < 0) { + h += 1; + } else if (h > 1) { + h -= 1; + } + } + return [h * 360, s * 100, v * 100]; +}; +convert.rgb.hwb = function (rgb) { + var r = rgb[0]; + var g = rgb[1]; + var b = rgb[2]; + var h = convert.rgb.hsl(rgb)[0]; + var w = 1 / 255 * Math.min(r, Math.min(g, b)); + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + return [h, w * 100, b * 100]; +}; +convert.rgb.cmyk = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var c; + var m; + var y; + var k; + k = Math.min(1 - r, 1 - g, 1 - b); + c = (1 - r - k) / (1 - k) || 0; + m = (1 - g - k) / (1 - k) || 0; + y = (1 - b - k) / (1 - k) || 0; + return [c * 100, m * 100, y * 100, k * 100]; +}; + +/** + * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance + * */ +function comparativeDistance(x, y) { + return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2); +} +convert.rgb.keyword = function (rgb) { + var reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; + } + var currentClosestDistance = Infinity; + var currentClosestKeyword; + for (var keyword in cssKeywords) { + if (cssKeywords.hasOwnProperty(keyword)) { + var value = cssKeywords[keyword]; + + // Compute comparative distance + var distance = comparativeDistance(rgb, value); + + // Check if its less, if so set as closest + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + } + return currentClosestKeyword; +}; +convert.keyword.rgb = function (keyword) { + return cssKeywords[keyword]; +}; +convert.rgb.xyz = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + + // assume sRGB + r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92; + g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92; + b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92; + var x = r * 0.4124 + g * 0.3576 + b * 0.1805; + var y = r * 0.2126 + g * 0.7152 + b * 0.0722; + var z = r * 0.0193 + g * 0.1192 + b * 0.9505; + return [x * 100, y * 100, z * 100]; +}; +convert.rgb.lab = function (rgb) { + var xyz = convert.rgb.xyz(rgb); + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + x /= 95.047; + y /= 100; + z /= 108.883; + x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116; + y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116; + z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116; + l = 116 * y - 16; + a = 500 * (x - y); + b = 200 * (y - z); + return [l, a, b]; +}; +convert.hsl.rgb = function (hsl) { + var h = hsl[0] / 360; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var t1; + var t2; + var t3; + var rgb; + var val; + if (s === 0) { + val = l * 255; + return [val, val, val]; + } + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } + t1 = 2 * l - t2; + rgb = [0, 0, 0]; + for (var i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + if (t3 < 0) { + t3++; + } + if (t3 > 1) { + t3--; + } + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } + rgb[i] = val * 255; + } + return rgb; +}; +convert.hsl.hsv = function (hsl) { + var h = hsl[0]; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var smin = s; + var lmin = Math.max(l, 0.01); + var sv; + var v; + l *= 2; + s *= l <= 1 ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + v = (l + s) / 2; + sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s); + return [h, sv * 100, v * 100]; +}; +convert.hsv.rgb = function (hsv) { + var h = hsv[0] / 60; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var hi = Math.floor(h) % 6; + var f = h - Math.floor(h); + var p = 255 * v * (1 - s); + var q = 255 * v * (1 - s * f); + var t = 255 * v * (1 - s * (1 - f)); + v *= 255; + switch (hi) { + case 0: + return [v, t, p]; + case 1: + return [q, v, p]; + case 2: + return [p, v, t]; + case 3: + return [p, q, v]; + case 4: + return [t, p, v]; + case 5: + return [v, p, q]; + } +}; +convert.hsv.hsl = function (hsv) { + var h = hsv[0]; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var vmin = Math.max(v, 0.01); + var lmin; + var sl; + var l; + l = (2 - s) * v; + lmin = (2 - s) * vmin; + sl = s * vmin; + sl /= lmin <= 1 ? lmin : 2 - lmin; + sl = sl || 0; + l /= 2; + return [h, sl * 100, l * 100]; +}; + +// http://dev.w3.org/csswg/css-color/#hwb-to-rgb +convert.hwb.rgb = function (hwb) { + var h = hwb[0] / 360; + var wh = hwb[1] / 100; + var bl = hwb[2] / 100; + var ratio = wh + bl; + var i; + var v; + var f; + var n; + + // wh + bl cant be > 1 + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + i = Math.floor(6 * h); + v = 1 - bl; + f = 6 * h - i; + if ((i & 0x01) !== 0) { + f = 1 - f; + } + n = wh + f * (v - wh); // linear interpolation + + var r; + var g; + var b; + switch (i) { + default: + case 6: + case 0: + r = v; + g = n; + b = wh; + break; + case 1: + r = n; + g = v; + b = wh; + break; + case 2: + r = wh; + g = v; + b = n; + break; + case 3: + r = wh; + g = n; + b = v; + break; + case 4: + r = n; + g = wh; + b = v; + break; + case 5: + r = v; + g = wh; + b = n; + break; + } + return [r * 255, g * 255, b * 255]; +}; +convert.cmyk.rgb = function (cmyk) { + var c = cmyk[0] / 100; + var m = cmyk[1] / 100; + var y = cmyk[2] / 100; + var k = cmyk[3] / 100; + var r; + var g; + var b; + r = 1 - Math.min(1, c * (1 - k) + k); + g = 1 - Math.min(1, m * (1 - k) + k); + b = 1 - Math.min(1, y * (1 - k) + k); + return [r * 255, g * 255, b * 255]; +}; +convert.xyz.rgb = function (xyz) { + var x = xyz[0] / 100; + var y = xyz[1] / 100; + var z = xyz[2] / 100; + var r; + var g; + var b; + r = x * 3.2406 + y * -1.5372 + z * -0.4986; + g = x * -0.9689 + y * 1.8758 + z * 0.0415; + b = x * 0.0557 + y * -0.2040 + z * 1.0570; + + // assume sRGB + r = r > 0.0031308 ? 1.055 * Math.pow(r, 1.0 / 2.4) - 0.055 : r * 12.92; + g = g > 0.0031308 ? 1.055 * Math.pow(g, 1.0 / 2.4) - 0.055 : g * 12.92; + b = b > 0.0031308 ? 1.055 * Math.pow(b, 1.0 / 2.4) - 0.055 : b * 12.92; + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); + return [r * 255, g * 255, b * 255]; +}; +convert.xyz.lab = function (xyz) { + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + x /= 95.047; + y /= 100; + z /= 108.883; + x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116; + y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116; + z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116; + l = 116 * y - 16; + a = 500 * (x - y); + b = 200 * (y - z); + return [l, a, b]; +}; +convert.lab.xyz = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var x; + var y; + var z; + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; + var y2 = Math.pow(y, 3); + var x2 = Math.pow(x, 3); + var z2 = Math.pow(z, 3); + y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; + x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; + z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; + x *= 95.047; + y *= 100; + z *= 108.883; + return [x, y, z]; +}; +convert.lab.lch = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var hr; + var h; + var c; + hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + if (h < 0) { + h += 360; + } + c = Math.sqrt(a * a + b * b); + return [l, c, h]; +}; +convert.lch.lab = function (lch) { + var l = lch[0]; + var c = lch[1]; + var h = lch[2]; + var a; + var b; + var hr; + hr = h / 360 * 2 * Math.PI; + a = c * Math.cos(hr); + b = c * Math.sin(hr); + return [l, a, b]; +}; +convert.rgb.ansi16 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization + + value = Math.round(value / 50); + if (value === 0) { + return 30; + } + var ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255)); + if (value === 2) { + ansi += 60; + } + return ansi; +}; +convert.hsv.ansi16 = function (args) { + // optimization here; we already know the value and don't need to get + // it converted for us. + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); +}; +convert.rgb.ansi256 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + + // we use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (r === g && g === b) { + if (r < 8) { + return 16; + } + if (r > 248) { + return 231; + } + return Math.round((r - 8) / 247 * 24) + 232; + } + var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5); + return ansi; +}; +convert.ansi16.rgb = function (args) { + var color = args % 10; + + // handle greyscale + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } + color = color / 10.5 * 255; + return [color, color, color]; + } + var mult = (~~(args > 50) + 1) * 0.5; + var r = (color & 1) * mult * 255; + var g = (color >> 1 & 1) * mult * 255; + var b = (color >> 2 & 1) * mult * 255; + return [r, g, b]; +}; +convert.ansi256.rgb = function (args) { + // handle greyscale + if (args >= 232) { + var c = (args - 232) * 10 + 8; + return [c, c, c]; + } + args -= 16; + var rem; + var r = Math.floor(args / 36) / 5 * 255; + var g = Math.floor((rem = args % 36) / 6) / 5 * 255; + var b = rem % 6 / 5 * 255; + return [r, g, b]; +}; +convert.rgb.hex = function (args) { + var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF); + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; +convert.hex.rgb = function (args) { + var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + if (!match) { + return [0, 0, 0]; + } + var colorString = match[0]; + if (match[0].length === 3) { + colorString = colorString.split('').map(function (char) { + return char + char; + }).join(''); + } + var integer = parseInt(colorString, 16); + var r = integer >> 16 & 0xFF; + var g = integer >> 8 & 0xFF; + var b = integer & 0xFF; + return [r, g, b]; +}; +convert.rgb.hcg = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var max = Math.max(Math.max(r, g), b); + var min = Math.min(Math.min(r, g), b); + var chroma = max - min; + var grayscale; + var hue; + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } + if (chroma <= 0) { + hue = 0; + } else if (max === r) { + hue = (g - b) / chroma % 6; + } else if (max === g) { + hue = 2 + (b - r) / chroma; + } else { + hue = 4 + (r - g) / chroma + 4; + } + hue /= 6; + hue %= 1; + return [hue * 360, chroma * 100, grayscale * 100]; +}; +convert.hsl.hcg = function (hsl) { + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var c = 1; + var f = 0; + if (l < 0.5) { + c = 2.0 * s * l; + } else { + c = 2.0 * s * (1.0 - l); + } + if (c < 1.0) { + f = (l - 0.5 * c) / (1.0 - c); + } + return [hsl[0], c * 100, f * 100]; +}; +convert.hsv.hcg = function (hsv) { + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var c = s * v; + var f = 0; + if (c < 1.0) { + f = (v - c) / (1 - c); + } + return [hsv[0], c * 100, f * 100]; +}; +convert.hcg.rgb = function (hcg) { + var h = hcg[0] / 360; + var c = hcg[1] / 100; + var g = hcg[2] / 100; + if (c === 0.0) { + return [g * 255, g * 255, g * 255]; + } + var pure = [0, 0, 0]; + var hi = h % 1 * 6; + var v = hi % 1; + var w = 1 - v; + var mg = 0; + switch (Math.floor(hi)) { + case 0: + pure[0] = 1; + pure[1] = v; + pure[2] = 0; + break; + case 1: + pure[0] = w; + pure[1] = 1; + pure[2] = 0; + break; + case 2: + pure[0] = 0; + pure[1] = 1; + pure[2] = v; + break; + case 3: + pure[0] = 0; + pure[1] = w; + pure[2] = 1; + break; + case 4: + pure[0] = v; + pure[1] = 0; + pure[2] = 1; + break; + default: + pure[0] = 1; + pure[1] = 0; + pure[2] = w; + } + mg = (1.0 - c) * g; + return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255]; +}; +convert.hcg.hsv = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var v = c + g * (1.0 - c); + var f = 0; + if (v > 0.0) { + f = c / v; + } + return [hcg[0], f * 100, v * 100]; +}; +convert.hcg.hsl = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var l = g * (1.0 - c) + 0.5 * c; + var s = 0; + if (l > 0.0 && l < 0.5) { + s = c / (2 * l); + } else if (l >= 0.5 && l < 1.0) { + s = c / (2 * (1 - l)); + } + return [hcg[0], s * 100, l * 100]; +}; +convert.hcg.hwb = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var v = c + g * (1.0 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; +}; +convert.hwb.hcg = function (hwb) { + var w = hwb[1] / 100; + var b = hwb[2] / 100; + var v = 1 - b; + var c = v - w; + var g = 0; + if (c < 1) { + g = (v - c) / (1 - c); + } + return [hwb[0], c * 100, g * 100]; +}; +convert.apple.rgb = function (apple) { + return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255]; +}; +convert.rgb.apple = function (rgb) { + return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535]; +}; +convert.gray.rgb = function (args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; +}; +convert.gray.hsl = convert.gray.hsv = function (args) { + return [0, 0, args[0]]; +}; +convert.gray.hwb = function (gray) { + return [0, 100, gray[0]]; +}; +convert.gray.cmyk = function (gray) { + return [0, 0, 0, gray[0]]; +}; +convert.gray.lab = function (gray) { + return [gray[0], 0, 0]; +}; +convert.gray.hex = function (gray) { + var val = Math.round(gray[0] / 100 * 255) & 0xFF; + var integer = (val << 16) + (val << 8) + val; + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; +convert.rgb.gray = function (rgb) { + var val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; +}; + +/***/ }), + +/***/ "./node_modules/color-convert/index.js": +/*!*********************************************!*\ + !*** ./node_modules/color-convert/index.js ***! + \*********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +var conversions = __webpack_require__(/*! ./conversions */ "./node_modules/color-convert/conversions.js"); +var route = __webpack_require__(/*! ./route */ "./node_modules/color-convert/route.js"); +var convert = {}; +var models = Object.keys(conversions); +function wrapRaw(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + return fn(args); + }; + + // preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + return wrappedFn; +} +function wrapRounded(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + var result = fn(args); + + // we're assuming the result is an array here. + // see notice in conversions.js; don't use box types + // in conversion functions. + if (typeof result === 'object') { + for (var len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); + } + } + return result; + }; + + // preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + return wrappedFn; +} +models.forEach(function (fromModel) { + convert[fromModel] = {}; + Object.defineProperty(convert[fromModel], 'channels', { + value: conversions[fromModel].channels + }); + Object.defineProperty(convert[fromModel], 'labels', { + value: conversions[fromModel].labels + }); + var routes = route(fromModel); + var routeModels = Object.keys(routes); + routeModels.forEach(function (toModel) { + var fn = routes[toModel]; + convert[fromModel][toModel] = wrapRounded(fn); + convert[fromModel][toModel].raw = wrapRaw(fn); + }); +}); +module.exports = convert; + +/***/ }), + +/***/ "./node_modules/color-convert/route.js": +/*!*********************************************!*\ + !*** ./node_modules/color-convert/route.js ***! + \*********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +var conversions = __webpack_require__(/*! ./conversions */ "./node_modules/color-convert/conversions.js"); + +/* + this function routes a model to all other models. + + all functions that are routed have a property `.conversion` attached + to the returned synthetic function. This property is an array + of strings, each with the steps in between the 'from' and 'to' + color models (inclusive). + + conversions that are not possible simply are not included. +*/ + +function buildGraph() { + var graph = {}; + // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + var models = Object.keys(conversions); + for (var len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + return graph; +} + +// https://en.wikipedia.org/wiki/Breadth-first_search +function deriveBFS(fromModel) { + var graph = buildGraph(); + var queue = [fromModel]; // unshift -> queue -> pop + + graph[fromModel].distance = 0; + while (queue.length) { + var current = queue.pop(); + var adjacents = Object.keys(conversions[current]); + for (var len = adjacents.length, i = 0; i < len; i++) { + var adjacent = adjacents[i]; + var node = graph[adjacent]; + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } + return graph; +} +function link(from, to) { + return function (args) { + return to(from(args)); + }; +} +function wrapConversion(toModel, graph) { + var path = [graph[toModel].parent, toModel]; + var fn = conversions[graph[toModel].parent][toModel]; + var cur = graph[toModel].parent; + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link(conversions[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + fn.conversion = path; + return fn; +} +module.exports = function (fromModel) { + var graph = deriveBFS(fromModel); + var conversion = {}; + var models = Object.keys(graph); + for (var len = models.length, i = 0; i < len; i++) { + var toModel = models[i]; + var node = graph[toModel]; + if (node.parent === null) { + // no possible conversion, or this node is the source model. + continue; + } + conversion[toModel] = wrapConversion(toModel, graph); + } + return conversion; +}; + +/***/ }), + +/***/ "./node_modules/color-name/index.js": +/*!******************************************!*\ + !*** ./node_modules/color-name/index.js ***! + \******************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] +}; + +/***/ }), + +/***/ "./node_modules/css-loader/dist/runtime/api.js": +/*!*****************************************************!*\ + !*** ./node_modules/css-loader/dist/runtime/api.js ***! + \*****************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +// css base code, injected by the css-loader +module.exports = function (useSourceMap) { + var list = []; // return the list of modules as css string + + list.toString = function toString() { + return this.map(function (item) { + var content = cssWithMappingToString(item, useSourceMap); + if (item[2]) { + return '@media ' + item[2] + '{' + content + '}'; + } else { + return content; + } + }).join(''); + }; // import a list of modules into the list + + list.i = function (modules, mediaQuery) { + if (typeof modules === 'string') { + modules = [[null, modules, '']]; + } + var alreadyImportedModules = {}; + for (var i = 0; i < this.length; i++) { + var id = this[i][0]; + if (id != null) { + alreadyImportedModules[id] = true; + } + } + for (i = 0; i < modules.length; i++) { + var item = modules[i]; // skip already imported module + // this implementation is not 100% perfect for weird media query combinations + // when a module is imported multiple times with different media queries. + // I hope this will never occur (Hey this way we have smaller bundles) + + if (item[0] == null || !alreadyImportedModules[item[0]]) { + if (mediaQuery && !item[2]) { + item[2] = mediaQuery; + } else if (mediaQuery) { + item[2] = '(' + item[2] + ') and (' + mediaQuery + ')'; + } + list.push(item); + } + } + }; + return list; +}; +function cssWithMappingToString(item, useSourceMap) { + var content = item[1] || ''; + var cssMapping = item[3]; + if (!cssMapping) { + return content; + } + if (useSourceMap && typeof btoa === 'function') { + var sourceMapping = toComment(cssMapping); + var sourceURLs = cssMapping.sources.map(function (source) { + return '/*# sourceURL=' + cssMapping.sourceRoot + source + ' */'; + }); + return [content].concat(sourceURLs).concat([sourceMapping]).join('\n'); + } + return [content].join('\n'); +} // Adapted from convert-source-map (MIT) + +function toComment(sourceMap) { + // eslint-disable-next-line no-undef + var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))); + var data = 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + base64; + return '/*# ' + data + ' */'; +} + +/***/ }), + +/***/ "./node_modules/css-loader/dist/runtime/url-escape.js": +/*!************************************************************!*\ + !*** ./node_modules/css-loader/dist/runtime/url-escape.js ***! + \************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = function escape(url, needQuotes) { + if (typeof url !== 'string') { + return url; + } // If url is already wrapped in quotes, remove them + + if (/^['"].*['"]$/.test(url)) { + url = url.slice(1, -1); + } // Should url be wrapped? + // See https://drafts.csswg.org/css-values-3/#urls + + if (/["'() \t\n]/.test(url) || needQuotes) { + return '"' + url.replace(/"/g, '\\"').replace(/\n/g, '\\n') + '"'; + } + return url; +}; + +/***/ }), + +/***/ "./node_modules/escape-string-regexp/index.js": +/*!****************************************************!*\ + !*** ./node_modules/escape-string-regexp/index.js ***! + \****************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; +module.exports = function (str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + return str.replace(matchOperatorsRe, '\\$&'); +}; + +/***/ }), + +/***/ "./node_modules/function-bind/implementation.js": +/*!******************************************************!*\ + !*** ./node_modules/function-bind/implementation.js ***! + \******************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/* eslint no-invalid-this: 1 */ +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var slice = Array.prototype.slice; +var toStr = Object.prototype.toString; +var funcType = '[object Function]'; +module.exports = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.call(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slice.call(arguments, 1); + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply(this, args.concat(slice.call(arguments))); + if (Object(result) === result) { + return result; + } + return this; + } else { + return target.apply(that, args.concat(slice.call(arguments))); + } + }; + var boundLength = Math.max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs.push('$' + i); + } + bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + return bound; +}; + +/***/ }), + +/***/ "./node_modules/function-bind/index.js": +/*!*********************************************!*\ + !*** ./node_modules/function-bind/index.js ***! + \*********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var implementation = __webpack_require__(/*! ./implementation */ "./node_modules/function-bind/implementation.js"); +module.exports = Function.prototype.bind || implementation; + +/***/ }), + +/***/ "./node_modules/get-intrinsic/index.js": +/*!*********************************************!*\ + !*** ./node_modules/get-intrinsic/index.js ***! + \*********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var undefined; +var $SyntaxError = SyntaxError; +var $Function = Function; +var $TypeError = TypeError; + +// eslint-disable-next-line consistent-return +var getEvalledConstructor = function (expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); + } catch (e) {} +}; +var $gOPD = Object.getOwnPropertyDescriptor; +if ($gOPD) { + try { + $gOPD({}, ''); + } catch (e) { + $gOPD = null; // this is IE 8, which has a broken gOPD + } +} + +var throwTypeError = function () { + throw new $TypeError(); +}; +var ThrowTypeError = $gOPD ? function () { + try { + // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties + arguments.callee; // IE 8 does not throw here + return throwTypeError; + } catch (calleeThrows) { + try { + // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') + return $gOPD(arguments, 'callee').get; + } catch (gOPDthrows) { + return throwTypeError; + } + } +}() : throwTypeError; +var hasSymbols = __webpack_require__(/*! has-symbols */ "./node_modules/has-symbols/index.js")(); +var hasProto = __webpack_require__(/*! has-proto */ "./node_modules/has-proto/index.js")(); +var getProto = Object.getPrototypeOf || (hasProto ? function (x) { + return x.__proto__; +} // eslint-disable-line no-proto +: null); +var needsEval = {}; +var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array); +var INTRINSICS = { + '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, + '%Array%': Array, + '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, + '%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined, + '%AsyncFromSyncIteratorPrototype%': undefined, + '%AsyncFunction%': needsEval, + '%AsyncGenerator%': needsEval, + '%AsyncGeneratorFunction%': needsEval, + '%AsyncIteratorPrototype%': needsEval, + '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, + '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, + '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array, + '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array, + '%Boolean%': Boolean, + '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, + '%Date%': Date, + '%decodeURI%': decodeURI, + '%decodeURIComponent%': decodeURIComponent, + '%encodeURI%': encodeURI, + '%encodeURIComponent%': encodeURIComponent, + '%Error%': Error, + '%eval%': eval, + // eslint-disable-line no-eval + '%EvalError%': EvalError, + '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, + '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, + '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, + '%Function%': $Function, + '%GeneratorFunction%': needsEval, + '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, + '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, + '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, + '%isFinite%': isFinite, + '%isNaN%': isNaN, + '%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined, + '%JSON%': typeof JSON === 'object' ? JSON : undefined, + '%Map%': typeof Map === 'undefined' ? undefined : Map, + '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()), + '%Math%': Math, + '%Number%': Number, + '%Object%': Object, + '%parseFloat%': parseFloat, + '%parseInt%': parseInt, + '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, + '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, + '%RangeError%': RangeError, + '%ReferenceError%': ReferenceError, + '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, + '%RegExp%': RegExp, + '%Set%': typeof Set === 'undefined' ? undefined : Set, + '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()), + '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, + '%String%': String, + '%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined, + '%Symbol%': hasSymbols ? Symbol : undefined, + '%SyntaxError%': $SyntaxError, + '%ThrowTypeError%': ThrowTypeError, + '%TypedArray%': TypedArray, + '%TypeError%': $TypeError, + '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, + '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, + '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, + '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, + '%URIError%': URIError, + '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, + '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, + '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet +}; +if (getProto) { + try { + null.error; // eslint-disable-line no-unused-expressions + } catch (e) { + // https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229 + var errorProto = getProto(getProto(e)); + INTRINSICS['%Error.prototype%'] = errorProto; + } +} +var doEval = function doEval(name) { + var value; + if (name === '%AsyncFunction%') { + value = getEvalledConstructor('async function () {}'); + } else if (name === '%GeneratorFunction%') { + value = getEvalledConstructor('function* () {}'); + } else if (name === '%AsyncGeneratorFunction%') { + value = getEvalledConstructor('async function* () {}'); + } else if (name === '%AsyncGenerator%') { + var fn = doEval('%AsyncGeneratorFunction%'); + if (fn) { + value = fn.prototype; + } + } else if (name === '%AsyncIteratorPrototype%') { + var gen = doEval('%AsyncGenerator%'); + if (gen && getProto) { + value = getProto(gen.prototype); + } + } + INTRINSICS[name] = value; + return value; +}; +var LEGACY_ALIASES = { + '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], + '%ArrayPrototype%': ['Array', 'prototype'], + '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], + '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], + '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], + '%ArrayProto_values%': ['Array', 'prototype', 'values'], + '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], + '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], + '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], + '%BooleanPrototype%': ['Boolean', 'prototype'], + '%DataViewPrototype%': ['DataView', 'prototype'], + '%DatePrototype%': ['Date', 'prototype'], + '%ErrorPrototype%': ['Error', 'prototype'], + '%EvalErrorPrototype%': ['EvalError', 'prototype'], + '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], + '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], + '%FunctionPrototype%': ['Function', 'prototype'], + '%Generator%': ['GeneratorFunction', 'prototype'], + '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], + '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], + '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], + '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], + '%JSONParse%': ['JSON', 'parse'], + '%JSONStringify%': ['JSON', 'stringify'], + '%MapPrototype%': ['Map', 'prototype'], + '%NumberPrototype%': ['Number', 'prototype'], + '%ObjectPrototype%': ['Object', 'prototype'], + '%ObjProto_toString%': ['Object', 'prototype', 'toString'], + '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], + '%PromisePrototype%': ['Promise', 'prototype'], + '%PromiseProto_then%': ['Promise', 'prototype', 'then'], + '%Promise_all%': ['Promise', 'all'], + '%Promise_reject%': ['Promise', 'reject'], + '%Promise_resolve%': ['Promise', 'resolve'], + '%RangeErrorPrototype%': ['RangeError', 'prototype'], + '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], + '%RegExpPrototype%': ['RegExp', 'prototype'], + '%SetPrototype%': ['Set', 'prototype'], + '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], + '%StringPrototype%': ['String', 'prototype'], + '%SymbolPrototype%': ['Symbol', 'prototype'], + '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], + '%TypedArrayPrototype%': ['TypedArray', 'prototype'], + '%TypeErrorPrototype%': ['TypeError', 'prototype'], + '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], + '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], + '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], + '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], + '%URIErrorPrototype%': ['URIError', 'prototype'], + '%WeakMapPrototype%': ['WeakMap', 'prototype'], + '%WeakSetPrototype%': ['WeakSet', 'prototype'] +}; +var bind = __webpack_require__(/*! function-bind */ "./node_modules/function-bind/index.js"); +var hasOwn = __webpack_require__(/*! has */ "./node_modules/has/src/index.js"); +var $concat = bind.call(Function.call, Array.prototype.concat); +var $spliceApply = bind.call(Function.apply, Array.prototype.splice); +var $replace = bind.call(Function.call, String.prototype.replace); +var $strSlice = bind.call(Function.call, String.prototype.slice); +var $exec = bind.call(Function.call, RegExp.prototype.exec); + +/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ +var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; +var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ +var stringToPath = function stringToPath(string) { + var first = $strSlice(string, 0, 1); + var last = $strSlice(string, -1); + if (first === '%' && last !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); + } else if (last === '%' && first !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); + } + var result = []; + $replace(string, rePropName, function (match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; + }); + return result; +}; +/* end adaptation */ + +var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = '%' + alias[0] + '%'; + } + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === 'undefined' && !allowMissing) { + throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); + } + return { + alias: alias, + name: intrinsicName, + value: value + }; + } + throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); +}; +module.exports = function GetIntrinsic(name, allowMissing) { + if (typeof name !== 'string' || name.length === 0) { + throw new $TypeError('intrinsic name must be a non-empty string'); + } + if (arguments.length > 1 && typeof allowMissing !== 'boolean') { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } + if ($exec(/^%?[^%]*%?$/, name) === null) { + throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); + } + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; + var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ((first === '"' || first === "'" || first === '`' || last === '"' || last === "'" || last === '`') && first !== last) { + throw new $SyntaxError('property names with quotes must have matching quotes'); + } + if (part === 'constructor' || !isOwn) { + skipFurtherCaching = true; + } + intrinsicBaseName += '.' + part; + intrinsicRealName = '%' + intrinsicBaseName + '%'; + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); + } + return void undefined; + } + if ($gOPD && i + 1 >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + + // By convention, when a data property is converted to an accessor + // property to emulate a data property that does not suffer from + // the override mistake, that accessor's getter is marked with + // an `originalValue` property. Here, when we detect this, we + // uphold the illusion by pretending to see that original data + // property, i.e., returning the value rather than the getter + // itself. + if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn(value, part); + value = value[part]; + } + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; +}; + +/***/ }), + +/***/ "./node_modules/has-proto/index.js": +/*!*****************************************!*\ + !*** ./node_modules/has-proto/index.js ***! + \*****************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var test = { + foo: {} +}; +var $Object = Object; +module.exports = function hasProto() { + return { + __proto__: test + }.foo === test.foo && !({ + __proto__: null + } instanceof $Object); +}; + +/***/ }), + +/***/ "./node_modules/has-symbols/index.js": +/*!*******************************************!*\ + !*** ./node_modules/has-symbols/index.js ***! + \*******************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var origSymbol = typeof Symbol !== 'undefined' && Symbol; +var hasSymbolSham = __webpack_require__(/*! ./shams */ "./node_modules/has-symbols/shams.js"); +module.exports = function hasNativeSymbols() { + if (typeof origSymbol !== 'function') { + return false; + } + if (typeof Symbol !== 'function') { + return false; + } + if (typeof origSymbol('foo') !== 'symbol') { + return false; + } + if (typeof Symbol('bar') !== 'symbol') { + return false; + } + return hasSymbolSham(); +}; + +/***/ }), + +/***/ "./node_modules/has-symbols/shams.js": +/*!*******************************************!*\ + !*** ./node_modules/has-symbols/shams.js ***! + \*******************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/* eslint complexity: [2, 18], max-statements: [2, 33] */ +module.exports = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { + return false; + } + if (typeof Symbol.iterator === 'symbol') { + return true; + } + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { + return false; + } + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { + return false; + } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { + return false; + } + + // temp disabled per https://github.com/ljharb/object.assign/issues/17 + // if (sym instanceof Symbol) { return false; } + // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + // if (!(symObj instanceof Symbol)) { return false; } + + // if (typeof Symbol.prototype.toString !== 'function') { return false; } + // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } + + var symVal = 42; + obj[sym] = symVal; + for (sym in obj) { + return false; + } // eslint-disable-line no-restricted-syntax, no-unreachable-loop + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { + return false; + } + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { + return false; + } + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { + return false; + } + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { + return false; + } + if (typeof Object.getOwnPropertyDescriptor === 'function') { + var descriptor = Object.getOwnPropertyDescriptor(obj, sym); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { + return false; + } + } + return true; +}; + +/***/ }), + +/***/ "./node_modules/has/src/index.js": +/*!***************************************!*\ + !*** ./node_modules/has/src/index.js ***! + \***************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var hasOwnProperty = {}.hasOwnProperty; +var call = Function.prototype.call; +module.exports = call.bind ? call.bind(hasOwnProperty) : function (O, P) { + return call.call(hasOwnProperty, O, P); +}; + +/***/ }), + +/***/ "./node_modules/inherits/inherits_browser.js": +/*!***************************************************!*\ + !*** ./node_modules/inherits/inherits_browser.js ***! + \***************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + }; +} + +/***/ }), + +/***/ "./node_modules/json3/lib/json3.js": +/*!*****************************************!*\ + !*** ./node_modules/json3/lib/json3.js ***! + \*****************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(module, global) {var __WEBPACK_AMD_DEFINE_RESULT__;/*! JSON v3.3.2 | https://bestiejs.github.io/json3 | Copyright 2012-2015, Kit Cambridge, Benjamin Tan | http://kit.mit-license.org */ +; +(function () { + // Detect the `define` function exposed by asynchronous module loaders. The + // strict `define` check is necessary for compatibility with `r.js`. + var isLoader = true && __webpack_require__(/*! !webpack amd options */ "./node_modules/webpack/buildin/amd-options.js"); + + // A set of types used to distinguish objects from primitives. + var objectTypes = { + "function": true, + "object": true + }; + + // Detect the `exports` object exposed by CommonJS implementations. + var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; + + // Use the `global` object exposed by Node (including Browserify via + // `insert-module-globals`), Narwhal, and Ringo as the default context, + // and the `window` object in browsers. Rhino exports a `global` function + // instead. + var root = objectTypes[typeof window] && window || this, + freeGlobal = freeExports && objectTypes[typeof module] && module && !module.nodeType && typeof global == "object" && global; + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal)) { + root = freeGlobal; + } + + // Public: Initializes JSON 3 using the given `context` object, attaching the + // `stringify` and `parse` functions to the specified `exports` object. + function runInContext(context, exports) { + context || (context = root.Object()); + exports || (exports = root.Object()); + + // Native constructor aliases. + var Number = context.Number || root.Number, + String = context.String || root.String, + Object = context.Object || root.Object, + Date = context.Date || root.Date, + SyntaxError = context.SyntaxError || root.SyntaxError, + TypeError = context.TypeError || root.TypeError, + Math = context.Math || root.Math, + nativeJSON = context.JSON || root.JSON; + + // Delegate to the native `stringify` and `parse` implementations. + if (typeof nativeJSON == "object" && nativeJSON) { + exports.stringify = nativeJSON.stringify; + exports.parse = nativeJSON.parse; + } + + // Convenience aliases. + var objectProto = Object.prototype, + getClass = objectProto.toString, + isProperty = objectProto.hasOwnProperty, + undefined; + + // Internal: Contains `try...catch` logic used by other functions. + // This prevents other functions from being deoptimized. + function attempt(func, errorFunc) { + try { + func(); + } catch (exception) { + if (errorFunc) { + errorFunc(); + } + } + } + + // Test the `Date#getUTC*` methods. Based on work by @Yaffle. + var isExtended = new Date(-3509827334573292); + attempt(function () { + // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical + // results for certain dates in Opera >= 10.53. + isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 && isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708; + }); + + // Internal: Determines whether the native `JSON.stringify` and `parse` + // implementations are spec-compliant. Based on work by Ken Snyder. + function has(name) { + if (has[name] != null) { + // Return cached feature test result. + return has[name]; + } + var isSupported; + if (name == "bug-string-char-index") { + // IE <= 7 doesn't support accessing string characters using square + // bracket notation. IE 8 only supports this for primitives. + isSupported = "a"[0] != "a"; + } else if (name == "json") { + // Indicates whether both `JSON.stringify` and `JSON.parse` are + // supported. + isSupported = has("json-stringify") && has("date-serialization") && has("json-parse"); + } else if (name == "date-serialization") { + // Indicates whether `Date`s can be serialized accurately by `JSON.stringify`. + isSupported = has("json-stringify") && isExtended; + if (isSupported) { + var stringify = exports.stringify; + attempt(function () { + isSupported = + // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly + // serialize extended years. + stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' && + // The milliseconds are optional in ES 5, but required in 5.1. + stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' && + // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative + // four-digit years instead of six-digit years. Credits: @Yaffle. + stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' && + // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond + // values less than 1000. Credits: @Yaffle. + stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"'; + }); + } + } else { + var value, + serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}'; + // Test `JSON.stringify`. + if (name == "json-stringify") { + var stringify = exports.stringify, + stringifySupported = typeof stringify == "function"; + if (stringifySupported) { + // A test function object with a custom `toJSON` method. + (value = function () { + return 1; + }).toJSON = value; + attempt(function () { + stringifySupported = + // Firefox 3.1b1 and b2 serialize string, number, and boolean + // primitives as object literals. + stringify(0) === "0" && + // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object + // literals. + stringify(new Number()) === "0" && stringify(new String()) == '""' && + // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or + // does not define a canonical JSON representation (this applies to + // objects with `toJSON` properties as well, *unless* they are nested + // within an object or array). + stringify(getClass) === undefined && + // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and + // FF 3.1b3 pass this test. + stringify(undefined) === undefined && + // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s, + // respectively, if the value is omitted entirely. + stringify() === undefined && + // FF 3.1b1, 2 throw an error if the given value is not a number, + // string, array, object, Boolean, or `null` literal. This applies to + // objects with custom `toJSON` methods as well, unless they are nested + // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON` + // methods entirely. + stringify(value) === "1" && stringify([value]) == "[1]" && + // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of + // `"[null]"`. + stringify([undefined]) == "[null]" && + // YUI 3.0.0b1 fails to serialize `null` literals. + stringify(null) == "null" && + // FF 3.1b1, 2 halts serialization if an array contains a function: + // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3 + // elides non-JSON values from objects and arrays, unless they + // define custom `toJSON` methods. + stringify([undefined, getClass, null]) == "[null,null,null]" && + // Simple serialization test. FF 3.1b1 uses Unicode escape sequences + // where character escape codes are expected (e.g., `\b` => `\u0008`). + stringify({ + "a": [value, true, false, null, "\x00\b\n\f\r\t"] + }) == serialized && + // FF 3.1b1 and b2 ignore the `filter` and `width` arguments. + stringify(null, value) === "1" && stringify([1, 2], null, 1) == "[\n 1,\n 2\n]"; + }, function () { + stringifySupported = false; + }); + } + isSupported = stringifySupported; + } + // Test `JSON.parse`. + if (name == "json-parse") { + var parse = exports.parse, + parseSupported; + if (typeof parse == "function") { + attempt(function () { + // FF 3.1b1, b2 will throw an exception if a bare literal is provided. + // Conforming implementations should also coerce the initial argument to + // a string prior to parsing. + if (parse("0") === 0 && !parse(false)) { + // Simple parsing test. + value = parse(serialized); + parseSupported = value["a"].length == 5 && value["a"][0] === 1; + if (parseSupported) { + attempt(function () { + // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings. + parseSupported = !parse('"\t"'); + }); + if (parseSupported) { + attempt(function () { + // FF 4.0 and 4.0.1 allow leading `+` signs and leading + // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow + // certain octal literals. + parseSupported = parse("01") !== 1; + }); + } + if (parseSupported) { + attempt(function () { + // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal + // points. These environments, along with FF 3.1b1 and 2, + // also allow trailing commas in JSON objects and arrays. + parseSupported = parse("1.") !== 1; + }); + } + } + } + }, function () { + parseSupported = false; + }); + } + isSupported = parseSupported; + } + } + return has[name] = !!isSupported; + } + has["bug-string-char-index"] = has["date-serialization"] = has["json"] = has["json-stringify"] = has["json-parse"] = null; + if (!has("json")) { + // Common `[[Class]]` name aliases. + var functionClass = "[object Function]", + dateClass = "[object Date]", + numberClass = "[object Number]", + stringClass = "[object String]", + arrayClass = "[object Array]", + booleanClass = "[object Boolean]"; + + // Detect incomplete support for accessing string characters by index. + var charIndexBuggy = has("bug-string-char-index"); + + // Internal: Normalizes the `for...in` iteration algorithm across + // environments. Each enumerated key is yielded to a `callback` function. + var forOwn = function (object, callback) { + var size = 0, + Properties, + dontEnums, + property; + + // Tests for bugs in the current environment's `for...in` algorithm. The + // `valueOf` property inherits the non-enumerable flag from + // `Object.prototype` in older versions of IE, Netscape, and Mozilla. + (Properties = function () { + this.valueOf = 0; + }).prototype.valueOf = 0; + + // Iterate over a new instance of the `Properties` class. + dontEnums = new Properties(); + for (property in dontEnums) { + // Ignore all properties inherited from `Object.prototype`. + if (isProperty.call(dontEnums, property)) { + size++; + } + } + Properties = dontEnums = null; + + // Normalize the iteration algorithm. + if (!size) { + // A list of non-enumerable properties inherited from `Object.prototype`. + dontEnums = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"]; + // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable + // properties. + forOwn = function (object, callback) { + var isFunction = getClass.call(object) == functionClass, + property, + length; + var hasProperty = !isFunction && typeof object.constructor != "function" && objectTypes[typeof object.hasOwnProperty] && object.hasOwnProperty || isProperty; + for (property in object) { + // Gecko <= 1.0 enumerates the `prototype` property of functions under + // certain conditions; IE does not. + if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) { + callback(property); + } + } + // Manually invoke the callback for each non-enumerable property. + for (length = dontEnums.length; property = dontEnums[--length];) { + if (hasProperty.call(object, property)) { + callback(property); + } + } + }; + } else { + // No bugs detected; use the standard `for...in` algorithm. + forOwn = function (object, callback) { + var isFunction = getClass.call(object) == functionClass, + property, + isConstructor; + for (property in object) { + if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) { + callback(property); + } + } + // Manually invoke the callback for the `constructor` property due to + // cross-environment inconsistencies. + if (isConstructor || isProperty.call(object, property = "constructor")) { + callback(property); + } + }; + } + return forOwn(object, callback); + }; + + // Public: Serializes a JavaScript `value` as a JSON string. The optional + // `filter` argument may specify either a function that alters how object and + // array members are serialized, or an array of strings and numbers that + // indicates which properties should be serialized. The optional `width` + // argument may be either a string or number that specifies the indentation + // level of the output. + if (!has("json-stringify") && !has("date-serialization")) { + // Internal: A map of control characters and their escaped equivalents. + var Escapes = { + 92: "\\\\", + 34: '\\"', + 8: "\\b", + 12: "\\f", + 10: "\\n", + 13: "\\r", + 9: "\\t" + }; + + // Internal: Converts `value` into a zero-padded string such that its + // length is at least equal to `width`. The `width` must be <= 6. + var leadingZeroes = "000000"; + var toPaddedString = function (width, value) { + // The `|| 0` expression is necessary to work around a bug in + // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`. + return (leadingZeroes + (value || 0)).slice(-width); + }; + + // Internal: Serializes a date object. + var serializeDate = function (value) { + var getData, year, month, date, time, hours, minutes, seconds, milliseconds; + // Define additional utility methods if the `Date` methods are buggy. + if (!isExtended) { + var floor = Math.floor; + // A mapping between the months of the year and the number of days between + // January 1st and the first of the respective month. + var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; + // Internal: Calculates the number of days between the Unix epoch and the + // first day of the given month. + var getDay = function (year, month) { + return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400); + }; + getData = function (value) { + // Manually compute the year, month, date, hours, minutes, + // seconds, and milliseconds if the `getUTC*` methods are + // buggy. Adapted from @Yaffle's `date-shim` project. + date = floor(value / 864e5); + for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++); + for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++); + date = 1 + date - getDay(year, month); + // The `time` value specifies the time within the day (see ES + // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used + // to compute `A modulo B`, as the `%` operator does not + // correspond to the `modulo` operation for negative numbers. + time = (value % 864e5 + 864e5) % 864e5; + // The hours, minutes, seconds, and milliseconds are obtained by + // decomposing the time within the day. See section 15.9.1.10. + hours = floor(time / 36e5) % 24; + minutes = floor(time / 6e4) % 60; + seconds = floor(time / 1e3) % 60; + milliseconds = time % 1e3; + }; + } else { + getData = function (value) { + year = value.getUTCFullYear(); + month = value.getUTCMonth(); + date = value.getUTCDate(); + hours = value.getUTCHours(); + minutes = value.getUTCMinutes(); + seconds = value.getUTCSeconds(); + milliseconds = value.getUTCMilliseconds(); + }; + } + serializeDate = function (value) { + if (value > -1 / 0 && value < 1 / 0) { + // Dates are serialized according to the `Date#toJSON` method + // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15 + // for the ISO 8601 date time string format. + getData(value); + // Serialize extended years correctly. + value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) + "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) + + // Months, dates, hours, minutes, and seconds should have two + // digits; milliseconds should have three. + "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) + + // Milliseconds are optional in ES 5.0, but required in 5.1. + "." + toPaddedString(3, milliseconds) + "Z"; + year = month = date = hours = minutes = seconds = milliseconds = null; + } else { + value = null; + } + return value; + }; + return serializeDate(value); + }; + + // For environments with `JSON.stringify` but buggy date serialization, + // we override the native `Date#toJSON` implementation with a + // spec-compliant one. + if (has("json-stringify") && !has("date-serialization")) { + // Internal: the `Date#toJSON` implementation used to override the native one. + function dateToJSON(key) { + return serializeDate(this); + } + + // Public: `JSON.stringify`. See ES 5.1 section 15.12.3. + var nativeStringify = exports.stringify; + exports.stringify = function (source, filter, width) { + var nativeToJSON = Date.prototype.toJSON; + Date.prototype.toJSON = dateToJSON; + var result = nativeStringify(source, filter, width); + Date.prototype.toJSON = nativeToJSON; + return result; + }; + } else { + // Internal: Double-quotes a string `value`, replacing all ASCII control + // characters (characters with code unit values between 0 and 31) with + // their escaped equivalents. This is an implementation of the + // `Quote(value)` operation defined in ES 5.1 section 15.12.3. + var unicodePrefix = "\\u00"; + var escapeChar = function (character) { + var charCode = character.charCodeAt(0), + escaped = Escapes[charCode]; + if (escaped) { + return escaped; + } + return unicodePrefix + toPaddedString(2, charCode.toString(16)); + }; + var reEscape = /[\x00-\x1f\x22\x5c]/g; + var quote = function (value) { + reEscape.lastIndex = 0; + return '"' + (reEscape.test(value) ? value.replace(reEscape, escapeChar) : value) + '"'; + }; + + // Internal: Recursively serializes an object. Implements the + // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations. + var serialize = function (property, object, callback, properties, whitespace, indentation, stack) { + var value, type, className, results, element, index, length, prefix, result; + attempt(function () { + // Necessary for host object support. + value = object[property]; + }); + if (typeof value == "object" && value) { + if (value.getUTCFullYear && getClass.call(value) == dateClass && value.toJSON === Date.prototype.toJSON) { + value = serializeDate(value); + } else if (typeof value.toJSON == "function") { + value = value.toJSON(property); + } + } + if (callback) { + // If a replacement function was provided, call it to obtain the value + // for serialization. + value = callback.call(object, property, value); + } + // Exit early if value is `undefined` or `null`. + if (value == undefined) { + return value === undefined ? value : "null"; + } + type = typeof value; + // Only call `getClass` if the value is an object. + if (type == "object") { + className = getClass.call(value); + } + switch (className || type) { + case "boolean": + case booleanClass: + // Booleans are represented literally. + return "" + value; + case "number": + case numberClass: + // JSON numbers must be finite. `Infinity` and `NaN` are serialized as + // `"null"`. + return value > -1 / 0 && value < 1 / 0 ? "" + value : "null"; + case "string": + case stringClass: + // Strings are double-quoted and escaped. + return quote("" + value); + } + // Recursively serialize objects and arrays. + if (typeof value == "object") { + // Check for cyclic structures. This is a linear search; performance + // is inversely proportional to the number of unique nested objects. + for (length = stack.length; length--;) { + if (stack[length] === value) { + // Cyclic structures cannot be serialized by `JSON.stringify`. + throw TypeError(); + } + } + // Add the object to the stack of traversed objects. + stack.push(value); + results = []; + // Save the current indentation level and indent one additional level. + prefix = indentation; + indentation += whitespace; + if (className == arrayClass) { + // Recursively serialize array elements. + for (index = 0, length = value.length; index < length; index++) { + element = serialize(index, value, callback, properties, whitespace, indentation, stack); + results.push(element === undefined ? "null" : element); + } + result = results.length ? whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : "[" + results.join(",") + "]" : "[]"; + } else { + // Recursively serialize object members. Members are selected from + // either a user-specified list of property names, or the object + // itself. + forOwn(properties || value, function (property) { + var element = serialize(property, value, callback, properties, whitespace, indentation, stack); + if (element !== undefined) { + // According to ES 5.1 section 15.12.3: "If `gap` {whitespace} + // is not the empty string, let `member` {quote(property) + ":"} + // be the concatenation of `member` and the `space` character." + // The "`space` character" refers to the literal space + // character, not the `space` {width} argument provided to + // `JSON.stringify`. + results.push(quote(property) + ":" + (whitespace ? " " : "") + element); + } + }); + result = results.length ? whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : "{" + results.join(",") + "}" : "{}"; + } + // Remove the object from the traversed object stack. + stack.pop(); + return result; + } + }; + + // Public: `JSON.stringify`. See ES 5.1 section 15.12.3. + exports.stringify = function (source, filter, width) { + var whitespace, callback, properties, className; + if (objectTypes[typeof filter] && filter) { + className = getClass.call(filter); + if (className == functionClass) { + callback = filter; + } else if (className == arrayClass) { + // Convert the property names array into a makeshift set. + properties = {}; + for (var index = 0, length = filter.length, value; index < length;) { + value = filter[index++]; + className = getClass.call(value); + if (className == "[object String]" || className == "[object Number]") { + properties[value] = 1; + } + } + } + } + if (width) { + className = getClass.call(width); + if (className == numberClass) { + // Convert the `width` to an integer and create a string containing + // `width` number of space characters. + if ((width -= width % 1) > 0) { + if (width > 10) { + width = 10; + } + for (whitespace = ""; whitespace.length < width;) { + whitespace += " "; + } + } + } else if (className == stringClass) { + whitespace = width.length <= 10 ? width : width.slice(0, 10); + } + } + // Opera <= 7.54u2 discards the values associated with empty string keys + // (`""`) only if they are used directly within an object member list + // (e.g., `!("" in { "": 1})`). + return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []); + }; + } + } + + // Public: Parses a JSON source string. + if (!has("json-parse")) { + var fromCharCode = String.fromCharCode; + + // Internal: A map of escaped control characters and their unescaped + // equivalents. + var Unescapes = { + 92: "\\", + 34: '"', + 47: "/", + 98: "\b", + 116: "\t", + 110: "\n", + 102: "\f", + 114: "\r" + }; + + // Internal: Stores the parser state. + var Index, Source; + + // Internal: Resets the parser state and throws a `SyntaxError`. + var abort = function () { + Index = Source = null; + throw SyntaxError(); + }; + + // Internal: Returns the next token, or `"$"` if the parser has reached + // the end of the source string. A token may be a string, number, `null` + // literal, or Boolean literal. + var lex = function () { + var source = Source, + length = source.length, + value, + begin, + position, + isSigned, + charCode; + while (Index < length) { + charCode = source.charCodeAt(Index); + switch (charCode) { + case 9: + case 10: + case 13: + case 32: + // Skip whitespace tokens, including tabs, carriage returns, line + // feeds, and space characters. + Index++; + break; + case 123: + case 125: + case 91: + case 93: + case 58: + case 44: + // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at + // the current position. + value = charIndexBuggy ? source.charAt(Index) : source[Index]; + Index++; + return value; + case 34: + // `"` delimits a JSON string; advance to the next character and + // begin parsing the string. String tokens are prefixed with the + // sentinel `@` character to distinguish them from punctuators and + // end-of-string tokens. + for (value = "@", Index++; Index < length;) { + charCode = source.charCodeAt(Index); + if (charCode < 32) { + // Unescaped ASCII control characters (those with a code unit + // less than the space character) are not permitted. + abort(); + } else if (charCode == 92) { + // A reverse solidus (`\`) marks the beginning of an escaped + // control character (including `"`, `\`, and `/`) or Unicode + // escape sequence. + charCode = source.charCodeAt(++Index); + switch (charCode) { + case 92: + case 34: + case 47: + case 98: + case 116: + case 110: + case 102: + case 114: + // Revive escaped control characters. + value += Unescapes[charCode]; + Index++; + break; + case 117: + // `\u` marks the beginning of a Unicode escape sequence. + // Advance to the first character and validate the + // four-digit code point. + begin = ++Index; + for (position = Index + 4; Index < position; Index++) { + charCode = source.charCodeAt(Index); + // A valid sequence comprises four hexdigits (case- + // insensitive) that form a single hexadecimal value. + if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) { + // Invalid Unicode escape sequence. + abort(); + } + } + // Revive the escaped character. + value += fromCharCode("0x" + source.slice(begin, Index)); + break; + default: + // Invalid escape sequence. + abort(); + } + } else { + if (charCode == 34) { + // An unescaped double-quote character marks the end of the + // string. + break; + } + charCode = source.charCodeAt(Index); + begin = Index; + // Optimize for the common case where a string is valid. + while (charCode >= 32 && charCode != 92 && charCode != 34) { + charCode = source.charCodeAt(++Index); + } + // Append the string as-is. + value += source.slice(begin, Index); + } + } + if (source.charCodeAt(Index) == 34) { + // Advance to the next character and return the revived string. + Index++; + return value; + } + // Unterminated string. + abort(); + default: + // Parse numbers and literals. + begin = Index; + // Advance past the negative sign, if one is specified. + if (charCode == 45) { + isSigned = true; + charCode = source.charCodeAt(++Index); + } + // Parse an integer or floating-point value. + if (charCode >= 48 && charCode <= 57) { + // Leading zeroes are interpreted as octal literals. + if (charCode == 48 && (charCode = source.charCodeAt(Index + 1), charCode >= 48 && charCode <= 57)) { + // Illegal octal literal. + abort(); + } + isSigned = false; + // Parse the integer component. + for (; Index < length && (charCode = source.charCodeAt(Index), charCode >= 48 && charCode <= 57); Index++); + // Floats cannot contain a leading decimal point; however, this + // case is already accounted for by the parser. + if (source.charCodeAt(Index) == 46) { + position = ++Index; + // Parse the decimal component. + for (; position < length; position++) { + charCode = source.charCodeAt(position); + if (charCode < 48 || charCode > 57) { + break; + } + } + if (position == Index) { + // Illegal trailing decimal. + abort(); + } + Index = position; + } + // Parse exponents. The `e` denoting the exponent is + // case-insensitive. + charCode = source.charCodeAt(Index); + if (charCode == 101 || charCode == 69) { + charCode = source.charCodeAt(++Index); + // Skip past the sign following the exponent, if one is + // specified. + if (charCode == 43 || charCode == 45) { + Index++; + } + // Parse the exponential component. + for (position = Index; position < length; position++) { + charCode = source.charCodeAt(position); + if (charCode < 48 || charCode > 57) { + break; + } + } + if (position == Index) { + // Illegal empty exponent. + abort(); + } + Index = position; + } + // Coerce the parsed value to a JavaScript number. + return +source.slice(begin, Index); + } + // A negative sign may only precede numbers. + if (isSigned) { + abort(); + } + // `true`, `false`, and `null` literals. + var temp = source.slice(Index, Index + 4); + if (temp == "true") { + Index += 4; + return true; + } else if (temp == "fals" && source.charCodeAt(Index + 4) == 101) { + Index += 5; + return false; + } else if (temp == "null") { + Index += 4; + return null; + } + // Unrecognized token. + abort(); + } + } + // Return the sentinel `$` character if the parser has reached the end + // of the source string. + return "$"; + }; + + // Internal: Parses a JSON `value` token. + var get = function (value) { + var results, hasMembers; + if (value == "$") { + // Unexpected end of input. + abort(); + } + if (typeof value == "string") { + if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") { + // Remove the sentinel `@` character. + return value.slice(1); + } + // Parse object and array literals. + if (value == "[") { + // Parses a JSON array, returning a new JavaScript array. + results = []; + for (;;) { + value = lex(); + // A closing square bracket marks the end of the array literal. + if (value == "]") { + break; + } + // If the array literal contains elements, the current token + // should be a comma separating the previous element from the + // next. + if (hasMembers) { + if (value == ",") { + value = lex(); + if (value == "]") { + // Unexpected trailing `,` in array literal. + abort(); + } + } else { + // A `,` must separate each array element. + abort(); + } + } else { + hasMembers = true; + } + // Elisions and leading commas are not permitted. + if (value == ",") { + abort(); + } + results.push(get(value)); + } + return results; + } else if (value == "{") { + // Parses a JSON object, returning a new JavaScript object. + results = {}; + for (;;) { + value = lex(); + // A closing curly brace marks the end of the object literal. + if (value == "}") { + break; + } + // If the object literal contains members, the current token + // should be a comma separator. + if (hasMembers) { + if (value == ",") { + value = lex(); + if (value == "}") { + // Unexpected trailing `,` in object literal. + abort(); + } + } else { + // A `,` must separate each object member. + abort(); + } + } else { + hasMembers = true; + } + // Leading commas are not permitted, object property names must be + // double-quoted strings, and a `:` must separate each property + // name and value. + if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") { + abort(); + } + results[value.slice(1)] = get(lex()); + } + return results; + } + // Unexpected token encountered. + abort(); + } + return value; + }; + + // Internal: Updates a traversed object member. + var update = function (source, property, callback) { + var element = walk(source, property, callback); + if (element === undefined) { + delete source[property]; + } else { + source[property] = element; + } + }; + + // Internal: Recursively traverses a parsed JSON object, invoking the + // `callback` function for each value. This is an implementation of the + // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2. + var walk = function (source, property, callback) { + var value = source[property], + length; + if (typeof value == "object" && value) { + // `forOwn` can't be used to traverse an array in Opera <= 8.54 + // because its `Object#hasOwnProperty` implementation returns `false` + // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`). + if (getClass.call(value) == arrayClass) { + for (length = value.length; length--;) { + update(getClass, forOwn, value, length, callback); + } + } else { + forOwn(value, function (property) { + update(value, property, callback); + }); + } + } + return callback.call(source, property, value); + }; + + // Public: `JSON.parse`. See ES 5.1 section 15.12.2. + exports.parse = function (source, callback) { + var result, value; + Index = 0; + Source = "" + source; + result = get(lex()); + // If a JSON string contains multiple tokens, it is invalid. + if (lex() != "$") { + abort(); + } + // Reset the parser state. + Index = Source = null; + return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result; + }; + } + } + exports.runInContext = runInContext; + return exports; + } + if (freeExports && !isLoader) { + // Export for CommonJS environments. + runInContext(root, freeExports); + } else { + // Export for web browsers and JavaScript engines. + var nativeJSON = root.JSON, + previousJSON = root.JSON3, + isRestored = false; + var JSON3 = runInContext(root, root.JSON3 = { + // Public: Restores the original value of the global `JSON` object and + // returns a reference to the `JSON3` object. + "noConflict": function () { + if (!isRestored) { + isRestored = true; + root.JSON = nativeJSON; + root.JSON3 = previousJSON; + nativeJSON = previousJSON = null; + } + return JSON3; + } + }); + root.JSON = { + "parse": JSON3.parse, + "stringify": JSON3.stringify + }; + } + + // Export for asynchronous module loaders. + if (isLoader) { + !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { + return JSON3; + }).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } +}).call(this); +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../webpack/buildin/module.js */ "./node_modules/webpack/buildin/module.js")(module), __webpack_require__(/*! ./../../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js"))) + +/***/ }), + +/***/ "./node_modules/ms/index.js": +/*!**********************************!*\ + !*** ./node_modules/ms/index.js ***! + \**********************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function (val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val)); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} + +/***/ }), + +/***/ "./node_modules/node-libs-browser/node_modules/punycode/punycode.js": +/*!**************************************************************************!*\ + !*** ./node_modules/node-libs-browser/node_modules/punycode/punycode.js ***! + \**************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(module, global) {var __WEBPACK_AMD_DEFINE_RESULT__;/*! https://mths.be/punycode v1.4.1 by @mathias */ +; +(function (root) { + /** Detect free variables */ + var freeExports = true && exports && !exports.nodeType && exports; + var freeModule = true && module && !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, + // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, + // 0x80 + delimiter = '-', + // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, + // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, + // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { + // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function (value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for /* no initialization */ + (; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for /* no final expression */ + (index = basic > 0 ? basic + 1 : 0; index < inputLength;) { + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for /* no condition */ + (oldi = i, w = 1, k = base;; k += base) { + if (index >= inputLength) { + error('invalid-input'); + } + digit = basicToDigit(input.charCodeAt(index++)); + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + i += digit * w; + t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + if (digit < t) { + break; + } + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + w *= baseMinusT; + } + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + } + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + delta += (m - n) * handledCPCountPlusOne; + n = m; + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for /* no condition */ + (q = delta, k = base;; k += base) { + t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))); + q = floor(qMinusT / baseMinusT); + } + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + ++delta; + ++n; + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function (string) { + return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function (string) { + return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if (true) { + !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { + return punycode; + }).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else {} +})(this); +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../webpack/buildin/module.js */ "./node_modules/webpack/buildin/module.js")(module), __webpack_require__(/*! ./../../../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js"))) + +/***/ }), + +/***/ "./node_modules/object-inspect/index.js": +/*!**********************************************!*\ + !*** ./node_modules/object-inspect/index.js ***! + \**********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +var hasMap = typeof Map === 'function' && Map.prototype; +var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null; +var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null; +var mapForEach = hasMap && Map.prototype.forEach; +var hasSet = typeof Set === 'function' && Set.prototype; +var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null; +var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null; +var setForEach = hasSet && Set.prototype.forEach; +var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype; +var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null; +var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype; +var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null; +var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype; +var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null; +var booleanValueOf = Boolean.prototype.valueOf; +var objectToString = Object.prototype.toString; +var functionToString = Function.prototype.toString; +var $match = String.prototype.match; +var $slice = String.prototype.slice; +var $replace = String.prototype.replace; +var $toUpperCase = String.prototype.toUpperCase; +var $toLowerCase = String.prototype.toLowerCase; +var $test = RegExp.prototype.test; +var $concat = Array.prototype.concat; +var $join = Array.prototype.join; +var $arrSlice = Array.prototype.slice; +var $floor = Math.floor; +var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null; +var gOPS = Object.getOwnPropertySymbols; +var symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null; +var hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object'; +// ie, `has-tostringtag/shams +var toStringTag = typeof Symbol === 'function' && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? 'object' : 'symbol') ? Symbol.toStringTag : null; +var isEnumerable = Object.prototype.propertyIsEnumerable; +var gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ([].__proto__ === Array.prototype // eslint-disable-line no-proto +? function (O) { + return O.__proto__; // eslint-disable-line no-proto +} : null); +function addNumericSeparator(num, str) { + if (num === Infinity || num === -Infinity || num !== num || num && num > -1000 && num < 1000 || $test.call(/e/, str)) { + return str; + } + var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g; + if (typeof num === 'number') { + var int = num < 0 ? -$floor(-num) : $floor(num); // trunc(num) + if (int !== num) { + var intStr = String(int); + var dec = $slice.call(str, intStr.length + 1); + return $replace.call(intStr, sepRegex, '$&_') + '.' + $replace.call($replace.call(dec, /([0-9]{3})/g, '$&_'), /_$/, ''); + } + } + return $replace.call(str, sepRegex, '$&_'); +} +var utilInspect = __webpack_require__(/*! ./util.inspect */ 1); +var inspectCustom = utilInspect.custom; +var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; +module.exports = function inspect_(obj, options, depth, seen) { + var opts = options || {}; + if (has(opts, 'quoteStyle') && opts.quoteStyle !== 'single' && opts.quoteStyle !== 'double') { + throw new TypeError('option "quoteStyle" must be "single" or "double"'); + } + if (has(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number' ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity : opts.maxStringLength !== null)) { + throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`'); + } + var customInspect = has(opts, 'customInspect') ? opts.customInspect : true; + if (typeof customInspect !== 'boolean' && customInspect !== 'symbol') { + throw new TypeError('option "customInspect", if provided, must be `true`, `false`, or `\'symbol\'`'); + } + if (has(opts, 'indent') && opts.indent !== null && opts.indent !== '\t' && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0)) { + throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`'); + } + if (has(opts, 'numericSeparator') && typeof opts.numericSeparator !== 'boolean') { + throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`'); + } + var numericSeparator = opts.numericSeparator; + if (typeof obj === 'undefined') { + return 'undefined'; + } + if (obj === null) { + return 'null'; + } + if (typeof obj === 'boolean') { + return obj ? 'true' : 'false'; + } + if (typeof obj === 'string') { + return inspectString(obj, opts); + } + if (typeof obj === 'number') { + if (obj === 0) { + return Infinity / obj > 0 ? '0' : '-0'; + } + var str = String(obj); + return numericSeparator ? addNumericSeparator(obj, str) : str; + } + if (typeof obj === 'bigint') { + var bigIntStr = String(obj) + 'n'; + return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr; + } + var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth; + if (typeof depth === 'undefined') { + depth = 0; + } + if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') { + return isArray(obj) ? '[Array]' : '[Object]'; + } + var indent = getIndent(opts, depth); + if (typeof seen === 'undefined') { + seen = []; + } else if (indexOf(seen, obj) >= 0) { + return '[Circular]'; + } + function inspect(value, from, noIndent) { + if (from) { + seen = $arrSlice.call(seen); + seen.push(from); + } + if (noIndent) { + var newOpts = { + depth: opts.depth + }; + if (has(opts, 'quoteStyle')) { + newOpts.quoteStyle = opts.quoteStyle; + } + return inspect_(value, newOpts, depth + 1, seen); + } + return inspect_(value, opts, depth + 1, seen); + } + if (typeof obj === 'function' && !isRegExp(obj)) { + // in older engines, regexes are callable + var name = nameOf(obj); + var keys = arrObjKeys(obj, inspect); + return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : ''); + } + if (isSymbol(obj)) { + var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, '$1') : symToString.call(obj); + return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString; + } + if (isElement(obj)) { + var s = '<' + $toLowerCase.call(String(obj.nodeName)); + var attrs = obj.attributes || []; + for (var i = 0; i < attrs.length; i++) { + s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts); + } + s += '>'; + if (obj.childNodes && obj.childNodes.length) { + s += '...'; + } + s += ''; + return s; + } + if (isArray(obj)) { + if (obj.length === 0) { + return '[]'; + } + var xs = arrObjKeys(obj, inspect); + if (indent && !singleLineValues(xs)) { + return '[' + indentedJoin(xs, indent) + ']'; + } + return '[ ' + $join.call(xs, ', ') + ' ]'; + } + if (isError(obj)) { + var parts = arrObjKeys(obj, inspect); + if (!('cause' in Error.prototype) && 'cause' in obj && !isEnumerable.call(obj, 'cause')) { + return '{ [' + String(obj) + '] ' + $join.call($concat.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }'; + } + if (parts.length === 0) { + return '[' + String(obj) + ']'; + } + return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }'; + } + if (typeof obj === 'object' && customInspect) { + if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && utilInspect) { + return utilInspect(obj, { + depth: maxDepth - depth + }); + } else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') { + return obj.inspect(); + } + } + if (isMap(obj)) { + var mapParts = []; + if (mapForEach) { + mapForEach.call(obj, function (value, key) { + mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj)); + }); + } + return collectionOf('Map', mapSize.call(obj), mapParts, indent); + } + if (isSet(obj)) { + var setParts = []; + if (setForEach) { + setForEach.call(obj, function (value) { + setParts.push(inspect(value, obj)); + }); + } + return collectionOf('Set', setSize.call(obj), setParts, indent); + } + if (isWeakMap(obj)) { + return weakCollectionOf('WeakMap'); + } + if (isWeakSet(obj)) { + return weakCollectionOf('WeakSet'); + } + if (isWeakRef(obj)) { + return weakCollectionOf('WeakRef'); + } + if (isNumber(obj)) { + return markBoxed(inspect(Number(obj))); + } + if (isBigInt(obj)) { + return markBoxed(inspect(bigIntValueOf.call(obj))); + } + if (isBoolean(obj)) { + return markBoxed(booleanValueOf.call(obj)); + } + if (isString(obj)) { + return markBoxed(inspect(String(obj))); + } + if (!isDate(obj) && !isRegExp(obj)) { + var ys = arrObjKeys(obj, inspect); + var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object; + var protoTag = obj instanceof Object ? '' : 'null prototype'; + var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? 'Object' : ''; + var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : ''; + var tag = constructorTag + (stringTag || protoTag ? '[' + $join.call($concat.call([], stringTag || [], protoTag || []), ': ') + '] ' : ''); + if (ys.length === 0) { + return tag + '{}'; + } + if (indent) { + return tag + '{' + indentedJoin(ys, indent) + '}'; + } + return tag + '{ ' + $join.call(ys, ', ') + ' }'; + } + return String(obj); +}; +function wrapQuotes(s, defaultStyle, opts) { + var quoteChar = (opts.quoteStyle || defaultStyle) === 'double' ? '"' : "'"; + return quoteChar + s + quoteChar; +} +function quote(s) { + return $replace.call(String(s), /"/g, '"'); +} +function isArray(obj) { + return toStr(obj) === '[object Array]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); +} +function isDate(obj) { + return toStr(obj) === '[object Date]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); +} +function isRegExp(obj) { + return toStr(obj) === '[object RegExp]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); +} +function isError(obj) { + return toStr(obj) === '[object Error]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); +} +function isString(obj) { + return toStr(obj) === '[object String]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); +} +function isNumber(obj) { + return toStr(obj) === '[object Number]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); +} +function isBoolean(obj) { + return toStr(obj) === '[object Boolean]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); +} + +// Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives +function isSymbol(obj) { + if (hasShammedSymbols) { + return obj && typeof obj === 'object' && obj instanceof Symbol; + } + if (typeof obj === 'symbol') { + return true; + } + if (!obj || typeof obj !== 'object' || !symToString) { + return false; + } + try { + symToString.call(obj); + return true; + } catch (e) {} + return false; +} +function isBigInt(obj) { + if (!obj || typeof obj !== 'object' || !bigIntValueOf) { + return false; + } + try { + bigIntValueOf.call(obj); + return true; + } catch (e) {} + return false; +} +var hasOwn = Object.prototype.hasOwnProperty || function (key) { + return key in this; +}; +function has(obj, key) { + return hasOwn.call(obj, key); +} +function toStr(obj) { + return objectToString.call(obj); +} +function nameOf(f) { + if (f.name) { + return f.name; + } + var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/); + if (m) { + return m[1]; + } + return null; +} +function indexOf(xs, x) { + if (xs.indexOf) { + return xs.indexOf(x); + } + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) { + return i; + } + } + return -1; +} +function isMap(x) { + if (!mapSize || !x || typeof x !== 'object') { + return false; + } + try { + mapSize.call(x); + try { + setSize.call(x); + } catch (s) { + return true; + } + return x instanceof Map; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} +function isWeakMap(x) { + if (!weakMapHas || !x || typeof x !== 'object') { + return false; + } + try { + weakMapHas.call(x, weakMapHas); + try { + weakSetHas.call(x, weakSetHas); + } catch (s) { + return true; + } + return x instanceof WeakMap; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} +function isWeakRef(x) { + if (!weakRefDeref || !x || typeof x !== 'object') { + return false; + } + try { + weakRefDeref.call(x); + return true; + } catch (e) {} + return false; +} +function isSet(x) { + if (!setSize || !x || typeof x !== 'object') { + return false; + } + try { + setSize.call(x); + try { + mapSize.call(x); + } catch (m) { + return true; + } + return x instanceof Set; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} +function isWeakSet(x) { + if (!weakSetHas || !x || typeof x !== 'object') { + return false; + } + try { + weakSetHas.call(x, weakSetHas); + try { + weakMapHas.call(x, weakMapHas); + } catch (s) { + return true; + } + return x instanceof WeakSet; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} +function isElement(x) { + if (!x || typeof x !== 'object') { + return false; + } + if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) { + return true; + } + return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function'; +} +function inspectString(str, opts) { + if (str.length > opts.maxStringLength) { + var remaining = str.length - opts.maxStringLength; + var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : ''); + return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer; + } + // eslint-disable-next-line no-control-regex + var s = $replace.call($replace.call(str, /(['\\])/g, '\\$1'), /[\x00-\x1f]/g, lowbyte); + return wrapQuotes(s, 'single', opts); +} +function lowbyte(c) { + var n = c.charCodeAt(0); + var x = { + 8: 'b', + 9: 't', + 10: 'n', + 12: 'f', + 13: 'r' + }[n]; + if (x) { + return '\\' + x; + } + return '\\x' + (n < 0x10 ? '0' : '') + $toUpperCase.call(n.toString(16)); +} +function markBoxed(str) { + return 'Object(' + str + ')'; +} +function weakCollectionOf(type) { + return type + ' { ? }'; +} +function collectionOf(type, size, entries, indent) { + var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ', '); + return type + ' (' + size + ') {' + joinedEntries + '}'; +} +function singleLineValues(xs) { + for (var i = 0; i < xs.length; i++) { + if (indexOf(xs[i], '\n') >= 0) { + return false; + } + } + return true; +} +function getIndent(opts, depth) { + var baseIndent; + if (opts.indent === '\t') { + baseIndent = '\t'; + } else if (typeof opts.indent === 'number' && opts.indent > 0) { + baseIndent = $join.call(Array(opts.indent + 1), ' '); + } else { + return null; + } + return { + base: baseIndent, + prev: $join.call(Array(depth + 1), baseIndent) + }; +} +function indentedJoin(xs, indent) { + if (xs.length === 0) { + return ''; + } + var lineJoiner = '\n' + indent.prev + indent.base; + return lineJoiner + $join.call(xs, ',' + lineJoiner) + '\n' + indent.prev; +} +function arrObjKeys(obj, inspect) { + var isArr = isArray(obj); + var xs = []; + if (isArr) { + xs.length = obj.length; + for (var i = 0; i < obj.length; i++) { + xs[i] = has(obj, i) ? inspect(obj[i], obj) : ''; + } + } + var syms = typeof gOPS === 'function' ? gOPS(obj) : []; + var symMap; + if (hasShammedSymbols) { + symMap = {}; + for (var k = 0; k < syms.length; k++) { + symMap['$' + syms[k]] = syms[k]; + } + } + for (var key in obj) { + // eslint-disable-line no-restricted-syntax + if (!has(obj, key)) { + continue; + } // eslint-disable-line no-restricted-syntax, no-continue + if (isArr && String(Number(key)) === key && key < obj.length) { + continue; + } // eslint-disable-line no-restricted-syntax, no-continue + if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) { + // this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section + continue; // eslint-disable-line no-restricted-syntax, no-continue + } else if ($test.call(/[^\w$]/, key)) { + xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj)); + } else { + xs.push(key + ': ' + inspect(obj[key], obj)); + } + } + if (typeof gOPS === 'function') { + for (var j = 0; j < syms.length; j++) { + if (isEnumerable.call(obj, syms[j])) { + xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj)); + } + } + } + return xs; +} + +/***/ }), + +/***/ "./node_modules/process/browser.js": +/*!*****************************************!*\ + !*** ./node_modules/process/browser.js ***! + \*****************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout() { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +})(); +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch (e) { + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch (e) { + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e) { + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e) { + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + var len = queue.length; + while (len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; +function noop() {} +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; +process.listeners = function (name) { + return []; +}; +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; +process.cwd = function () { + return '/'; +}; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function () { + return 0; +}; + +/***/ }), + +/***/ "./node_modules/querystringify/index.js": +/*!**********************************************!*\ + !*** ./node_modules/querystringify/index.js ***! + \**********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var has = Object.prototype.hasOwnProperty, + undef; + +/** + * Decode a URI encoded string. + * + * @param {String} input The URI encoded string. + * @returns {String|Null} The decoded string. + * @api private + */ +function decode(input) { + try { + return decodeURIComponent(input.replace(/\+/g, ' ')); + } catch (e) { + return null; + } +} + +/** + * Attempts to encode a given input. + * + * @param {String} input The string that needs to be encoded. + * @returns {String|Null} The encoded string. + * @api private + */ +function encode(input) { + try { + return encodeURIComponent(input); + } catch (e) { + return null; + } +} + +/** + * Simple query string parser. + * + * @param {String} query The query string that needs to be parsed. + * @returns {Object} + * @api public + */ +function querystring(query) { + var parser = /([^=?#&]+)=?([^&]*)/g, + result = {}, + part; + while (part = parser.exec(query)) { + var key = decode(part[1]), + value = decode(part[2]); + + // + // Prevent overriding of existing properties. This ensures that build-in + // methods like `toString` or __proto__ are not overriden by malicious + // querystrings. + // + // In the case if failed decoding, we want to omit the key/value pairs + // from the result. + // + if (key === null || value === null || key in result) continue; + result[key] = value; + } + return result; +} + +/** + * Transform a query string to an object. + * + * @param {Object} obj Object that should be transformed. + * @param {String} prefix Optional prefix. + * @returns {String} + * @api public + */ +function querystringify(obj, prefix) { + prefix = prefix || ''; + var pairs = [], + value, + key; + + // + // Optionally prefix with a '?' if needed + // + if ('string' !== typeof prefix) prefix = '?'; + for (key in obj) { + if (has.call(obj, key)) { + value = obj[key]; + + // + // Edge cases where we actually want to encode the value to an empty + // string instead of the stringified value. + // + if (!value && (value === null || value === undef || isNaN(value))) { + value = ''; + } + key = encode(key); + value = encode(value); + + // + // If we failed to encode the strings, we should bail out as we don't + // want to add invalid strings to the query. + // + if (key === null || value === null) continue; + pairs.push(key + '=' + value); + } + } + return pairs.length ? prefix + pairs.join('&') : ''; +} + +// +// Expose the module. +// +exports.stringify = querystringify; +exports.parse = querystring; + +/***/ }), + +/***/ "./node_modules/react-dev-utils/formatWebpackMessages.js": +/*!***************************************************************!*\ + !*** ./node_modules/react-dev-utils/formatWebpackMessages.js ***! + \***************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + + +const chalk = __webpack_require__(/*! chalk */ "./node_modules/chalk/index.js"); +const friendlySyntaxErrorLabel = 'Syntax error:'; +function isLikelyASyntaxError(message) { + return message.indexOf(friendlySyntaxErrorLabel) !== -1; +} + +// Cleans up webpack error messages. +function formatMessage(message) { + let lines = message.split('\n'); + + // Strip Webpack-added headers off errors/warnings + // https://github.com/webpack/webpack/blob/master/lib/ModuleError.js + lines = lines.filter(line => !/Module [A-z ]+\(from/.test(line)); + + // Transform parsing error into syntax error + // TODO: move this to our ESLint formatter? + lines = lines.map(line => { + const parsingError = /Line (\d+):(?:(\d+):)?\s*Parsing error: (.+)$/.exec(line); + if (!parsingError) { + return line; + } + const [, errorLine, errorColumn, errorMessage] = parsingError; + return `${friendlySyntaxErrorLabel} ${errorMessage} (${errorLine}:${errorColumn})`; + }); + message = lines.join('\n'); + // Smoosh syntax errors (commonly found in CSS) + message = message.replace(/SyntaxError\s+\((\d+):(\d+)\)\s*(.+?)\n/g, `${friendlySyntaxErrorLabel} $3 ($1:$2)\n`); + // Clean up export errors + message = message.replace(/^.*export '(.+?)' was not found in '(.+?)'.*$/gm, `Attempted import error: '$1' is not exported from '$2'.`); + message = message.replace(/^.*export 'default' \(imported as '(.+?)'\) was not found in '(.+?)'.*$/gm, `Attempted import error: '$2' does not contain a default export (imported as '$1').`); + message = message.replace(/^.*export '(.+?)' \(imported as '(.+?)'\) was not found in '(.+?)'.*$/gm, `Attempted import error: '$1' is not exported from '$3' (imported as '$2').`); + lines = message.split('\n'); + + // Remove leading newline + if (lines.length > 2 && lines[1].trim() === '') { + lines.splice(1, 1); + } + // Clean up file name + lines[0] = lines[0].replace(/^(.*) \d+:\d+-\d+$/, '$1'); + + // Cleans up verbose "module not found" messages for files and packages. + if (lines[1] && lines[1].indexOf('Module not found: ') === 0) { + lines = [lines[0], lines[1].replace('Error: ', '').replace('Module not found: Cannot find file:', 'Cannot find file:')]; + } + + // Add helpful message for users trying to use Sass for the first time + if (lines[1] && lines[1].match(/Cannot find module.+node-sass/)) { + lines[1] = 'To import Sass files, you first need to install node-sass.\n'; + lines[1] += 'Run `npm install node-sass` or `yarn add node-sass` inside your workspace.'; + } + lines[0] = chalk.inverse(lines[0]); + message = lines.join('\n'); + // Internal stacks are generally useless so we strip them... with the + // exception of stacks containing `webpack:` because they're normally + // from user code generated by Webpack. For more information see + // https://github.com/facebook/create-react-app/pull/1050 + message = message.replace(/^\s*at\s((?!webpack:).)*:\d+:\d+[\s)]*(\n|$)/gm, ''); // at ... ...:x:y + message = message.replace(/^\s*at\s(\n|$)/gm, ''); // at + lines = message.split('\n'); + + // Remove duplicated newlines + lines = lines.filter((line, index, arr) => index === 0 || line.trim() !== '' || line.trim() !== arr[index - 1].trim()); + + // Reassemble the message + message = lines.join('\n'); + return message.trim(); +} +function formatWebpackMessages(json) { + const formattedErrors = json.errors.map(function (message) { + return formatMessage(message, true); + }); + const formattedWarnings = json.warnings.map(function (message) { + return formatMessage(message, false); + }); + const result = { + errors: formattedErrors, + warnings: formattedWarnings + }; + if (result.errors.some(isLikelyASyntaxError)) { + // If there are any syntax errors, show just them. + result.errors = result.errors.filter(isLikelyASyntaxError); + } + return result; +} +module.exports = formatWebpackMessages; + +/***/ }), + +/***/ "./node_modules/react-dev-utils/launchEditorEndpoint.js": +/*!**************************************************************!*\ + !*** ./node_modules/react-dev-utils/launchEditorEndpoint.js ***! + \**************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + +// TODO: we might want to make this injectable to support DEV-time non-root URLs. +module.exports = '/__open-stack-frame-in-editor'; + +/***/ }), + +/***/ "./node_modules/react-dev-utils/node_modules/ansi-regex/index.js": +/*!***********************************************************************!*\ + !*** ./node_modules/react-dev-utils/node_modules/ansi-regex/index.js ***! + \***********************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = options => { + options = Object.assign({ + onlyFirst: false + }, options); + const pattern = ['[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'].join('|'); + return new RegExp(pattern, options.onlyFirst ? undefined : 'g'); +}; + +/***/ }), + +/***/ "./node_modules/react-dev-utils/node_modules/strip-ansi/index.js": +/*!***********************************************************************!*\ + !*** ./node_modules/react-dev-utils/node_modules/strip-ansi/index.js ***! + \***********************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const ansiRegex = __webpack_require__(/*! ansi-regex */ "./node_modules/react-dev-utils/node_modules/ansi-regex/index.js"); +const stripAnsi = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; +module.exports = stripAnsi; +module.exports.default = stripAnsi; + +/***/ }), + +/***/ "./node_modules/react-dev-utils/webpackHotDevClient.js": +/*!*************************************************************!*\ + !*** ./node_modules/react-dev-utils/webpackHotDevClient.js ***! + \*************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + + +// This alternative WebpackDevServer combines the functionality of: +// https://github.com/webpack/webpack-dev-server/blob/webpack-1/client/index.js +// https://github.com/webpack/webpack/blob/webpack-1/hot/dev-server.js + +// It only supports their simplest configuration (hot updates on same server). +// It makes some opinionated choices on top, like adding a syntax error overlay +// that looks similar to our console output. The error overlay is inspired by: +// https://github.com/glenjamin/webpack-hot-middleware +var SockJS = __webpack_require__(/*! sockjs-client */ "./node_modules/sockjs-client/lib/entry.js"); +var stripAnsi = __webpack_require__(/*! strip-ansi */ "./node_modules/react-dev-utils/node_modules/strip-ansi/index.js"); +var url = __webpack_require__(/*! url */ "./node_modules/url/url.js"); +var launchEditorEndpoint = __webpack_require__(/*! ./launchEditorEndpoint */ "./node_modules/react-dev-utils/launchEditorEndpoint.js"); +var formatWebpackMessages = __webpack_require__(/*! ./formatWebpackMessages */ "./node_modules/react-dev-utils/formatWebpackMessages.js"); +var ErrorOverlay = __webpack_require__(/*! react-error-overlay */ "./node_modules/react-error-overlay/lib/index.js"); +ErrorOverlay.setEditorHandler(function editorHandler(errorLocation) { + // Keep this sync with errorOverlayMiddleware.js + fetch(launchEditorEndpoint + '?fileName=' + window.encodeURIComponent(errorLocation.fileName) + '&lineNumber=' + window.encodeURIComponent(errorLocation.lineNumber || 1) + '&colNumber=' + window.encodeURIComponent(errorLocation.colNumber || 1)); +}); + +// We need to keep track of if there has been a runtime error. +// Essentially, we cannot guarantee application state was not corrupted by the +// runtime error. To prevent confusing behavior, we forcibly reload the entire +// application. This is handled below when we are notified of a compile (code +// change). +// See https://github.com/facebook/create-react-app/issues/3096 +var hadRuntimeError = false; +ErrorOverlay.startReportingRuntimeErrors({ + onError: function () { + hadRuntimeError = true; + }, + filename: '/static/js/bundle.js' +}); +if ( true && typeof module.hot.dispose === 'function') { + module.hot.dispose(function () { + // TODO: why do we need this? + ErrorOverlay.stopReportingRuntimeErrors(); + }); +} + +// Connect to WebpackDevServer via a socket. +var connection = new SockJS(url.format({ + protocol: window.location.protocol, + hostname: window.location.hostname, + port: window.location.port, + // Hardcoded in WebpackDevServer + pathname: '/sockjs-node' +})); + +// Unlike WebpackDevServer client, we won't try to reconnect +// to avoid spamming the console. Disconnect usually happens +// when developer stops the server. +connection.onclose = function () { + if (typeof console !== 'undefined' && typeof console.info === 'function') { + console.info('The development server has disconnected.\nRefresh the page if necessary.'); + } +}; + +// Remember some state related to hot module replacement. +var isFirstCompilation = true; +var mostRecentCompilationHash = null; +var hasCompileErrors = false; +function clearOutdatedErrors() { + // Clean up outdated compile errors, if any. + if (typeof console !== 'undefined' && typeof console.clear === 'function') { + if (hasCompileErrors) { + console.clear(); + } + } +} + +// Successful compilation. +function handleSuccess() { + clearOutdatedErrors(); + var isHotUpdate = !isFirstCompilation; + isFirstCompilation = false; + hasCompileErrors = false; + + // Attempt to apply hot updates or reload. + if (isHotUpdate) { + tryApplyUpdates(function onHotUpdateSuccess() { + // Only dismiss it when we're sure it's a hot update. + // Otherwise it would flicker right before the reload. + tryDismissErrorOverlay(); + }); + } +} + +// Compilation with warnings (e.g. ESLint). +function handleWarnings(warnings) { + clearOutdatedErrors(); + var isHotUpdate = !isFirstCompilation; + isFirstCompilation = false; + hasCompileErrors = false; + function printWarnings() { + // Print warnings to the console. + var formatted = formatWebpackMessages({ + warnings: warnings, + errors: [] + }); + if (typeof console !== 'undefined' && typeof console.warn === 'function') { + for (var i = 0; i < formatted.warnings.length; i++) { + if (i === 5) { + console.warn('There were more warnings in other files.\n' + 'You can find a complete log in the terminal.'); + break; + } + console.warn(stripAnsi(formatted.warnings[i])); + } + } + } + printWarnings(); + + // Attempt to apply hot updates or reload. + if (isHotUpdate) { + tryApplyUpdates(function onSuccessfulHotUpdate() { + // Only dismiss it when we're sure it's a hot update. + // Otherwise it would flicker right before the reload. + tryDismissErrorOverlay(); + }); + } +} + +// Compilation with errors (e.g. syntax error or missing modules). +function handleErrors(errors) { + clearOutdatedErrors(); + isFirstCompilation = false; + hasCompileErrors = true; + + // "Massage" webpack messages. + var formatted = formatWebpackMessages({ + errors: errors, + warnings: [] + }); + + // Only show the first error. + ErrorOverlay.reportBuildError(formatted.errors[0]); + + // Also log them to the console. + if (typeof console !== 'undefined' && typeof console.error === 'function') { + for (var i = 0; i < formatted.errors.length; i++) { + console.error(stripAnsi(formatted.errors[i])); + } + } + + // Do not attempt to reload now. + // We will reload on next success instead. +} + +function tryDismissErrorOverlay() { + if (!hasCompileErrors) { + ErrorOverlay.dismissBuildError(); + } +} + +// There is a newer version of the code available. +function handleAvailableHash(hash) { + // Update last known compilation hash. + mostRecentCompilationHash = hash; +} + +// Handle messages from the server. +connection.onmessage = function (e) { + var message = JSON.parse(e.data); + switch (message.type) { + case 'hash': + handleAvailableHash(message.data); + break; + case 'still-ok': + case 'ok': + handleSuccess(); + break; + case 'content-changed': + // Triggered when a file from `contentBase` changed. + window.location.reload(); + break; + case 'warnings': + handleWarnings(message.data); + break; + case 'errors': + handleErrors(message.data); + break; + default: + // Do nothing. + } +}; + +// Is there a newer version of this code available? +function isUpdateAvailable() { + /* globals __webpack_hash__ */ + // __webpack_hash__ is the hash of the current compilation. + // It's a global variable injected by Webpack. + return mostRecentCompilationHash !== __webpack_require__.h(); +} + +// Webpack disallows updates in other states. +function canApplyUpdates() { + return module.hot.status() === 'idle'; +} + +// Attempt to update code on the fly, fall back to a hard reload. +function tryApplyUpdates(onHotUpdateSuccess) { + if (false) {} + if (!isUpdateAvailable() || !canApplyUpdates()) { + return; + } + function handleApplyUpdates(err, updatedModules) { + if (err || !updatedModules || hadRuntimeError) { + window.location.reload(); + return; + } + if (typeof onHotUpdateSuccess === 'function') { + // Maybe we want to do something. + onHotUpdateSuccess(); + } + if (isUpdateAvailable()) { + // While we were updating, there was a new update! Do it again. + tryApplyUpdates(); + } + } + + // https://webpack.github.io/docs/hot-module-replacement.html#check + var result = module.hot.check( /* autoApply */true, handleApplyUpdates); + + // // Webpack 2 returns a Promise instead of invoking a callback + if (result && result.then) { + result.then(function (updatedModules) { + handleApplyUpdates(null, updatedModules); + }, function (err) { + handleApplyUpdates(err, null); + }); + } +} + +/***/ }), + +/***/ "./node_modules/react-dom/cjs/react-dom.development.js": +/*!*************************************************************!*\ + !*** ./node_modules/react-dom/cjs/react-dom.development.js ***! + \*************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * @license React + * react-dom.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + + +if (true) { + (function () { + 'use strict'; + + /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ + if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === 'function') { + __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); + } + var React = __webpack_require__(/*! react */ "./node_modules/react/index.js"); + var Scheduler = __webpack_require__(/*! scheduler */ "./node_modules/scheduler/index.js"); + var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + var suppressWarning = false; + function setSuppressWarning(newSuppressWarning) { + { + suppressWarning = newSuppressWarning; + } + } // In DEV, calls to console.warn and console.error get replaced + // by calls to these methods by a Babel plugin. + // + // In PROD (or in packages without access to React internals), + // they are left as they are instead. + + function warn(format) { + { + if (!suppressWarning) { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + printWarning('warn', format, args); + } + } + } + function error(format) { + { + if (!suppressWarning) { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + printWarning('error', format, args); + } + } + } + function printWarning(level, format, args) { + // When changing this logic, you might want to also + // update consoleWithStackDev.www.js as well. + { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); + if (stack !== '') { + format += '%s'; + args = args.concat([stack]); + } // eslint-disable-next-line react-internal/safe-string-coercion + + var argsWithFormat = args.map(function (item) { + return String(item); + }); // Careful: RN currently depends on this prefix + + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging + + Function.prototype.apply.call(console[level], console, argsWithFormat); + } + } + var FunctionComponent = 0; + var ClassComponent = 1; + var IndeterminateComponent = 2; // Before we know whether it is function or class + + var HostRoot = 3; // Root of a host tree. Could be nested inside another node. + + var HostPortal = 4; // A subtree. Could be an entry point to a different renderer. + + var HostComponent = 5; + var HostText = 6; + var Fragment = 7; + var Mode = 8; + var ContextConsumer = 9; + var ContextProvider = 10; + var ForwardRef = 11; + var Profiler = 12; + var SuspenseComponent = 13; + var MemoComponent = 14; + var SimpleMemoComponent = 15; + var LazyComponent = 16; + var IncompleteClassComponent = 17; + var DehydratedFragment = 18; + var SuspenseListComponent = 19; + var ScopeComponent = 21; + var OffscreenComponent = 22; + var LegacyHiddenComponent = 23; + var CacheComponent = 24; + var TracingMarkerComponent = 25; + + // ----------------------------------------------------------------------------- + + var enableClientRenderFallbackOnTextMismatch = true; // TODO: Need to review this code one more time before landing + // the react-reconciler package. + + var enableNewReconciler = false; // Support legacy Primer support on internal FB www + + var enableLazyContextPropagation = false; // FB-only usage. The new API has different semantics. + + var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber + + var enableSuspenseAvoidThisFallback = false; // Enables unstable_avoidThisFallback feature in Fizz + // React DOM Chopping Block + // + // Similar to main Chopping Block but only flags related to React DOM. These are + // grouped because we will likely batch all of them into a single major release. + // ----------------------------------------------------------------------------- + // Disable support for comment nodes as React DOM containers. Already disabled + // in open source, but www codebase still relies on it. Need to remove. + + var disableCommentsAsDOMContainers = true; // Disable javascript: URL strings in href for XSS protection. + // and client rendering, mostly to allow JSX attributes to apply to the custom + // element's object properties instead of only HTML attributes. + // https://github.com/facebook/react/issues/11347 + + var enableCustomElementPropertySupport = false; // Disables children for