From 9d82accbad8e94abb3b91b69302b1910b4a5c8a4 Mon Sep 17 00:00:00 2001 From: mfilip Date: Fri, 6 May 2022 16:13:06 +0200 Subject: [PATCH] fix(JS): Rebuild JS assets --- view/base/web/admin.js | 8552 +--------------------------- view/base/web/binding.js | 11136 +------------------------------------ 2 files changed, 2 insertions(+), 19686 deletions(-) diff --git a/view/base/web/admin.js b/view/base/web/admin.js index 466e2ded..dca9c46b 100644 --- a/view/base/web/admin.js +++ b/view/base/web/admin.js @@ -4,8554 +4,4 @@ * Magento Integration * Copyright IDDQD Limited, all rights reserved */ -(function () { - 'use strict'; - - function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; - } - - var isString$4 = function isString(input) { - return typeof input === "string"; - }; - - var hasWindow$1 = function hasWindow() { - return typeof window !== "undefined"; - }; - - var isTrue$2 = function isTrue() { - return true; - }; - - var getParent$1 = function getParent(node, entity) { - var test = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : isTrue$2; - var parent = node; - var tagName = entity.toUpperCase(); - - while (parent.tagName !== "HTML") { - if (parent.tagName === tagName && test(parent)) return parent; - if (parent.parentNode === null) return null; - parent = parent.parentNode; - } - - return null; - }; - var insertBefore = function insertBefore(_ref) { - var elem = _ref.elem, - target = _ref.target; - var parent = target.parentNode; - if (parent === null) return; - parent.insertBefore(elem, target); - return elem; - }; - var toElem$1 = function toElem(elem, context) { - if (isString$4(elem)) return context.querySelector(elem); - return elem; - }; - - function ownKeys$9(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - - function _objectSpread$9(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$9(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$9(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - var defaults$c = { - enabled: true, - apiKey: "", - populateOrganisation: true, - populateCounty: false, - autocomplete: true, - autocompleteOverride: {}, - postcodeLookup: true, - postcodeLookupOverride: {} - }; - var config = function config() { - var c = window.idpcConfig; - if (c === undefined) return; - return _objectSpread$9(_objectSpread$9({}, defaults$c), c); - }; - - var g$1 = {}; - - if (hasWindow$1()) { - if (window.idpcGlobal) { - g$1 = window.idpcGlobal; - } else { - window.idpcGlobal = g$1; - } - } - - function _arrayWithHoles(arr) { - if (Array.isArray(arr)) return arr; - } - - function _iterableToArrayLimit(arr, i) { - var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; - - if (_i == null) return; - var _arr = []; - var _n = true; - var _d = false; - - var _s, _e; - - try { - for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { - _arr.push(_s.value); - - if (i && _arr.length === i) break; - } - } catch (err) { - _d = true; - _e = err; - } finally { - try { - if (!_n && _i["return"] != null) _i["return"](); - } finally { - if (_d) throw _e; - } - } - - return _arr; - } - - function _arrayLikeToArray(arr, len) { - if (len == null || len > arr.length) len = arr.length; - - for (var i = 0, arr2 = new Array(len); i < len; i++) { - arr2[i] = arr[i]; - } - - return arr2; - } - - function _unsupportedIterableToArray(o, minLen) { - if (!o) return; - if (typeof o === "string") return _arrayLikeToArray(o, minLen); - var n = Object.prototype.toString.call(o).slice(8, -1); - if (n === "Object" && o.constructor) n = o.constructor.name; - if (n === "Map" || n === "Set") return Array.from(o); - if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); - } - - function _nonIterableRest() { - throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); - } - - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - - var dist = {}; - - Object.defineProperty(dist, "__esModule", { - value: true - }); - var capitalisePostTown_1 = dist.capitalisePostTown = void 0; - var exclusion = /^(of|le|upon|on|the)$/; - var containsAmpersand = /\w+&\w+/; // capitalise word with exceptions on exclusion list - - var capitaliseWord = function capitaliseWord(word) { - word = word.toLowerCase(); - if (word.match(exclusion)) return word; - if (word.match(containsAmpersand)) return word.toUpperCase(); - return word.charAt(0).toUpperCase() + word.slice(1); - }; - - var joiner = /-/; - var joinerWord = /^(in|de|under|upon|y|on|over|the|by)$/; // Check for names connected with hyphens - - var checkJoins = function checkJoins(string) { - if (string.match(joiner) === null) return string; - return string.split("-").map(function (str) { - if (str.match(joinerWord)) return str.toLowerCase(); - return capitaliseWord(str); - }).join("-"); - }; - - var boness = /bo'ness/i; - var bfpo = /bfpo/i; // Handles unusual names which cannot be easily generalised into a rule - - var exceptions = function exceptions(str) { - if (str.match(boness)) return "Bo'Ness"; - if (str.match(bfpo)) return "BFPO"; - return str; - }; - - var capitalisePostTown = function capitalisePostTown(postTown) { - return postTown.split(" ").map(capitaliseWord).map(checkJoins).map(exceptions).join(" "); - }; - - capitalisePostTown_1 = dist.capitalisePostTown = capitalisePostTown; - - function _typeof(obj) { - "@babel/helpers - typeof"; - - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof = function _typeof(obj) { - return typeof obj; - }; - } else { - _typeof = function _typeof(obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }; - } - - return _typeof(obj); - } - - function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { - try { - var info = gen[key](arg); - var value = info.value; - } catch (error) { - reject(error); - return; - } - - if (info.done) { - resolve(value); - } else { - Promise.resolve(value).then(_next, _throw); - } - } - - function _asyncToGenerator(fn) { - return function () { - var self = this, - args = arguments; - return new Promise(function (resolve, reject) { - var gen = fn.apply(self, args); - - function _next(value) { - asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); - } - - function _throw(err) { - asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); - } - - _next(undefined); - }); - }; - } - - /** - * Copyright (c) 2014-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. - */ - var Op = Object.prototype; - var hasOwn = Op.hasOwnProperty; - var undefined$1; // More compressible than void 0. - - var $Symbol = typeof Symbol === "function" ? Symbol : {}; - var iteratorSymbol = $Symbol.iterator || "@@iterator"; - var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; - var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; - - function wrap(innerFn, outerFn, self, tryLocsList) { - // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. - var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; - var generator = Object.create(protoGenerator.prototype); - var context = new Context(tryLocsList || []); // The ._invoke method unifies the implementations of the .next, - // .throw, and .return methods. - - generator._invoke = makeInvokeMethod(innerFn, self, context); - return generator; - } // Try/catch helper to minimize deoptimizations. Returns a completion - // record like context.tryEntries[i].completion. This interface could - // have been (and was previously) designed to take a closure to be - // invoked without arguments, but in all the cases we care about we - // already have an existing method we want to call, so there's no need - // to create a new function object. We can even get away with assuming - // the method takes exactly one argument, since that happens to be true - // in every case, so we don't have to touch the arguments object. The - // only additional allocation required is the completion record, which - // has a stable shape and so hopefully should be cheap to allocate. - - - function tryCatch(fn, obj, arg) { - try { - return { - type: "normal", - arg: fn.call(obj, arg) - }; - } catch (err) { - return { - type: "throw", - arg: err - }; - } - } - - var GenStateSuspendedStart = "suspendedStart"; - var GenStateSuspendedYield = "suspendedYield"; - var GenStateExecuting = "executing"; - var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as - // breaking out of the dispatch switch statement. - - var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and - // .constructor.prototype properties for functions that return Generator - // objects. For full spec compliance, you may wish to configure your - // minifier not to mangle the names of these two functions. - - function Generator() {} - - function GeneratorFunction() {} - - function GeneratorFunctionPrototype() {} // This is a polyfill for %IteratorPrototype% for environments that - // don't natively support it. - - - var IteratorPrototype = {}; - - IteratorPrototype[iteratorSymbol] = function () { - return this; - }; - - var getProto = Object.getPrototypeOf; - var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); - - if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { - // This environment has a native %IteratorPrototype%; use it instead - // of the polyfill. - IteratorPrototype = NativeIteratorPrototype; - } - - var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); - GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; - GeneratorFunctionPrototype.constructor = GeneratorFunction; - GeneratorFunctionPrototype[toStringTagSymbol] = GeneratorFunction.displayName = "GeneratorFunction"; // Helper for defining the .next, .throw, and .return methods of the - // Iterator interface in terms of a single ._invoke method. - - function defineIteratorMethods(prototype) { - ["next", "throw", "return"].forEach(function (method) { - prototype[method] = function (arg) { - return this._invoke(method, arg); - }; - }); - } - - function isGeneratorFunction(genFun) { - var ctor = typeof genFun === "function" && genFun.constructor; - return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can - // do is to check its .name property. - (ctor.displayName || ctor.name) === "GeneratorFunction" : false; - } - - function mark(genFun) { - if (Object.setPrototypeOf) { - Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); - } else { - genFun.__proto__ = GeneratorFunctionPrototype; - - if (!(toStringTagSymbol in genFun)) { - genFun[toStringTagSymbol] = "GeneratorFunction"; - } - } - - genFun.prototype = Object.create(Gp); - return genFun; - } - // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test - // `hasOwn.call(value, "__await")` to determine if the yielded value is - // meant to be awaited. - - function awrap(arg) { - return { - __await: arg - }; - } - - function AsyncIterator(generator, PromiseImpl) { - function invoke(method, arg, resolve, reject) { - var record = tryCatch(generator[method], generator, arg); - - if (record.type === "throw") { - reject(record.arg); - } else { - var result = record.arg; - var value = result.value; - - if (value && _typeof(value) === "object" && hasOwn.call(value, "__await")) { - return PromiseImpl.resolve(value.__await).then(function (value) { - invoke("next", value, resolve, reject); - }, function (err) { - invoke("throw", err, resolve, reject); - }); - } - - return PromiseImpl.resolve(value).then(function (unwrapped) { - // When a yielded Promise is resolved, its final value becomes - // the .value of the Promise<{value,done}> result for the - // current iteration. - result.value = unwrapped; - resolve(result); - }, function (error) { - // If a rejected Promise was yielded, throw the rejection back - // into the async generator function so it can be handled there. - return invoke("throw", error, resolve, reject); - }); - } - } - - var previousPromise; - - function enqueue(method, arg) { - function callInvokeWithMethodAndArg() { - return new PromiseImpl(function (resolve, reject) { - invoke(method, arg, resolve, reject); - }); - } - - return previousPromise = // If enqueue has been called before, then we want to wait until - // all previous Promises have been resolved before calling invoke, - // so that results are always delivered in the correct order. If - // enqueue has not been called before, then it is important to - // call invoke immediately, without waiting on a callback to fire, - // so that the async generator function has the opportunity to do - // any necessary setup in a predictable way. This predictability - // is why the Promise constructor synchronously invokes its - // executor callback, and why async functions synchronously - // execute code before the first await. Since we implement simple - // async functions in terms of async generators, it is especially - // important to get this right, even though it requires care. - previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later - // invocations of the iterator. - callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); - } // Define the unified helper method that is used to implement .next, - // .throw, and .return (see defineIteratorMethods). - - - this._invoke = enqueue; - } - - defineIteratorMethods(AsyncIterator.prototype); - - AsyncIterator.prototype[asyncIteratorSymbol] = function () { - return this; - }; // Note that simple async functions are implemented on top of - // AsyncIterator objects; they just return a Promise for the value of - // the final result produced by the iterator. - - - function async(innerFn, outerFn, self, tryLocsList, PromiseImpl) { - if (PromiseImpl === void 0) PromiseImpl = Promise; - var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); - return isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator. - : iter.next().then(function (result) { - return result.done ? result.value : iter.next(); - }); - } - - function makeInvokeMethod(innerFn, self, context) { - var state = GenStateSuspendedStart; - return function invoke(method, arg) { - if (state === GenStateExecuting) { - throw new Error("Generator is already running"); - } - - if (state === GenStateCompleted) { - if (method === "throw") { - throw arg; - } // Be forgiving, per 25.3.3.3.3 of the spec: - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume - - - return doneResult(); - } - - context.method = method; - context.arg = arg; - - while (true) { - var delegate = context.delegate; - - if (delegate) { - var delegateResult = maybeInvokeDelegate(delegate, context); - - if (delegateResult) { - if (delegateResult === ContinueSentinel) continue; - return delegateResult; - } - } - - if (context.method === "next") { - // Setting context._sent for legacy support of Babel's - // function.sent implementation. - context.sent = context._sent = context.arg; - } else if (context.method === "throw") { - if (state === GenStateSuspendedStart) { - state = GenStateCompleted; - throw context.arg; - } - - context.dispatchException(context.arg); - } else if (context.method === "return") { - context.abrupt("return", context.arg); - } - - state = GenStateExecuting; - var record = tryCatch(innerFn, self, context); - - if (record.type === "normal") { - // If an exception is thrown from innerFn, we leave state === - // GenStateExecuting and loop back for another invocation. - state = context.done ? GenStateCompleted : GenStateSuspendedYield; - - if (record.arg === ContinueSentinel) { - continue; - } - - return { - value: record.arg, - done: context.done - }; - } else if (record.type === "throw") { - state = GenStateCompleted; // Dispatch the exception by looping back around to the - // context.dispatchException(context.arg) call above. - - context.method = "throw"; - context.arg = record.arg; - } - } - }; - } // Call delegate.iterator[context.method](context.arg) and handle the - // result, either by returning a { value, done } result from the - // delegate iterator, or by modifying context.method and context.arg, - // setting context.delegate to null, and returning the ContinueSentinel. - - - function maybeInvokeDelegate(delegate, context) { - var method = delegate.iterator[context.method]; - - if (method === undefined$1) { - // A .throw or .return when the delegate iterator has no .throw - // method always terminates the yield* loop. - context.delegate = null; - - if (context.method === "throw") { - // Note: ["return"] must be used for ES3 parsing compatibility. - if (delegate.iterator["return"]) { - // If the delegate iterator has a return method, give it a - // chance to clean up. - context.method = "return"; - context.arg = undefined$1; - maybeInvokeDelegate(delegate, context); - - if (context.method === "throw") { - // If maybeInvokeDelegate(context) changed context.method from - // "return" to "throw", let that override the TypeError below. - return ContinueSentinel; - } - } - - context.method = "throw"; - context.arg = new TypeError("The iterator does not provide a 'throw' method"); - } - - return ContinueSentinel; - } - - var record = tryCatch(method, delegate.iterator, context.arg); - - if (record.type === "throw") { - context.method = "throw"; - context.arg = record.arg; - context.delegate = null; - return ContinueSentinel; - } - - var info = record.arg; - - if (!info) { - context.method = "throw"; - context.arg = new TypeError("iterator result is not an object"); - context.delegate = null; - return ContinueSentinel; - } - - if (info.done) { - // Assign the result of the finished delegate to the temporary - // variable specified by delegate.resultName (see delegateYield). - context[delegate.resultName] = info.value; // Resume execution at the desired location (see delegateYield). - - context.next = delegate.nextLoc; // If context.method was "throw" but the delegate handled the - // exception, let the outer generator proceed normally. If - // context.method was "next", forget context.arg since it has been - // "consumed" by the delegate iterator. If context.method was - // "return", allow the original .return call to continue in the - // outer generator. - - if (context.method !== "return") { - context.method = "next"; - context.arg = undefined$1; - } - } else { - // Re-yield the result returned by the delegate method. - return info; - } // The delegate iterator is finished, so forget it and continue with - // the outer generator. - - - context.delegate = null; - return ContinueSentinel; - } // Define Generator.prototype.{next,throw,return} in terms of the - // unified ._invoke helper method. - - - defineIteratorMethods(Gp); - Gp[toStringTagSymbol] = "Generator"; // A Generator should always return itself as the iterator object when the - // @@iterator function is called on it. Some browsers' implementations of the - // iterator prototype chain incorrectly implement this, causing the Generator - // object to not be returned from this call. This ensures that doesn't happen. - // See https://github.com/facebook/regenerator/issues/274 for more details. - - Gp[iteratorSymbol] = function () { - return this; - }; - - Gp.toString = function () { - return "[object Generator]"; - }; - - function pushTryEntry(locs) { - var entry = { - tryLoc: locs[0] - }; - - if (1 in locs) { - entry.catchLoc = locs[1]; - } - - if (2 in locs) { - entry.finallyLoc = locs[2]; - entry.afterLoc = locs[3]; - } - - this.tryEntries.push(entry); - } - - function resetTryEntry(entry) { - var record = entry.completion || {}; - record.type = "normal"; - delete record.arg; - entry.completion = record; - } - - function Context(tryLocsList) { - // The root entry object (effectively a try statement without a catch - // or a finally block) gives us a place to store values thrown from - // locations where there is no enclosing try statement. - this.tryEntries = [{ - tryLoc: "root" - }]; - tryLocsList.forEach(pushTryEntry, this); - this.reset(true); - } - - function keys(object) { - var keys = []; - - for (var key in object) { - keys.push(key); - } - - keys.reverse(); // Rather than returning an object with a next method, we keep - // things simple and return the next function itself. - - return function next() { - while (keys.length) { - var key = keys.pop(); - - if (key in object) { - next.value = key; - next.done = false; - return next; - } - } // To avoid creating an additional object, we just hang the .value - // and .done properties off the next function object itself. This - // also ensures that the minifier will not anonymize the function. - - - next.done = true; - return next; - }; - } - - function values(iterable) { - if (iterable) { - var iteratorMethod = iterable[iteratorSymbol]; - - if (iteratorMethod) { - return iteratorMethod.call(iterable); - } - - if (typeof iterable.next === "function") { - return iterable; - } - - if (!isNaN(iterable.length)) { - var i = -1, - next = function next() { - while (++i < iterable.length) { - if (hasOwn.call(iterable, i)) { - next.value = iterable[i]; - next.done = false; - return next; - } - } - - next.value = undefined$1; - next.done = true; - return next; - }; - - return next.next = next; - } - } // Return an iterator with no values. - - - return { - next: doneResult - }; - } - - function doneResult() { - return { - value: undefined$1, - done: true - }; - } - - Context.prototype = { - constructor: Context, - reset: function reset(skipTempReset) { - this.prev = 0; - this.next = 0; // Resetting context._sent for legacy support of Babel's - // function.sent implementation. - - this.sent = this._sent = undefined$1; - this.done = false; - this.delegate = null; - this.method = "next"; - this.arg = undefined$1; - this.tryEntries.forEach(resetTryEntry); - - if (!skipTempReset) { - for (var name in this) { - // Not sure about the optimal order of these conditions: - if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) { - this[name] = undefined$1; - } - } - } - }, - stop: function stop() { - this.done = true; - var rootEntry = this.tryEntries[0]; - var rootRecord = rootEntry.completion; - - if (rootRecord.type === "throw") { - throw rootRecord.arg; - } - - return this.rval; - }, - dispatchException: function dispatchException(exception) { - if (this.done) { - throw exception; - } - - var context = this; - - function handle(loc, caught) { - record.type = "throw"; - record.arg = exception; - context.next = loc; - - if (caught) { - // If the dispatched exception was caught by a catch block, - // then let that catch block handle the exception normally. - context.method = "next"; - context.arg = undefined$1; - } - - return !!caught; - } - - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - var record = entry.completion; - - if (entry.tryLoc === "root") { - // Exception thrown outside of any try block that could handle - // it, so set the completion value of the entire function to - // throw the exception. - return handle("end"); - } - - if (entry.tryLoc <= this.prev) { - var hasCatch = hasOwn.call(entry, "catchLoc"); - var hasFinally = hasOwn.call(entry, "finallyLoc"); - - if (hasCatch && hasFinally) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } else if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - } else if (hasCatch) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } - } else if (hasFinally) { - if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - } else { - throw new Error("try statement without catch or finally"); - } - } - } - }, - abrupt: function abrupt(type, arg) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - - if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { - var finallyEntry = entry; - break; - } - } - - if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { - // Ignore the finally entry if control is not jumping to a - // location outside the try/catch block. - finallyEntry = null; - } - - var record = finallyEntry ? finallyEntry.completion : {}; - record.type = type; - record.arg = arg; - - if (finallyEntry) { - this.method = "next"; - this.next = finallyEntry.finallyLoc; - return ContinueSentinel; - } - - return this.complete(record); - }, - complete: function complete(record, afterLoc) { - if (record.type === "throw") { - throw record.arg; - } - - if (record.type === "break" || record.type === "continue") { - this.next = record.arg; - } else if (record.type === "return") { - this.rval = this.arg = record.arg; - this.method = "return"; - this.next = "end"; - } else if (record.type === "normal" && afterLoc) { - this.next = afterLoc; - } - - return ContinueSentinel; - }, - finish: function finish(finallyLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - - if (entry.finallyLoc === finallyLoc) { - this.complete(entry.completion, entry.afterLoc); - resetTryEntry(entry); - return ContinueSentinel; - } - } - }, - "catch": function _catch(tryLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - - if (entry.tryLoc === tryLoc) { - var record = entry.completion; - - if (record.type === "throw") { - var thrown = record.arg; - resetTryEntry(entry); - } - - return thrown; - } - } // The context.catch method must only be called with a location - // argument that corresponds to a known catch block. - - - throw new Error("illegal catch attempt"); - }, - delegateYield: function delegateYield(iterable, resultName, nextLoc) { - this.delegate = { - iterator: values(iterable), - resultName: resultName, - nextLoc: nextLoc - }; - - if (this.method === "next") { - // Deliberately forget the last sent value so that we don't - // accidentally pass it on to the delegate. - this.arg = undefined$1; - } - - return ContinueSentinel; - } - }; // Export a default namespace that plays well with Rollup - - var _regeneratorRuntime = { - wrap: wrap, - isGeneratorFunction: isGeneratorFunction, - AsyncIterator: AsyncIterator, - mark: mark, - awrap: awrap, - async: async, - keys: keys, - values: values - }; - - function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } - } - - function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); - } - } - - function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) _defineProperties(Constructor.prototype, protoProps); - if (staticProps) _defineProperties(Constructor, staticProps); - return Constructor; - } - - function isObject$5(value) { - var type = _typeof(value); - - return value != null && (type == 'object' || type == 'function'); - } - - var isObject_1 = isObject$5; - - var freeGlobal$1 = _typeof(commonjsGlobal) == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; - var _freeGlobal = freeGlobal$1; - - var freeGlobal = _freeGlobal; - /** Detect free variable `self`. */ - - var freeSelf = (typeof self === "undefined" ? "undefined" : _typeof(self)) == 'object' && self && self.Object === Object && self; - /** Used as a reference to the global object. */ - - var root$2 = freeGlobal || freeSelf || Function('return this')(); - var _root = root$2; - - var root$1 = _root; - /** - * Gets the timestamp of the number of milliseconds that have elapsed since - * the Unix epoch (1 January 1970 00:00:00 UTC). - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Date - * @returns {number} Returns the timestamp. - * @example - * - * _.defer(function(stamp) { - * console.log(_.now() - stamp); - * }, _.now()); - * // => Logs the number of milliseconds it took for the deferred invocation. - */ - - var now$1 = function now() { - return root$1.Date.now(); - }; - - var now_1 = now$1; - - /** Used to match a single whitespace character. */ - var reWhitespace = /\s/; - /** - * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace - * character of `string`. - * - * @private - * @param {string} string The string to inspect. - * @returns {number} Returns the index of the last non-whitespace character. - */ - - function trimmedEndIndex$1(string) { - var index = string.length; - - while (index-- && reWhitespace.test(string.charAt(index))) {} - - return index; - } - - var _trimmedEndIndex = trimmedEndIndex$1; - - var trimmedEndIndex = _trimmedEndIndex; - /** Used to match leading whitespace. */ - - var reTrimStart = /^\s+/; - /** - * The base implementation of `_.trim`. - * - * @private - * @param {string} string The string to trim. - * @returns {string} Returns the trimmed string. - */ - - function baseTrim$1(string) { - return string ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '') : string; - } - - var _baseTrim = baseTrim$1; - - var root = _root; - /** Built-in value references. */ - - var _Symbol2 = root.Symbol; - var _Symbol$2 = _Symbol2; - - var _Symbol$1 = _Symbol$2; - /** Used for built-in method references. */ - - var objectProto$1 = Object.prototype; - /** Used to check objects for own properties. */ - - var hasOwnProperty = objectProto$1.hasOwnProperty; - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - - var nativeObjectToString$1 = objectProto$1.toString; - /** Built-in value references. */ - - var symToStringTag$1 = _Symbol$1 ? _Symbol$1.toStringTag : undefined; - /** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. - */ - - function getRawTag$1(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag$1), - tag = value[symToStringTag$1]; - - try { - value[symToStringTag$1] = undefined; - var unmasked = true; - } catch (e) {} - - var result = nativeObjectToString$1.call(value); - - if (unmasked) { - if (isOwn) { - value[symToStringTag$1] = tag; - } else { - delete value[symToStringTag$1]; - } - } - - return result; - } - - var _getRawTag = getRawTag$1; - - /** Used for built-in method references. */ - var objectProto = Object.prototype; - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - - var nativeObjectToString = objectProto.toString; - /** - * Converts `value` to a string using `Object.prototype.toString`. - * - * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - */ - - function objectToString$1(value) { - return nativeObjectToString.call(value); - } - - var _objectToString = objectToString$1; - - var _Symbol = _Symbol$2, - getRawTag = _getRawTag, - objectToString = _objectToString; - /** `Object#toString` result references. */ - - var nullTag = '[object Null]', - undefinedTag = '[object Undefined]'; - /** Built-in value references. */ - - var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined; - /** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - - function baseGetTag$1(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; - } - - return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value); - } - - var _baseGetTag = baseGetTag$1; - - function isObjectLike$1(value) { - return value != null && _typeof(value) == 'object'; - } - - var isObjectLike_1 = isObjectLike$1; - - var baseGetTag = _baseGetTag, - isObjectLike = isObjectLike_1; - /** `Object#toString` result references. */ - - var symbolTag = '[object Symbol]'; - /** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ - - function isSymbol$1(value) { - return _typeof(value) == 'symbol' || isObjectLike(value) && baseGetTag(value) == symbolTag; - } - - var isSymbol_1 = isSymbol$1; - - var baseTrim = _baseTrim, - isObject$4 = isObject_1, - isSymbol = isSymbol_1; - /** Used as references for various `Number` constants. */ - - var NAN = 0 / 0; - /** Used to detect bad signed hexadecimal string values. */ - - var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - /** Used to detect binary string values. */ - - var reIsBinary = /^0b[01]+$/i; - /** Used to detect octal string values. */ - - var reIsOctal = /^0o[0-7]+$/i; - /** Built-in method references without a dependency on `root`. */ - - var freeParseInt = parseInt; - /** - * Converts `value` to a number. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. - * @example - * - * _.toNumber(3.2); - * // => 3.2 - * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toNumber(Infinity); - * // => Infinity - * - * _.toNumber('3.2'); - * // => 3.2 - */ - - function toNumber$1(value) { - if (typeof value == 'number') { - return value; - } - - if (isSymbol(value)) { - return NAN; - } - - if (isObject$4(value)) { - var other = typeof value.valueOf == 'function' ? value.valueOf() : value; - value = isObject$4(other) ? other + '' : other; - } - - if (typeof value != 'string') { - return value === 0 ? value : +value; - } - - value = baseTrim(value); - var isBinary = reIsBinary.test(value); - return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value; - } - - var toNumber_1 = toNumber$1; - - var isObject$3 = isObject_1, - now = now_1, - toNumber = toNumber_1; - /** Error message constants. */ - - var FUNC_ERROR_TEXT = 'Expected a function'; - /* Built-in method references for those with the same name as other `lodash` methods. */ - - var nativeMax = Math.max, - nativeMin = Math.min; - /** - * Creates a debounced function that delays invoking `func` until after `wait` - * milliseconds have elapsed since the last time the debounced function was - * invoked. The debounced function comes with a `cancel` method to cancel - * delayed `func` invocations and a `flush` method to immediately invoke them. - * Provide `options` to indicate whether `func` should be invoked on the - * leading and/or trailing edge of the `wait` timeout. The `func` is invoked - * with the last arguments provided to the debounced function. Subsequent - * calls to the debounced function return the result of the last `func` - * invocation. - * - * **Note:** If `leading` and `trailing` options are `true`, `func` is - * invoked on the trailing edge of the timeout only if the debounced function - * is invoked more than once during the `wait` timeout. - * - * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred - * until to the next tick, similar to `setTimeout` with a timeout of `0`. - * - * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) - * for details over the differences between `_.debounce` and `_.throttle`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to debounce. - * @param {number} [wait=0] The number of milliseconds to delay. - * @param {Object} [options={}] The options object. - * @param {boolean} [options.leading=false] - * Specify invoking on the leading edge of the timeout. - * @param {number} [options.maxWait] - * The maximum time `func` is allowed to be delayed before it's invoked. - * @param {boolean} [options.trailing=true] - * Specify invoking on the trailing edge of the timeout. - * @returns {Function} Returns the new debounced function. - * @example - * - * // Avoid costly calculations while the window size is in flux. - * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); - * - * // Invoke `sendMail` when clicked, debouncing subsequent calls. - * jQuery(element).on('click', _.debounce(sendMail, 300, { - * 'leading': true, - * 'trailing': false - * })); - * - * // Ensure `batchLog` is invoked once after 1 second of debounced calls. - * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); - * var source = new EventSource('/stream'); - * jQuery(source).on('message', debounced); - * - * // Cancel the trailing debounced invocation. - * jQuery(window).on('popstate', debounced.cancel); - */ - - function debounce(func, wait, options) { - var lastArgs, - lastThis, - maxWait, - result, - timerId, - lastCallTime, - lastInvokeTime = 0, - leading = false, - maxing = false, - trailing = true; - - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - - wait = toNumber(wait) || 0; - - if (isObject$3(options)) { - leading = !!options.leading; - maxing = 'maxWait' in options; - maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; - trailing = 'trailing' in options ? !!options.trailing : trailing; - } - - function invokeFunc(time) { - var args = lastArgs, - thisArg = lastThis; - lastArgs = lastThis = undefined; - lastInvokeTime = time; - result = func.apply(thisArg, args); - return result; - } - - function leadingEdge(time) { - // Reset any `maxWait` timer. - lastInvokeTime = time; // Start the timer for the trailing edge. - - timerId = setTimeout(timerExpired, wait); // Invoke the leading edge. - - return leading ? invokeFunc(time) : result; - } - - function remainingWait(time) { - var timeSinceLastCall = time - lastCallTime, - timeSinceLastInvoke = time - lastInvokeTime, - timeWaiting = wait - timeSinceLastCall; - return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting; - } - - function shouldInvoke(time) { - var timeSinceLastCall = time - lastCallTime, - timeSinceLastInvoke = time - lastInvokeTime; // Either this is the first call, activity has stopped and we're at the - // trailing edge, the system time has gone backwards and we're treating - // it as the trailing edge, or we've hit the `maxWait` limit. - - return lastCallTime === undefined || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait; - } - - function timerExpired() { - var time = now(); - - if (shouldInvoke(time)) { - return trailingEdge(time); - } // Restart the timer. - - - timerId = setTimeout(timerExpired, remainingWait(time)); - } - - function trailingEdge(time) { - timerId = undefined; // Only invoke if we have `lastArgs` which means `func` has been - // debounced at least once. - - if (trailing && lastArgs) { - return invokeFunc(time); - } - - lastArgs = lastThis = undefined; - return result; - } - - function cancel() { - if (timerId !== undefined) { - clearTimeout(timerId); - } - - lastInvokeTime = 0; - lastArgs = lastCallTime = lastThis = timerId = undefined; - } - - function flush() { - return timerId === undefined ? result : trailingEdge(now()); - } - - function debounced() { - var time = now(), - isInvoking = shouldInvoke(time); - lastArgs = arguments; - lastThis = this; - lastCallTime = time; - - if (isInvoking) { - if (timerId === undefined) { - return leadingEdge(lastCallTime); - } - - if (maxing) { - // Handle invocations in a tight loop. - clearTimeout(timerId); - timerId = setTimeout(timerExpired, wait); - return invokeFunc(lastCallTime); - } - } - - if (timerId === undefined) { - timerId = setTimeout(timerExpired, wait); - } - - return result; - } - - debounced.cancel = cancel; - debounced.flush = flush; - return debounced; - } - - var debounce_1 = debounce; - - /** - * @hidden - */ - - var reset = "border:0px;padding:0px;"; - /** - * @hidden - */ - - var hidden = "clip:rect(0px,0px,0px,0px);height:1px;margin-bottom:-1px;margin-right:-1px;overflow:hidden;position:absolute;white-space:nowrap;width:1px"; - /** - * @hidden - */ - - var update$1 = function update(e, id) { - e.id = id; - e.setAttribute("role", "status"); - e.setAttribute("aria-live", "polite"); - e.setAttribute("aria-atomic", "true"); - return e; - }; - /** - * Generates a screen reader compatible live area for announcements - * - * @hidden - */ - - - var announcer = function announcer(_ref) { - var document = _ref.document, - idA = _ref.idA, - idB = _ref.idB; - var container = document.createElement("div"); - container.setAttribute("style", reset + hidden); - var a = update$1(document.createElement("div"), idA); - var b = update$1(document.createElement("div"), idB); - container.appendChild(a); - container.appendChild(b); - var A = true; - var announce = debounce_1(function (message) { - var announcer = A ? a : b; - var backup = A ? b : a; - A = !A; - announcer.textContent = message; - backup.textContent = ""; - }, 1500, {}); - return { - container: container, - announce: announce - }; - }; - - var defaultContexts = { - GBR: { - name: "United Kingdom", - icon: "πŸ‡¬πŸ‡§" - }, - USA: { - name: "United States", - icon: "πŸ‡ΊπŸ‡Έ" - } - }; - var toContextList = function toContextList(contexts, restrictCountries) { - var result = []; - var codes = Object.keys(contexts); - - var _loop = function _loop() { - var code = _codes[_i]; - if (restrictCountries.length > 0 && !restrictCountries.some(function (e) { - return e === code; - })) return "continue"; - var _contexts$code = contexts[code], - name = _contexts$code.name, - icon = _contexts$code.icon; - result.push({ - code: code, - name: name, - icon: icon - }); - }; - - for (var _i = 0, _codes = codes; _i < _codes.length; _i++) { - var _ret = _loop(); - - if (_ret === "continue") continue; - } - - result.sort(function (b, a) { - return b.name.localeCompare(a.name); - }); - return result; - }; - - function ownKeys$8(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - - function _objectSpread$8(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$8(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$8(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - - /** - * @module Client - * - * @description HTTP API Client - */ - - /** - * Default configuration - */ - var defaults$b = { - tls: true, - api_key: "", - baseUrl: "api.ideal-postcodes.co.uk", - version: "v1", - strictAuthorisation: false, - timeout: 10000, - header: { - Accept: "application/json", - "Content-Type": "application/json" - }, - tags: [], - agent: {} - }; - /** - * Client Class - */ - - var Client$1 = /*#__PURE__*/function () { - function Client(config) { - _classCallCheck(this, Client); - - this.config = _objectSpread$8(_objectSpread$8({}, defaults$b), config); - this.config.header = _objectSpread$8(_objectSpread$8({}, defaults$b.header), config.header && config.header); - } - /** - * Return base URL for API requests - */ - - - _createClass(Client, [{ - key: "url", - value: function url() { - var _this$config = this.config, - baseUrl = _this$config.baseUrl, - version = _this$config.version; - return "".concat(this.protocol(), "://").concat(baseUrl, "/").concat(version); - } - }, { - key: "protocol", - value: function protocol() { - return this.config.tls ? "https" : "http"; - } - }]); - - return Client; - }(); - - function ownKeys$7(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - - function _objectSpread$7(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$7(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$7(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - - /** - * @module Utils - */ - - /** - * toQuery - * - * Shallow copies object while omitting undefined attributes - */ - var toStringMap = function toStringMap(optional) { - if (optional === undefined) return {}; - return Object.keys(optional).reduce(function (result, key) { - var value = optional[key]; - var reduce = reduceStringMap(value); - if (reduce.length > 0) result[key] = reduce; - return result; - }, {}); - }; - - var isString$3 = function isString(i) { - return typeof i === "string"; - }; - - var isArray$2 = function isArray(i) { - return Array.isArray(i); - }; - - var reduceStringMap = function reduceStringMap(value) { - var result = []; - - if (isArray$2(value)) { - value.forEach(function (val) { - if (isNumber$2(val)) result.push(val.toString()); - if (isString$3(val)) result.push(val); - }); - return result.join(","); - } - - if (isNumber$2(value)) return value.toString(); - if (isString$3(value)) return value; - return ""; - }; - - var isNumber$2 = function isNumber(n) { - return typeof n === "number"; - }; - /** - * toTimeout - * - * Returns timeout value from request object. Delegates to default client - * timeout if not specified - */ - - - var toTimeout = function toTimeout(_ref, client) { - var timeout = _ref.timeout; - if (isNumber$2(timeout)) return timeout; - return client.config.timeout; - }; - /** - * toHeader - * - * Extracts HTTP Header object from request and client default headers - * - * Precendence is given to request specific headers - */ - - var toHeader$1 = function toHeader(_ref2, client) { - var _ref2$header = _ref2.header, - header = _ref2$header === void 0 ? {} : _ref2$header; - return _objectSpread$7(_objectSpread$7({}, client.config.header), toStringMap(header)); - }; - - function _assertThisInitialized(self) { - if (self === void 0) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - } - - return self; - } - - function _setPrototypeOf(o, p) { - _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { - o.__proto__ = p; - return o; - }; - - return _setPrototypeOf(o, p); - } - - function _inherits(subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError("Super expression must either be null or a function"); - } - - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - writable: true, - configurable: true - } - }); - if (superClass) _setPrototypeOf(subClass, superClass); - } - - function _possibleConstructorReturn(self, call) { - if (call && (_typeof(call) === "object" || typeof call === "function")) { - return call; - } else if (call !== void 0) { - throw new TypeError("Derived constructors may only return object or undefined"); - } - - return _assertThisInitialized(self); - } - - function _getPrototypeOf(o) { - _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { - return o.__proto__ || Object.getPrototypeOf(o); - }; - return _getPrototypeOf(o); - } - - function _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; - } - - function _isNativeReflectConstruct$2() { - if (typeof Reflect === "undefined" || !Reflect.construct) return false; - if (Reflect.construct.sham) return false; - if (typeof Proxy === "function") return true; - - try { - Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); - return true; - } catch (e) { - return false; - } - } - - function _construct(Parent, args, Class) { - if (_isNativeReflectConstruct$2()) { - _construct = Reflect.construct; - } else { - _construct = function _construct(Parent, args, Class) { - var a = [null]; - a.push.apply(a, args); - var Constructor = Function.bind.apply(Parent, a); - var instance = new Constructor(); - if (Class) _setPrototypeOf(instance, Class.prototype); - return instance; - }; - } - - return _construct.apply(null, arguments); - } - - function _wrapNativeSuper(Class) { - var _cache = typeof Map === "function" ? new Map() : undefined; - - _wrapNativeSuper = function _wrapNativeSuper(Class) { - if (Class === null || !_isNativeFunction(Class)) return Class; - - if (typeof Class !== "function") { - throw new TypeError("Super expression must either be null or a function"); - } - - if (typeof _cache !== "undefined") { - if (_cache.has(Class)) return _cache.get(Class); - - _cache.set(Class, Wrapper); - } - - function Wrapper() { - return _construct(Class, arguments, _getPrototypeOf(this).constructor); - } - - Wrapper.prototype = Object.create(Class.prototype, { - constructor: { - value: Wrapper, - enumerable: false, - writable: true, - configurable: true - } - }); - return _setPrototypeOf(Wrapper, Class); - }; - - return _wrapNativeSuper(Class); - } - - function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } - - function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } - - /** - * @module Errors - * - * @description Exports error classes which may be returned by this client - */ - // Take note of https://github.com/Microsoft/TypeScript/issues/13965 - - /** - * IdealPostcodesError - * - * Base error class for all API responses that return an error. This class - * is used where a JSON body is not provided or invalid - * E.g. 503 rate limit response, JSON parse failure response - */ - var IdealPostcodesError$1 = /*#__PURE__*/function (_Error) { - _inherits(IdealPostcodesError, _Error); - - var _super = _createSuper$1(IdealPostcodesError); - - /** - * Instantiate IdealPostcodesError - */ - function IdealPostcodesError(options) { - var _this; - - _classCallCheck(this, IdealPostcodesError); - - var trueProto = (this instanceof IdealPostcodesError ? this.constructor : void 0).prototype; - _this = _super.call(this); - _this.__proto__ = trueProto; - var message = options.message, - httpStatus = options.httpStatus, - _options$metadata = options.metadata, - metadata = _options$metadata === void 0 ? {} : _options$metadata; - _this.message = message; - _this.name = "Ideal Postcodes Error"; - _this.httpStatus = httpStatus; - _this.metadata = metadata; - - if (Error.captureStackTrace) { - Error.captureStackTrace(_assertThisInitialized(_this), IdealPostcodesError); - } - - return _this; - } - - return IdealPostcodesError; - }( /*#__PURE__*/_wrapNativeSuper(Error)); - /** - * IdpcApiError - * - * Base error class for API responses with a JSON body. Typically a subclass - * will be used to capture the error category (e.g. 400, 401, 500, etc) - */ - - var IdpcApiError = /*#__PURE__*/function (_IdealPostcodesError) { - _inherits(IdpcApiError, _IdealPostcodesError); - - var _super2 = _createSuper$1(IdpcApiError); - - /** - * Returns an API error instance - */ - function IdpcApiError(httpResponse) { - var _this2; - - _classCallCheck(this, IdpcApiError); - - _this2 = _super2.call(this, { - httpStatus: httpResponse.httpStatus, - message: httpResponse.body.message - }); - _this2.response = httpResponse; - return _this2; - } - - return IdpcApiError; - }(IdealPostcodesError$1); - /** - * IdpcBadRequestError - * - * Captures API responses that return a 400 (Bad Request Error) response - * - * Examples include: - * - Invalid syntax submitted - * - Invalid date range submitted - * - Invalid tag submitted - */ - - var IdpcBadRequestError = /*#__PURE__*/function (_IdpcApiError) { - _inherits(IdpcBadRequestError, _IdpcApiError); - - var _super3 = _createSuper$1(IdpcBadRequestError); - - function IdpcBadRequestError() { - _classCallCheck(this, IdpcBadRequestError); - - return _super3.apply(this, arguments); - } - - return IdpcBadRequestError; - }(IdpcApiError); - /** - * IdpcUnauthorisedError - * - * Captures API responses that return a 401 (Unauthorised) response - * - * Examples include: - * - Invalid api_key - * - Invalid user_token - * - Invalid licensee - */ - - var IdpcUnauthorisedError = /*#__PURE__*/function (_IdpcApiError2) { - _inherits(IdpcUnauthorisedError, _IdpcApiError2); - - var _super4 = _createSuper$1(IdpcUnauthorisedError); - - function IdpcUnauthorisedError() { - _classCallCheck(this, IdpcUnauthorisedError); - - return _super4.apply(this, arguments); - } - - return IdpcUnauthorisedError; - }(IdpcApiError); - /** - * IpdcInvalidKeyError - * - * Invalid API Key presented for request - */ - - var IdpcInvalidKeyError = /*#__PURE__*/function (_IdpcUnauthorisedErro) { - _inherits(IdpcInvalidKeyError, _IdpcUnauthorisedErro); - - var _super5 = _createSuper$1(IdpcInvalidKeyError); - - function IdpcInvalidKeyError() { - _classCallCheck(this, IdpcInvalidKeyError); - - return _super5.apply(this, arguments); - } - - return IdpcInvalidKeyError; - }(IdpcUnauthorisedError); - /** - * IdpcRequestFailedError - * - * Captures API responses that return a 402 (Request Failed) response - * - * Examples include: - * - Key balance depleted - * - Daily key limit reached - */ - - var IdpcRequestFailedError = /*#__PURE__*/function (_IdpcApiError3) { - _inherits(IdpcRequestFailedError, _IdpcApiError3); - - var _super6 = _createSuper$1(IdpcRequestFailedError); - - function IdpcRequestFailedError() { - _classCallCheck(this, IdpcRequestFailedError); - - return _super6.apply(this, arguments); - } - - return IdpcRequestFailedError; - }(IdpcApiError); - /** - * IdpcBalanceDepleted - * - * Balance on key has been depleted - */ - - var IdpcBalanceDepletedError = /*#__PURE__*/function (_IdpcRequestFailedErr) { - _inherits(IdpcBalanceDepletedError, _IdpcRequestFailedErr); - - var _super7 = _createSuper$1(IdpcBalanceDepletedError); - - function IdpcBalanceDepletedError() { - _classCallCheck(this, IdpcBalanceDepletedError); - - return _super7.apply(this, arguments); - } - - return IdpcBalanceDepletedError; - }(IdpcRequestFailedError); - /** - * IdpcLimitReachedError - * - * Limit reached. One of your lookup limits has been breached for today. This - * could either be your total daily limit on your key or the individual IP - * limit. You can either wait for for the limit to reset (after a day) or - * manually disable or increase your limit. - */ - - var IdpcLimitReachedError = /*#__PURE__*/function (_IdpcRequestFailedErr2) { - _inherits(IdpcLimitReachedError, _IdpcRequestFailedErr2); - - var _super8 = _createSuper$1(IdpcLimitReachedError); - - function IdpcLimitReachedError() { - _classCallCheck(this, IdpcLimitReachedError); - - return _super8.apply(this, arguments); - } - - return IdpcLimitReachedError; - }(IdpcRequestFailedError); - /** - * IdpcResourceNotFoundError - * - * Captures API responses that return a 404 (Resource Not Found) response - * - * Examples include: - * - Postcode not found - * - UDPRN not found - * - Key not found - */ - - var IdpcResourceNotFoundError = /*#__PURE__*/function (_IdpcApiError4) { - _inherits(IdpcResourceNotFoundError, _IdpcApiError4); - - var _super9 = _createSuper$1(IdpcResourceNotFoundError); - - function IdpcResourceNotFoundError() { - _classCallCheck(this, IdpcResourceNotFoundError); - - return _super9.apply(this, arguments); - } - - return IdpcResourceNotFoundError; - }(IdpcApiError); - /** - * IdpcPostcodeNotFoundError - * - * Requested postcode does not exist - */ - - var IdpcPostcodeNotFoundError = /*#__PURE__*/function (_IdpcResourceNotFound) { - _inherits(IdpcPostcodeNotFoundError, _IdpcResourceNotFound); - - var _super10 = _createSuper$1(IdpcPostcodeNotFoundError); - - function IdpcPostcodeNotFoundError() { - _classCallCheck(this, IdpcPostcodeNotFoundError); - - return _super10.apply(this, arguments); - } - - return IdpcPostcodeNotFoundError; - }(IdpcResourceNotFoundError); - /** - * IdpcKeyNotFoundError - * - * Requested API Key does not exist - */ - - var IdpcKeyNotFoundError = /*#__PURE__*/function (_IdpcResourceNotFound2) { - _inherits(IdpcKeyNotFoundError, _IdpcResourceNotFound2); - - var _super11 = _createSuper$1(IdpcKeyNotFoundError); - - function IdpcKeyNotFoundError() { - _classCallCheck(this, IdpcKeyNotFoundError); - - return _super11.apply(this, arguments); - } - - return IdpcKeyNotFoundError; - }(IdpcResourceNotFoundError); - /** - * IdpcUdprnNotFoundError - * - * Requested UDPRN does not exist - */ - - var IdpcUdprnNotFoundError = /*#__PURE__*/function (_IdpcResourceNotFound3) { - _inherits(IdpcUdprnNotFoundError, _IdpcResourceNotFound3); - - var _super12 = _createSuper$1(IdpcUdprnNotFoundError); - - function IdpcUdprnNotFoundError() { - _classCallCheck(this, IdpcUdprnNotFoundError); - - return _super12.apply(this, arguments); - } - - return IdpcUdprnNotFoundError; - }(IdpcResourceNotFoundError); - /** - * IdpcUmprnNotFoundError - * - * Requested UMPRN does not exist - */ - - var IdpcUmprnNotFoundError = /*#__PURE__*/function (_IdpcResourceNotFound4) { - _inherits(IdpcUmprnNotFoundError, _IdpcResourceNotFound4); - - var _super13 = _createSuper$1(IdpcUmprnNotFoundError); - - function IdpcUmprnNotFoundError() { - _classCallCheck(this, IdpcUmprnNotFoundError); - - return _super13.apply(this, arguments); - } - - return IdpcUmprnNotFoundError; - }(IdpcResourceNotFoundError); - /** - * IdpcServerError - * - * Captures API responses that return a 500 (Server Error) response - */ - - var IdpcServerError = /*#__PURE__*/function (_IdpcApiError5) { - _inherits(IdpcServerError, _IdpcApiError5); - - var _super14 = _createSuper$1(IdpcServerError); - - function IdpcServerError() { - _classCallCheck(this, IdpcServerError); - - return _super14.apply(this, arguments); - } - - return IdpcServerError; - }(IdpcApiError); // 200 Responses - - var OK = 200; // 300 Responses - - var REDIRECT = 300; // 400 Responses - - var BAD_REQUEST = 400; // 401 Responses - - var UNAUTHORISED = 401; - var INVALID_KEY = 4010; // 402 Responses - - var PAYMENT_REQUIRED = 402; - var BALANCE_DEPLETED = 4020; - var LIMIT_REACHED = 4021; // 404 Responses - - var NOT_FOUND = 404; - var POSTCODE_NOT_FOUND = 4040; - var KEY_NOT_FOUND = 4042; - var UDPRN_NOT_FOUND = 4044; - var UMPRN_NOT_FOUND = 4046; // 500 Responses - - var SERVER_ERROR = 500; - - var isSuccess = function isSuccess(code) { - if (code < OK) return false; - if (code >= REDIRECT) return false; - return true; - }; - - var isObject$2 = function isObject(o) { - if (o === null) return false; - if (_typeof(o) !== "object") return false; - return true; - }; - - var isErrorResponse = function isErrorResponse(body) { - if (!isObject$2(body)) return false; - if (typeof body.message !== "string") return false; - if (typeof body.code !== "number") return false; - return true; - }; - /** - * parse - * - * Parses API responses and returns an error for non 2xx responses - * - * Upon detecting an error an instance of IdealPostcodesError is returned - */ - - - var parse = function parse(response) { - var httpStatus = response.httpStatus, - body = response.body; - if (isSuccess(httpStatus)) return; - - if (isErrorResponse(body)) { - // Test for specific API errors of interest - var code = body.code; - if (code === INVALID_KEY) return new IdpcInvalidKeyError(response); - if (code === POSTCODE_NOT_FOUND) return new IdpcPostcodeNotFoundError(response); - if (code === KEY_NOT_FOUND) return new IdpcKeyNotFoundError(response); - if (code === UDPRN_NOT_FOUND) return new IdpcUdprnNotFoundError(response); - if (code === UMPRN_NOT_FOUND) return new IdpcUmprnNotFoundError(response); - if (code === BALANCE_DEPLETED) return new IdpcBalanceDepletedError(response); - if (code === LIMIT_REACHED) return new IdpcLimitReachedError(response); // If no API errors of interest detected, fall back to http status code - - if (httpStatus === NOT_FOUND) return new IdpcResourceNotFoundError(response); - if (httpStatus === BAD_REQUEST) return new IdpcBadRequestError(response); - if (httpStatus === PAYMENT_REQUIRED) return new IdpcRequestFailedError(response); - if (httpStatus === UNAUTHORISED) return new IdpcUnauthorisedError(response); - if (httpStatus === SERVER_ERROR) return new IdpcServerError(response); - } // Generate generic error (backstop) - - - return new IdealPostcodesError$1({ - httpStatus: httpStatus, - message: JSON.stringify(body) - }); - }; - - var toRetrieveUrl = function toRetrieveUrl(options, id) { - return [options.client.url(), options.resource, encodeURIComponent(id), options.action].filter(function (e) { - return e !== undefined; - }).join("/"); - }; - - var retrieveMethod = function retrieveMethod(options) { - var client = options.client; - return function (id, request) { - return client.config.agent.http({ - method: "GET", - url: toRetrieveUrl(options, id), - query: toStringMap(request.query), - header: toHeader$1(request, client), - timeout: toTimeout(request, client) - }).then(function (response) { - var error = parse(response); - if (error) throw error; - return response; - }); - }; - }; - var listMethod = function listMethod(options) { - var client = options.client, - resource = options.resource; - return function (request) { - return client.config.agent.http({ - method: "GET", - url: "".concat(client.url(), "/").concat(resource), - query: toStringMap(request.query), - header: toHeader$1(request, client), - timeout: toTimeout(request, client) - }).then(function (response) { - var error = parse(response); - if (error) throw error; - return response; - }); - }; - }; - - var resource$1 = "keys"; - var retrieve = function retrieve(client, apiKey, request) { - return retrieveMethod({ - resource: resource$1, - client: client - })(apiKey, request); - }; - - /** - * @module Helper Methods - */ - /** - * Check Key Availability - * - * Checks if a key can bey used - * - * [API Documentation for /keys]()https://ideal-postcodes.co.uk/documentation/keys#key) - */ - - var checkKeyUsability = function checkKeyUsability(options) { - var client = options.client, - timeout = options.timeout; - var api_key = options.api_key || options.client.config.api_key; - var licensee = options.licensee; - var query; - - if (licensee === undefined) { - query = {}; - } else { - query = { - licensee: licensee - }; - } - - var queryOptions = { - query: query, - header: {} - }; - if (timeout !== undefined) queryOptions.timeout = timeout; - return retrieve(client, api_key, queryOptions).then(function (response) { - return response.body.result; - }); // Assert that we're retrieving public key information as no user_token provided - }; - - var resource = "autocomplete/addresses"; - var list = function list(client, request) { - return listMethod({ - resource: resource, - client: client - })(request); - }; // Resolves address to the GBR format - - var gbr = function gbr(client, id, request) { - return retrieveMethod({ - resource: resource, - client: client, - action: "gbr" - })(id, request); - }; - - var axios$4 = {exports: {}}; - - var bind$9 = function bind(fn, thisArg) { - return function wrap() { - var args = new Array(arguments.length); - - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } - - return fn.apply(thisArg, args); - }; - }; - - var bind$8 = bind$9; // utils is a library of generic helper functions non-specific to axios - - var toString$1 = Object.prototype.toString; - /** - * Determine if a value is an Array - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an Array, otherwise false - */ - - function isArray$1(val) { - return toString$1.call(val) === '[object Array]'; - } - /** - * Determine if a value is undefined - * - * @param {Object} val The value to test - * @returns {boolean} True if the value is undefined, otherwise false - */ - - - function isUndefined$1(val) { - return typeof val === 'undefined'; - } - /** - * Determine if a value is a Buffer - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Buffer, otherwise false - */ - - - function isBuffer$1(val) { - return val !== null && !isUndefined$1(val) && val.constructor !== null && !isUndefined$1(val.constructor) && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); - } - /** - * Determine if a value is an ArrayBuffer - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an ArrayBuffer, otherwise false - */ - - - function isArrayBuffer$1(val) { - return toString$1.call(val) === '[object ArrayBuffer]'; - } - /** - * Determine if a value is a FormData - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an FormData, otherwise false - */ - - - function isFormData$1(val) { - return typeof FormData !== 'undefined' && val instanceof FormData; - } - /** - * Determine if a value is a view on an ArrayBuffer - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false - */ - - - function isArrayBufferView$1(val) { - var result; - - if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) { - result = ArrayBuffer.isView(val); - } else { - result = val && val.buffer && val.buffer instanceof ArrayBuffer; - } - - return result; - } - /** - * Determine if a value is a String - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a String, otherwise false - */ - - - function isString$2(val) { - return typeof val === 'string'; - } - /** - * Determine if a value is a Number - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Number, otherwise false - */ - - - function isNumber$1(val) { - return typeof val === 'number'; - } - /** - * Determine if a value is an Object - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an Object, otherwise false - */ - - - function isObject$1(val) { - return val !== null && _typeof(val) === 'object'; - } - /** - * Determine if a value is a plain Object - * - * @param {Object} val The value to test - * @return {boolean} True if value is a plain Object, otherwise false - */ - - - function isPlainObject$1(val) { - if (toString$1.call(val) !== '[object Object]') { - return false; - } - - var prototype = Object.getPrototypeOf(val); - return prototype === null || prototype === Object.prototype; - } - /** - * Determine if a value is a Date - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Date, otherwise false - */ - - - function isDate$1(val) { - return toString$1.call(val) === '[object Date]'; - } - /** - * Determine if a value is a File - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a File, otherwise false - */ - - - function isFile$1(val) { - return toString$1.call(val) === '[object File]'; - } - /** - * Determine if a value is a Blob - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Blob, otherwise false - */ - - - function isBlob$1(val) { - return toString$1.call(val) === '[object Blob]'; - } - /** - * Determine if a value is a Function - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Function, otherwise false - */ - - - function isFunction$1(val) { - return toString$1.call(val) === '[object Function]'; - } - /** - * Determine if a value is a Stream - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Stream, otherwise false - */ - - - function isStream$1(val) { - return isObject$1(val) && isFunction$1(val.pipe); - } - /** - * Determine if a value is a URLSearchParams object - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a URLSearchParams object, otherwise false - */ - - - function isURLSearchParams$1(val) { - return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; - } - /** - * Trim excess whitespace off the beginning and end of a string - * - * @param {String} str The String to trim - * @returns {String} The String freed of excess whitespace - */ - - - function trim$1(str) { - return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, ''); - } - /** - * Determine if we're running in a standard browser environment - * - * This allows axios to run in a web worker, and react-native. - * Both environments support XMLHttpRequest, but not fully standard globals. - * - * web workers: - * typeof window -> undefined - * typeof document -> undefined - * - * react-native: - * navigator.product -> 'ReactNative' - * nativescript - * navigator.product -> 'NativeScript' or 'NS' - */ - - - function isStandardBrowserEnv$1() { - if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || navigator.product === 'NativeScript' || navigator.product === 'NS')) { - return false; - } - - return typeof window !== 'undefined' && typeof document !== 'undefined'; - } - /** - * Iterate over an Array or an Object invoking a function for each item. - * - * If `obj` is an Array callback will be called passing - * the value, index, and complete array for each item. - * - * If 'obj' is an Object callback will be called passing - * the value, key, and complete object for each property. - * - * @param {Object|Array} obj The object to iterate - * @param {Function} fn The callback to invoke for each item - */ - - - function forEach$1(obj, fn) { - // Don't bother if no value provided - if (obj === null || typeof obj === 'undefined') { - return; - } // Force an array if not already something iterable - - - if (_typeof(obj) !== 'object') { - /*eslint no-param-reassign:0*/ - obj = [obj]; - } - - if (isArray$1(obj)) { - // Iterate over array values - for (var i = 0, l = obj.length; i < l; i++) { - fn.call(null, obj[i], i, obj); - } - } else { - // Iterate over object keys - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - fn.call(null, obj[key], key, obj); - } - } - } - } - /** - * Accepts varargs expecting each argument to be an object, then - * immutably merges the properties of each object and returns result. - * - * When multiple objects contain the same key the later object in - * the arguments list will take precedence. - * - * Example: - * - * ```js - * var result = merge({foo: 123}, {foo: 456}); - * console.log(result.foo); // outputs 456 - * ``` - * - * @param {Object} obj1 Object to merge - * @returns {Object} Result of all merge properties - */ - - - function merge$1() { - var result = {}; - - function assignValue(val, key) { - if (isPlainObject$1(result[key]) && isPlainObject$1(val)) { - result[key] = merge$1(result[key], val); - } else if (isPlainObject$1(val)) { - result[key] = merge$1({}, val); - } else if (isArray$1(val)) { - result[key] = val.slice(); - } else { - result[key] = val; - } - } - - for (var i = 0, l = arguments.length; i < l; i++) { - forEach$1(arguments[i], assignValue); - } - - return result; - } - /** - * Extends object a by mutably adding to it the properties of object b. - * - * @param {Object} a The object to be extended - * @param {Object} b The object to copy properties from - * @param {Object} thisArg The object to bind function to - * @return {Object} The resulting value of object a - */ - - - function extend$1(a, b, thisArg) { - forEach$1(b, function assignValue(val, key) { - if (thisArg && typeof val === 'function') { - a[key] = bind$8(val, thisArg); - } else { - a[key] = val; - } - }); - return a; - } - /** - * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) - * - * @param {string} content with BOM - * @return {string} content value without BOM - */ - - - function stripBOM$1(content) { - if (content.charCodeAt(0) === 0xFEFF) { - content = content.slice(1); - } - - return content; - } - - var utils$r = { - isArray: isArray$1, - isArrayBuffer: isArrayBuffer$1, - isBuffer: isBuffer$1, - isFormData: isFormData$1, - isArrayBufferView: isArrayBufferView$1, - isString: isString$2, - isNumber: isNumber$1, - isObject: isObject$1, - isPlainObject: isPlainObject$1, - isUndefined: isUndefined$1, - isDate: isDate$1, - isFile: isFile$1, - isBlob: isBlob$1, - isFunction: isFunction$1, - isStream: isStream$1, - isURLSearchParams: isURLSearchParams$1, - isStandardBrowserEnv: isStandardBrowserEnv$1, - forEach: forEach$1, - merge: merge$1, - extend: extend$1, - trim: trim$1, - stripBOM: stripBOM$1 - }; - - var utils$q = utils$r; - - function encode$1(val) { - return encodeURIComponent(val).replace(/%3A/gi, ':').replace(/%24/g, '$').replace(/%2C/gi, ',').replace(/%20/g, '+').replace(/%5B/gi, '[').replace(/%5D/gi, ']'); - } - /** - * Build a URL by appending params to the end - * - * @param {string} url The base of the url (e.g., http://www.google.com) - * @param {object} [params] The params to be appended - * @returns {string} The formatted url - */ - - - var buildURL$5 = function buildURL(url, params, paramsSerializer) { - /*eslint no-param-reassign:0*/ - if (!params) { - return url; - } - - var serializedParams; - - if (paramsSerializer) { - serializedParams = paramsSerializer(params); - } else if (utils$q.isURLSearchParams(params)) { - serializedParams = params.toString(); - } else { - var parts = []; - utils$q.forEach(params, function serialize(val, key) { - if (val === null || typeof val === 'undefined') { - return; - } - - if (utils$q.isArray(val)) { - key = key + '[]'; - } else { - val = [val]; - } - - utils$q.forEach(val, function parseValue(v) { - if (utils$q.isDate(v)) { - v = v.toISOString(); - } else if (utils$q.isObject(v)) { - v = JSON.stringify(v); - } - - parts.push(encode$1(key) + '=' + encode$1(v)); - }); - }); - serializedParams = parts.join('&'); - } - - if (serializedParams) { - var hashmarkIndex = url.indexOf('#'); - - if (hashmarkIndex !== -1) { - url = url.slice(0, hashmarkIndex); - } - - url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; - } - - return url; - }; - - var utils$p = utils$r; - - function InterceptorManager$3() { - this.handlers = []; - } - /** - * Add a new interceptor to the stack - * - * @param {Function} fulfilled The function to handle `then` for a `Promise` - * @param {Function} rejected The function to handle `reject` for a `Promise` - * - * @return {Number} An ID used to remove interceptor later - */ - - - InterceptorManager$3.prototype.use = function use(fulfilled, rejected, options) { - this.handlers.push({ - fulfilled: fulfilled, - rejected: rejected, - synchronous: options ? options.synchronous : false, - runWhen: options ? options.runWhen : null - }); - return this.handlers.length - 1; - }; - /** - * Remove an interceptor from the stack - * - * @param {Number} id The ID that was returned by `use` - */ - - - InterceptorManager$3.prototype.eject = function eject(id) { - if (this.handlers[id]) { - this.handlers[id] = null; - } - }; - /** - * Iterate over all the registered interceptors - * - * This method is particularly useful for skipping over any - * interceptors that may have become `null` calling `eject`. - * - * @param {Function} fn The function to call for each interceptor - */ - - - InterceptorManager$3.prototype.forEach = function forEach(fn) { - utils$p.forEach(this.handlers, function forEachHandler(h) { - if (h !== null) { - fn(h); - } - }); - }; - - var InterceptorManager_1$1 = InterceptorManager$3; - - var utils$o = utils$r; - - var normalizeHeaderName$3 = function normalizeHeaderName(headers, normalizedName) { - utils$o.forEach(headers, function processHeader(value, name) { - if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { - headers[normalizedName] = value; - delete headers[name]; - } - }); - }; - - /** - * Update an Error with the specified config, error code, and response. - * - * @param {Error} error The error to update. - * @param {Object} config The config. - * @param {string} [code] The error code (for example, 'ECONNABORTED'). - * @param {Object} [request] The request. - * @param {Object} [response] The response. - * @returns {Error} The error. - */ - - - var enhanceError$5 = function enhanceError(error, config, code, request, response) { - error.config = config; - - if (code) { - error.code = code; - } - - error.request = request; - error.response = response; - error.isAxiosError = true; - - error.toJSON = function toJSON() { - return { - // Standard - message: this.message, - name: this.name, - // Microsoft - description: this.description, - number: this.number, - // Mozilla - fileName: this.fileName, - lineNumber: this.lineNumber, - columnNumber: this.columnNumber, - stack: this.stack, - // Axios - config: this.config, - code: this.code, - status: this.response && this.response.status ? this.response.status : null - }; - }; - - return error; - }; - - var enhanceError$4 = enhanceError$5; - /** - * Create an Error with the specified message, config, error code, request and response. - * - * @param {string} message The error message. - * @param {Object} config The config. - * @param {string} [code] The error code (for example, 'ECONNABORTED'). - * @param {Object} [request] The request. - * @param {Object} [response] The response. - * @returns {Error} The created error. - */ - - var createError$5 = function createError(message, config, code, request, response) { - var error = new Error(message); - return enhanceError$4(error, config, code, request, response); - }; - - var createError$4 = createError$5; - /** - * Resolve or reject a Promise based on response status. - * - * @param {Function} resolve A function that resolves the promise. - * @param {Function} reject A function that rejects the promise. - * @param {object} response The response. - */ - - var settle$3 = function settle(resolve, reject, response) { - var validateStatus = response.config.validateStatus; - - if (!response.status || !validateStatus || validateStatus(response.status)) { - resolve(response); - } else { - reject(createError$4('Request failed with status code ' + response.status, response.config, null, response.request, response)); - } - }; - - var utils$n = utils$r; - var cookies$3 = utils$n.isStandardBrowserEnv() ? // Standard browser envs support document.cookie - function standardBrowserEnv() { - return { - write: function write(name, value, expires, path, domain, secure) { - var cookie = []; - cookie.push(name + '=' + encodeURIComponent(value)); - - if (utils$n.isNumber(expires)) { - cookie.push('expires=' + new Date(expires).toGMTString()); - } - - if (utils$n.isString(path)) { - cookie.push('path=' + path); - } - - if (utils$n.isString(domain)) { - cookie.push('domain=' + domain); - } - - if (secure === true) { - cookie.push('secure'); - } - - document.cookie = cookie.join('; '); - }, - read: function read(name) { - var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); - return match ? decodeURIComponent(match[3]) : null; - }, - remove: function remove(name) { - this.write(name, '', Date.now() - 86400000); - } - }; - }() : // Non standard browser env (web workers, react-native) lack needed support. - function nonStandardBrowserEnv() { - return { - write: function write() {}, - read: function read() { - return null; - }, - remove: function remove() {} - }; - }(); - - /** - * Determines whether the specified URL is absolute - * - * @param {string} url The URL to test - * @returns {boolean} True if the specified URL is absolute, otherwise false - */ - - - var isAbsoluteURL$3 = function isAbsoluteURL(url) { - // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). - // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed - // by any combination of letters, digits, plus, period, or hyphen. - return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); - }; - - /** - * Creates a new URL by combining the specified URLs - * - * @param {string} baseURL The base URL - * @param {string} relativeURL The relative URL - * @returns {string} The combined URL - */ - - - var combineURLs$3 = function combineURLs(baseURL, relativeURL) { - return relativeURL ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') : baseURL; - }; - - var isAbsoluteURL$2 = isAbsoluteURL$3; - var combineURLs$2 = combineURLs$3; - /** - * Creates a new URL by combining the baseURL with the requestedURL, - * only when the requestedURL is not already an absolute URL. - * If the requestURL is absolute, this function returns the requestedURL untouched. - * - * @param {string} baseURL The base URL - * @param {string} requestedURL Absolute or relative URL to combine - * @returns {string} The combined full path - */ - - var buildFullPath$3 = function buildFullPath(baseURL, requestedURL) { - if (baseURL && !isAbsoluteURL$2(requestedURL)) { - return combineURLs$2(baseURL, requestedURL); - } - - return requestedURL; - }; - - var utils$m = utils$r; // Headers whose duplicates are ignored by node - // c.f. https://nodejs.org/api/http.html#http_message_headers - - var ignoreDuplicateOf$1 = ['age', 'authorization', 'content-length', 'content-type', 'etag', 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', 'last-modified', 'location', 'max-forwards', 'proxy-authorization', 'referer', 'retry-after', 'user-agent']; - /** - * Parse headers into an object - * - * ``` - * Date: Wed, 27 Aug 2014 08:58:49 GMT - * Content-Type: application/json - * Connection: keep-alive - * Transfer-Encoding: chunked - * ``` - * - * @param {String} headers Headers needing to be parsed - * @returns {Object} Headers parsed into an object - */ - - var parseHeaders$3 = function parseHeaders(headers) { - var parsed = {}; - var key; - var val; - var i; - - if (!headers) { - return parsed; - } - - utils$m.forEach(headers.split('\n'), function parser(line) { - i = line.indexOf(':'); - key = utils$m.trim(line.substr(0, i)).toLowerCase(); - val = utils$m.trim(line.substr(i + 1)); - - if (key) { - if (parsed[key] && ignoreDuplicateOf$1.indexOf(key) >= 0) { - return; - } - - if (key === 'set-cookie') { - parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); - } else { - parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; - } - } - }); - return parsed; - }; - - var utils$l = utils$r; - var isURLSameOrigin$3 = utils$l.isStandardBrowserEnv() ? // Standard browser envs have full support of the APIs needed to test - // whether the request URL is of the same origin as current location. - function standardBrowserEnv() { - var msie = /(msie|trident)/i.test(navigator.userAgent); - var urlParsingNode = document.createElement('a'); - var originURL; - /** - * Parse a URL to discover it's components - * - * @param {String} url The URL to be parsed - * @returns {Object} - */ - - function resolveURL(url) { - var href = url; - - if (msie) { - // IE needs attribute set twice to normalize properties - urlParsingNode.setAttribute('href', href); - href = urlParsingNode.href; - } - - urlParsingNode.setAttribute('href', href); // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils - - return { - href: urlParsingNode.href, - protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', - host: urlParsingNode.host, - search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', - hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', - hostname: urlParsingNode.hostname, - port: urlParsingNode.port, - pathname: urlParsingNode.pathname.charAt(0) === '/' ? urlParsingNode.pathname : '/' + urlParsingNode.pathname - }; - } - - originURL = resolveURL(window.location.href); - /** - * Determine if a URL shares the same origin as the current location - * - * @param {String} requestURL The URL to test - * @returns {boolean} True if URL shares the same origin, otherwise false - */ - - return function isURLSameOrigin(requestURL) { - var parsed = utils$l.isString(requestURL) ? resolveURL(requestURL) : requestURL; - return parsed.protocol === originURL.protocol && parsed.host === originURL.host; - }; - }() : // Non standard browser envs (web workers, react-native) lack needed support. - function nonStandardBrowserEnv() { - return function isURLSameOrigin() { - return true; - }; - }(); - - /** - * A `Cancel` is an object that is thrown when an operation is canceled. - * - * @class - * @param {string=} message The message. - */ - - - function Cancel$7(message) { - this.message = message; - } - - Cancel$7.prototype.toString = function toString() { - return 'Cancel' + (this.message ? ': ' + this.message : ''); - }; - - Cancel$7.prototype.__CANCEL__ = true; - var Cancel_1$1 = Cancel$7; - - var utils$k = utils$r; - var settle$2 = settle$3; - var cookies$2 = cookies$3; - var buildURL$4 = buildURL$5; - var buildFullPath$2 = buildFullPath$3; - var parseHeaders$2 = parseHeaders$3; - var isURLSameOrigin$2 = isURLSameOrigin$3; - var createError$3 = createError$5; - var defaults$a = defaults_1$1; - var Cancel$6 = Cancel_1$1; - - var xhr$1 = function xhrAdapter(config) { - return new Promise(function dispatchXhrRequest(resolve, reject) { - var requestData = config.data; - var requestHeaders = config.headers; - var responseType = config.responseType; - var onCanceled; - - function done() { - if (config.cancelToken) { - config.cancelToken.unsubscribe(onCanceled); - } - - if (config.signal) { - config.signal.removeEventListener('abort', onCanceled); - } - } - - if (utils$k.isFormData(requestData)) { - delete requestHeaders['Content-Type']; // Let the browser set it - } - - var request = new XMLHttpRequest(); // HTTP basic authentication - - if (config.auth) { - var username = config.auth.username || ''; - var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; - requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); - } - - var fullPath = buildFullPath$2(config.baseURL, config.url); - request.open(config.method.toUpperCase(), buildURL$4(fullPath, config.params, config.paramsSerializer), true); // Set the request timeout in MS - - request.timeout = config.timeout; - - function onloadend() { - if (!request) { - return; - } // Prepare the response - - - var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders$2(request.getAllResponseHeaders()) : null; - var responseData = !responseType || responseType === 'text' || responseType === 'json' ? request.responseText : request.response; - var response = { - data: responseData, - status: request.status, - statusText: request.statusText, - headers: responseHeaders, - config: config, - request: request - }; - settle$2(function _resolve(value) { - resolve(value); - done(); - }, function _reject(err) { - reject(err); - done(); - }, response); // Clean up request - - request = null; - } - - if ('onloadend' in request) { - // Use onloadend if available - request.onloadend = onloadend; - } else { - // Listen for ready state to emulate onloadend - request.onreadystatechange = function handleLoad() { - if (!request || request.readyState !== 4) { - return; - } // The request errored out and we didn't get a response, this will be - // handled by onerror instead - // With one exception: request that using file: protocol, most browsers - // will return status as 0 even though it's a successful request - - - if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { - return; - } // readystate handler is calling before onerror or ontimeout handlers, - // so we should call onloadend on the next 'tick' - - - setTimeout(onloadend); - }; - } // Handle browser request cancellation (as opposed to a manual cancellation) - - - request.onabort = function handleAbort() { - if (!request) { - return; - } - - reject(createError$3('Request aborted', config, 'ECONNABORTED', request)); // Clean up request - - request = null; - }; // Handle low level network errors - - - request.onerror = function handleError() { - // Real errors are hidden from us by the browser - // onerror should only fire if it's a network error - reject(createError$3('Network Error', config, null, request)); // Clean up request - - request = null; - }; // Handle timeout - - - request.ontimeout = function handleTimeout() { - var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded'; - var transitional = config.transitional || defaults$a.transitional; - - if (config.timeoutErrorMessage) { - timeoutErrorMessage = config.timeoutErrorMessage; - } - - reject(createError$3(timeoutErrorMessage, config, transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED', request)); // Clean up request - - request = null; - }; // Add xsrf header - // This is only done if running in a standard browser environment. - // Specifically not if we're in a web worker, or react-native. - - - if (utils$k.isStandardBrowserEnv()) { - // Add xsrf header - var xsrfValue = (config.withCredentials || isURLSameOrigin$2(fullPath)) && config.xsrfCookieName ? cookies$2.read(config.xsrfCookieName) : undefined; - - if (xsrfValue) { - requestHeaders[config.xsrfHeaderName] = xsrfValue; - } - } // Add headers to the request - - - if ('setRequestHeader' in request) { - utils$k.forEach(requestHeaders, function setRequestHeader(val, key) { - if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { - // Remove Content-Type if data is undefined - delete requestHeaders[key]; - } else { - // Otherwise add header to the request - request.setRequestHeader(key, val); - } - }); - } // Add withCredentials to request if needed - - - if (!utils$k.isUndefined(config.withCredentials)) { - request.withCredentials = !!config.withCredentials; - } // Add responseType to request if needed - - - if (responseType && responseType !== 'json') { - request.responseType = config.responseType; - } // Handle progress if needed - - - if (typeof config.onDownloadProgress === 'function') { - request.addEventListener('progress', config.onDownloadProgress); - } // Not all browsers support upload events - - - if (typeof config.onUploadProgress === 'function' && request.upload) { - request.upload.addEventListener('progress', config.onUploadProgress); - } - - if (config.cancelToken || config.signal) { - // Handle cancellation - // eslint-disable-next-line func-names - onCanceled = function onCanceled(cancel) { - if (!request) { - return; - } - - reject(!cancel || cancel && cancel.type ? new Cancel$6('canceled') : cancel); - request.abort(); - request = null; - }; - - config.cancelToken && config.cancelToken.subscribe(onCanceled); - - if (config.signal) { - config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled); - } - } - - if (!requestData) { - requestData = null; - } // Send the request - - - request.send(requestData); - }); - }; - - var utils$j = utils$r; - var normalizeHeaderName$2 = normalizeHeaderName$3; - var enhanceError$3 = enhanceError$5; - var DEFAULT_CONTENT_TYPE$1 = { - 'Content-Type': 'application/x-www-form-urlencoded' - }; - - function setContentTypeIfUnset$1(headers, value) { - if (!utils$j.isUndefined(headers) && utils$j.isUndefined(headers['Content-Type'])) { - headers['Content-Type'] = value; - } - } - - function getDefaultAdapter$1() { - var adapter; - - if (typeof XMLHttpRequest !== 'undefined') { - // For browsers use XHR adapter - adapter = xhr$1; - } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { - // For node use HTTP adapter - adapter = xhr$1; - } - - return adapter; - } - - function stringifySafely$1(rawValue, parser, encoder) { - if (utils$j.isString(rawValue)) { - try { - (parser || JSON.parse)(rawValue); - return utils$j.trim(rawValue); - } catch (e) { - if (e.name !== 'SyntaxError') { - throw e; - } - } - } - - return (encoder || JSON.stringify)(rawValue); - } - - var defaults$9 = { - transitional: { - silentJSONParsing: true, - forcedJSONParsing: true, - clarifyTimeoutError: false - }, - adapter: getDefaultAdapter$1(), - transformRequest: [function transformRequest(data, headers) { - normalizeHeaderName$2(headers, 'Accept'); - normalizeHeaderName$2(headers, 'Content-Type'); - - if (utils$j.isFormData(data) || utils$j.isArrayBuffer(data) || utils$j.isBuffer(data) || utils$j.isStream(data) || utils$j.isFile(data) || utils$j.isBlob(data)) { - return data; - } - - if (utils$j.isArrayBufferView(data)) { - return data.buffer; - } - - if (utils$j.isURLSearchParams(data)) { - setContentTypeIfUnset$1(headers, 'application/x-www-form-urlencoded;charset=utf-8'); - return data.toString(); - } - - if (utils$j.isObject(data) || headers && headers['Content-Type'] === 'application/json') { - setContentTypeIfUnset$1(headers, 'application/json'); - return stringifySafely$1(data); - } - - return data; - }], - transformResponse: [function transformResponse(data) { - var transitional = this.transitional || defaults$9.transitional; - var silentJSONParsing = transitional && transitional.silentJSONParsing; - var forcedJSONParsing = transitional && transitional.forcedJSONParsing; - var strictJSONParsing = !silentJSONParsing && this.responseType === 'json'; - - if (strictJSONParsing || forcedJSONParsing && utils$j.isString(data) && data.length) { - try { - return JSON.parse(data); - } catch (e) { - if (strictJSONParsing) { - if (e.name === 'SyntaxError') { - throw enhanceError$3(e, this, 'E_JSON_PARSE'); - } - - throw e; - } - } - } - - return data; - }], - - /** - * A timeout in milliseconds to abort a request. If set to 0 (default) a - * timeout is not created. - */ - timeout: 0, - xsrfCookieName: 'XSRF-TOKEN', - xsrfHeaderName: 'X-XSRF-TOKEN', - maxContentLength: -1, - maxBodyLength: -1, - validateStatus: function validateStatus(status) { - return status >= 200 && status < 300; - }, - headers: { - common: { - 'Accept': 'application/json, text/plain, */*' - } - } - }; - utils$j.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { - defaults$9.headers[method] = {}; - }); - utils$j.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { - defaults$9.headers[method] = utils$j.merge(DEFAULT_CONTENT_TYPE$1); - }); - var defaults_1$1 = defaults$9; - - var utils$i = utils$r; - var defaults$8 = defaults_1$1; - /** - * Transform the data for a request or a response - * - * @param {Object|String} data The data to be transformed - * @param {Array} headers The headers for the request or response - * @param {Array|Function} fns A single function or Array of functions - * @returns {*} The resulting transformed data - */ - - var transformData$3 = function transformData(data, headers, fns) { - var context = this || defaults$8; - /*eslint no-param-reassign:0*/ - - utils$i.forEach(fns, function transform(fn) { - data = fn.call(context, data, headers); - }); - return data; - }; - - var isCancel$3 = function isCancel(value) { - return !!(value && value.__CANCEL__); - }; - - var utils$h = utils$r; - var transformData$2 = transformData$3; - var isCancel$2 = isCancel$3; - var defaults$7 = defaults_1$1; - var Cancel$5 = Cancel_1$1; - /** - * Throws a `Cancel` if cancellation has been requested. - */ - - function throwIfCancellationRequested$1(config) { - if (config.cancelToken) { - config.cancelToken.throwIfRequested(); - } - - if (config.signal && config.signal.aborted) { - throw new Cancel$5('canceled'); - } - } - /** - * Dispatch a request to the server using the configured adapter. - * - * @param {object} config The config that is to be used for the request - * @returns {Promise} The Promise to be fulfilled - */ - - - var dispatchRequest$3 = function dispatchRequest(config) { - throwIfCancellationRequested$1(config); // Ensure headers exist - - config.headers = config.headers || {}; // Transform request data - - config.data = transformData$2.call(config, config.data, config.headers, config.transformRequest); // Flatten headers - - config.headers = utils$h.merge(config.headers.common || {}, config.headers[config.method] || {}, config.headers); - utils$h.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], function cleanHeaderConfig(method) { - delete config.headers[method]; - }); - var adapter = config.adapter || defaults$7.adapter; - return adapter(config).then(function onAdapterResolution(response) { - throwIfCancellationRequested$1(config); // Transform response data - - response.data = transformData$2.call(config, response.data, response.headers, config.transformResponse); - return response; - }, function onAdapterRejection(reason) { - if (!isCancel$2(reason)) { - throwIfCancellationRequested$1(config); // Transform response data - - if (reason && reason.response) { - reason.response.data = transformData$2.call(config, reason.response.data, reason.response.headers, config.transformResponse); - } - } - - return Promise.reject(reason); - }); - }; - - var utils$g = utils$r; - /** - * Config-specific merge-function which creates a new config-object - * by merging two configuration objects together. - * - * @param {Object} config1 - * @param {Object} config2 - * @returns {Object} New object resulting from merging config2 to config1 - */ - - var mergeConfig$5 = function mergeConfig(config1, config2) { - // eslint-disable-next-line no-param-reassign - config2 = config2 || {}; - var config = {}; - - function getMergedValue(target, source) { - if (utils$g.isPlainObject(target) && utils$g.isPlainObject(source)) { - return utils$g.merge(target, source); - } else if (utils$g.isPlainObject(source)) { - return utils$g.merge({}, source); - } else if (utils$g.isArray(source)) { - return source.slice(); - } - - return source; - } // eslint-disable-next-line consistent-return - - - function mergeDeepProperties(prop) { - if (!utils$g.isUndefined(config2[prop])) { - return getMergedValue(config1[prop], config2[prop]); - } else if (!utils$g.isUndefined(config1[prop])) { - return getMergedValue(undefined, config1[prop]); - } - } // eslint-disable-next-line consistent-return - - - function valueFromConfig2(prop) { - if (!utils$g.isUndefined(config2[prop])) { - return getMergedValue(undefined, config2[prop]); - } - } // eslint-disable-next-line consistent-return - - - function defaultToConfig2(prop) { - if (!utils$g.isUndefined(config2[prop])) { - return getMergedValue(undefined, config2[prop]); - } else if (!utils$g.isUndefined(config1[prop])) { - return getMergedValue(undefined, config1[prop]); - } - } // eslint-disable-next-line consistent-return - - - function mergeDirectKeys(prop) { - if (prop in config2) { - return getMergedValue(config1[prop], config2[prop]); - } else if (prop in config1) { - return getMergedValue(undefined, config1[prop]); - } - } - - var mergeMap = { - 'url': valueFromConfig2, - 'method': valueFromConfig2, - 'data': valueFromConfig2, - 'baseURL': defaultToConfig2, - 'transformRequest': defaultToConfig2, - 'transformResponse': defaultToConfig2, - 'paramsSerializer': defaultToConfig2, - 'timeout': defaultToConfig2, - 'timeoutMessage': defaultToConfig2, - 'withCredentials': defaultToConfig2, - 'adapter': defaultToConfig2, - 'responseType': defaultToConfig2, - 'xsrfCookieName': defaultToConfig2, - 'xsrfHeaderName': defaultToConfig2, - 'onUploadProgress': defaultToConfig2, - 'onDownloadProgress': defaultToConfig2, - 'decompress': defaultToConfig2, - 'maxContentLength': defaultToConfig2, - 'maxBodyLength': defaultToConfig2, - 'transport': defaultToConfig2, - 'httpAgent': defaultToConfig2, - 'httpsAgent': defaultToConfig2, - 'cancelToken': defaultToConfig2, - 'socketPath': defaultToConfig2, - 'responseEncoding': defaultToConfig2, - 'validateStatus': mergeDirectKeys - }; - utils$g.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) { - var merge = mergeMap[prop] || mergeDeepProperties; - var configValue = merge(prop); - utils$g.isUndefined(configValue) && merge !== mergeDirectKeys || (config[prop] = configValue); - }); - return config; - }; - - var data$1 = { - "version": "0.24.0" - }; - - var VERSION$1 = data$1.version; - var validators$3 = {}; // eslint-disable-next-line func-names - - ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function (type, i) { - validators$3[type] = function validator(thing) { - return _typeof(thing) === type || 'a' + (i < 1 ? 'n ' : ' ') + type; - }; - }); - var deprecatedWarnings$1 = {}; - /** - * Transitional option validator - * @param {function|boolean?} validator - set to false if the transitional option has been removed - * @param {string?} version - deprecated version / removed since version - * @param {string?} message - some message with additional info - * @returns {function} - */ - - validators$3.transitional = function transitional(validator, version, message) { - function formatMessage(opt, desc) { - return '[Axios v' + VERSION$1 + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); - } // eslint-disable-next-line func-names - - - return function (value, opt, opts) { - if (validator === false) { - throw new Error(formatMessage(opt, ' has been removed' + (version ? ' in ' + version : ''))); - } - - if (version && !deprecatedWarnings$1[opt]) { - deprecatedWarnings$1[opt] = true; // eslint-disable-next-line no-console - - console.warn(formatMessage(opt, ' has been deprecated since v' + version + ' and will be removed in the near future')); - } - - return validator ? validator(value, opt, opts) : true; - }; - }; - /** - * Assert object's properties type - * @param {object} options - * @param {object} schema - * @param {boolean?} allowUnknown - */ - - - function assertOptions$1(options, schema, allowUnknown) { - if (_typeof(options) !== 'object') { - throw new TypeError('options must be an object'); - } - - var keys = Object.keys(options); - var i = keys.length; - - while (i-- > 0) { - var opt = keys[i]; - var validator = schema[opt]; - - if (validator) { - var value = options[opt]; - var result = value === undefined || validator(value, opt, options); - - if (result !== true) { - throw new TypeError('option ' + opt + ' must be ' + result); - } - - continue; - } - - if (allowUnknown !== true) { - throw Error('Unknown option ' + opt); - } - } - } - - var validator$3 = { - assertOptions: assertOptions$1, - validators: validators$3 - }; - - var utils$f = utils$r; - var buildURL$3 = buildURL$5; - var InterceptorManager$2 = InterceptorManager_1$1; - var dispatchRequest$2 = dispatchRequest$3; - var mergeConfig$4 = mergeConfig$5; - var validator$2 = validator$3; - var validators$2 = validator$2.validators; - /** - * Create a new instance of Axios - * - * @param {Object} instanceConfig The default config for the instance - */ - - function Axios$3(instanceConfig) { - this.defaults = instanceConfig; - this.interceptors = { - request: new InterceptorManager$2(), - response: new InterceptorManager$2() - }; - } - /** - * Dispatch a request - * - * @param {Object} config The config specific for this request (merged with this.defaults) - */ - - - Axios$3.prototype.request = function request(config) { - /*eslint no-param-reassign:0*/ - // Allow for axios('example/url'[, config]) a la fetch API - if (typeof config === 'string') { - config = arguments[1] || {}; - config.url = arguments[0]; - } else { - config = config || {}; - } - - config = mergeConfig$4(this.defaults, config); // Set config.method - - if (config.method) { - config.method = config.method.toLowerCase(); - } else if (this.defaults.method) { - config.method = this.defaults.method.toLowerCase(); - } else { - config.method = 'get'; - } - - var transitional = config.transitional; - - if (transitional !== undefined) { - validator$2.assertOptions(transitional, { - silentJSONParsing: validators$2.transitional(validators$2.boolean), - forcedJSONParsing: validators$2.transitional(validators$2.boolean), - clarifyTimeoutError: validators$2.transitional(validators$2.boolean) - }, false); - } // filter out skipped interceptors - - - var requestInterceptorChain = []; - var synchronousRequestInterceptors = true; - this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { - if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { - return; - } - - synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; - requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); - }); - var responseInterceptorChain = []; - this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { - responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); - }); - var promise; - - if (!synchronousRequestInterceptors) { - var chain = [dispatchRequest$2, undefined]; - Array.prototype.unshift.apply(chain, requestInterceptorChain); - chain = chain.concat(responseInterceptorChain); - promise = Promise.resolve(config); - - while (chain.length) { - promise = promise.then(chain.shift(), chain.shift()); - } - - return promise; - } - - var newConfig = config; - - while (requestInterceptorChain.length) { - var onFulfilled = requestInterceptorChain.shift(); - var onRejected = requestInterceptorChain.shift(); - - try { - newConfig = onFulfilled(newConfig); - } catch (error) { - onRejected(error); - break; - } - } - - try { - promise = dispatchRequest$2(newConfig); - } catch (error) { - return Promise.reject(error); - } - - while (responseInterceptorChain.length) { - promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift()); - } - - return promise; - }; - - Axios$3.prototype.getUri = function getUri(config) { - config = mergeConfig$4(this.defaults, config); - return buildURL$3(config.url, config.params, config.paramsSerializer).replace(/^\?/, ''); - }; // Provide aliases for supported request methods - - - utils$f.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { - /*eslint func-names:0*/ - Axios$3.prototype[method] = function (url, config) { - return this.request(mergeConfig$4(config || {}, { - method: method, - url: url, - data: (config || {}).data - })); - }; - }); - utils$f.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { - /*eslint func-names:0*/ - Axios$3.prototype[method] = function (url, data, config) { - return this.request(mergeConfig$4(config || {}, { - method: method, - url: url, - data: data - })); - }; - }); - var Axios_1$1 = Axios$3; - - var Cancel$4 = Cancel_1$1; - /** - * A `CancelToken` is an object that can be used to request cancellation of an operation. - * - * @class - * @param {Function} executor The executor function. - */ - - function CancelToken$1(executor) { - if (typeof executor !== 'function') { - throw new TypeError('executor must be a function.'); - } - - var resolvePromise; - this.promise = new Promise(function promiseExecutor(resolve) { - resolvePromise = resolve; - }); - var token = this; // eslint-disable-next-line func-names - - this.promise.then(function (cancel) { - if (!token._listeners) return; - var i; - var l = token._listeners.length; - - for (i = 0; i < l; i++) { - token._listeners[i](cancel); - } - - token._listeners = null; - }); // eslint-disable-next-line func-names - - this.promise.then = function (onfulfilled) { - var _resolve; // eslint-disable-next-line func-names - - - var promise = new Promise(function (resolve) { - token.subscribe(resolve); - _resolve = resolve; - }).then(onfulfilled); - - promise.cancel = function reject() { - token.unsubscribe(_resolve); - }; - - return promise; - }; - - executor(function cancel(message) { - if (token.reason) { - // Cancellation has already been requested - return; - } - - token.reason = new Cancel$4(message); - resolvePromise(token.reason); - }); - } - /** - * Throws a `Cancel` if cancellation has been requested. - */ - - - CancelToken$1.prototype.throwIfRequested = function throwIfRequested() { - if (this.reason) { - throw this.reason; - } - }; - /** - * Subscribe to the cancel signal - */ - - - CancelToken$1.prototype.subscribe = function subscribe(listener) { - if (this.reason) { - listener(this.reason); - return; - } - - if (this._listeners) { - this._listeners.push(listener); - } else { - this._listeners = [listener]; - } - }; - /** - * Unsubscribe from the cancel signal - */ - - - CancelToken$1.prototype.unsubscribe = function unsubscribe(listener) { - if (!this._listeners) { - return; - } - - var index = this._listeners.indexOf(listener); - - if (index !== -1) { - this._listeners.splice(index, 1); - } - }; - /** - * Returns an object that contains a new `CancelToken` and a function that, when called, - * cancels the `CancelToken`. - */ - - - CancelToken$1.source = function source() { - var cancel; - var token = new CancelToken$1(function executor(c) { - cancel = c; - }); - return { - token: token, - cancel: cancel - }; - }; - - var CancelToken_1$1 = CancelToken$1; - - /** - * Syntactic sugar for invoking a function and expanding an array for arguments. - * - * Common use case would be to use `Function.prototype.apply`. - * - * ```js - * function f(x, y, z) {} - * var args = [1, 2, 3]; - * f.apply(null, args); - * ``` - * - * With `spread` this example can be re-written. - * - * ```js - * spread(function(x, y, z) {})([1, 2, 3]); - * ``` - * - * @param {Function} callback - * @returns {Function} - */ - - - var spread$1 = function spread(callback) { - return function wrap(arr) { - return callback.apply(null, arr); - }; - }; - - /** - * Determines whether the payload is an error thrown by Axios - * - * @param {*} payload The value to test - * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false - */ - - - var isAxiosError$1 = function isAxiosError(payload) { - return _typeof(payload) === 'object' && payload.isAxiosError === true; - }; - - var utils$e = utils$r; - var bind$7 = bind$9; - var Axios$2 = Axios_1$1; - var mergeConfig$3 = mergeConfig$5; - var defaults$6 = defaults_1$1; - /** - * Create an instance of Axios - * - * @param {Object} defaultConfig The default config for the instance - * @return {Axios} A new instance of Axios - */ - - function createInstance$1(defaultConfig) { - var context = new Axios$2(defaultConfig); - var instance = bind$7(Axios$2.prototype.request, context); // Copy axios.prototype to instance - - utils$e.extend(instance, Axios$2.prototype, context); // Copy context to instance - - utils$e.extend(instance, context); // Factory for creating new instances - - instance.create = function create(instanceConfig) { - return createInstance$1(mergeConfig$3(defaultConfig, instanceConfig)); - }; - - return instance; - } // Create the default instance to be exported - - - var axios$3 = createInstance$1(defaults$6); // Expose Axios class to allow class inheritance - - axios$3.Axios = Axios$2; // Expose Cancel & CancelToken - - axios$3.Cancel = Cancel_1$1; - axios$3.CancelToken = CancelToken_1$1; - axios$3.isCancel = isCancel$3; - axios$3.VERSION = data$1.version; // Expose all/spread - - axios$3.all = function all(promises) { - return Promise.all(promises); - }; - - axios$3.spread = spread$1; // Expose isAxiosError - - axios$3.isAxiosError = isAxiosError$1; - axios$4.exports = axios$3; // Allow use of default import syntax in TypeScript - - axios$4.exports.default = axios$3; - - var axios$2 = axios$4.exports; - - var IdealPostcodesError = IdealPostcodesError$1; - /** - * Converts a Got header object to one that can be used by the client - * - * @hidden - */ - - var toHeader = function toHeader(gotHeaders) { - return Object.keys(gotHeaders).reduce(function (headers, key) { - var val = gotHeaders[key]; - - if (typeof val === "string") { - headers[key] = val; - } else if (Array.isArray(val)) { - headers[key] = val.join(","); - } - - return headers; - }, {}); - }; - /** - * Adapts got responses to a format consumable by core-interface - * - * @hidden - */ - - var toHttpResponse = function toHttpResponse(httpRequest, response) { - return { - httpRequest: httpRequest, - body: response.data, - httpStatus: response.status || 0, - header: toHeader(response.headers), - metadata: { - response: response - } - }; - }; - /** - * Catch non-response errors (e.g. network failure, DNS failure, timeout) - * wrap in our Error class and return - * - * @hidden - */ - - - var handleError = function handleError(error) { - var idpcError = new IdealPostcodesError({ - message: "[".concat(error.name, "] ").concat(error.message), - httpStatus: 0, - metadata: { - axios: error - } - }); - return Promise.reject(idpcError); - }; // Don't throw errors for any HTTP status code - // Allow core-interface to absorb these and emit own errors - - - var validateStatus = function validateStatus() { - return true; - }; - /** - * Agent - * - * @hidden - */ - - - var Agent = /*#__PURE__*/function () { - function Agent() { - _classCallCheck(this, Agent); - - this.Axios = axios$2.create({ - validateStatus: validateStatus - }); - } - - _createClass(Agent, [{ - key: "requestWithBody", - value: function requestWithBody(httpRequest) { - var body = httpRequest.body, - method = httpRequest.method, - timeout = httpRequest.timeout, - url = httpRequest.url, - header = httpRequest.header, - query = httpRequest.query; - return this.Axios.request({ - url: url, - method: method, - headers: header, - params: query, - data: body, - timeout: timeout - }).then(function (response) { - return toHttpResponse(httpRequest, response); - }).catch(handleError); - } - }, { - key: "request", - value: function request(httpRequest) { - var method = httpRequest.method, - timeout = httpRequest.timeout, - url = httpRequest.url, - header = httpRequest.header, - query = httpRequest.query; - return this.Axios.request({ - url: url, - method: method, - headers: header, - params: query, - timeout: timeout - }).then(function (response) { - return toHttpResponse(httpRequest, response); - }).catch(handleError); - } - }, { - key: "http", - value: function http(httpRequest) { - if (httpRequest.body !== undefined) return this.requestWithBody(httpRequest); - return this.request(httpRequest); - } - }]); - - return Agent; - }(); - - function ownKeys$6(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - - function _objectSpread$6(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$6(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$6(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - - function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } - - function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } - var Client = /*#__PURE__*/function (_CoreInterface) { - _inherits(Client, _CoreInterface); - - var _super = _createSuper(Client); - - /** - * Client constructor extends CoreInterface - */ - function Client(config) { - _classCallCheck(this, Client); - - var agent = new Agent(); - return _super.call(this, _objectSpread$6({ - agent: agent - }, config)); - } - - return Client; - }(Client$1); - - function ownKeys$5(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - - function _objectSpread$5(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$5(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$5(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - /** - * @hidden - */ - - var ApiCache = /*#__PURE__*/function () { - function ApiCache(client) { - _classCallCheck(this, ApiCache); - - this.prefix = "!"; - this.client = client; - this.cache = {}; - } - - _createClass(ApiCache, [{ - key: "key", - value: function key(query) { - return "".concat(this.prefix).concat(query.toLowerCase()); - } - }, { - key: "retrieve", - value: function retrieve(query) { - return this.cache[this.key(query)]; - } - }, { - key: "store", - value: function store(query, data) { - this.cache[this.key(query)] = data; - return data; - } - }, { - key: "clear", - value: function clear() { - this.cache = {}; - } - /** - * Retrieve a list of address suggestions given a query - * - * Write and read from cache if previously requested - */ - - }, { - key: "query", - value: function query(_query) { - var _this = this; - - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var cachedValue = this.retrieve(_query); - if (cachedValue) return Promise.resolve(cachedValue); - var p = list(this.client, { - query: _objectSpread$5({ - query: _query, - api_key: this.client.config.api_key - }, options) - }).then(function (response) { - var suggestions = response.body.result.hits; - - _this.store(_query, suggestions); - - return suggestions; - }); - this.store(_query, p); - return p; - } - }, { - key: "resolve", - value: function resolve(suggestion) { - return gbr(this.client, suggestion.id, { - query: { - api_key: this.client.config.api_key - } - }).then(function (response) { - return response.body.result; - }); - } - }]); - - return ApiCache; - }(); - - var isString$1 = function isString(input) { - return typeof input === "string"; - }; - - var hasWindow = function hasWindow() { - return typeof window !== "undefined"; - }; - var toArray = function toArray(nodeList) { - return Array.prototype.slice.call(nodeList); - }; - var loaded = function loaded(elem) { - var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "idpc"; - return elem.getAttribute(prefix) === "true"; - }; - var markLoaded = function markLoaded(elem) { - var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "idpc"; - return elem.setAttribute(prefix, "true"); - }; - - var isTrue$1 = function isTrue() { - return true; - }; - - var getParent = function getParent(node, entity) { - var test = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : isTrue$1; - var parent = node; - var tagName = entity.toUpperCase(); - - while (parent.tagName !== "HTML") { - if (parent.tagName === tagName && test(parent)) return parent; - if (parent.parentNode === null) return null; - parent = parent.parentNode; - } - - return null; - }; - var toHtmlElem = function toHtmlElem(parent, selector) { - return selector ? parent.querySelector(selector) : null; - }; - var toElem = function toElem(elem, context) { - if (isString$1(elem)) return context.querySelector(elem); - return elem; - }; - - var d$1 = function d() { - return window.document; - }; - - var getScope = function getScope(scope) { - if (isString$1(scope)) return d$1().querySelector(scope); - if (scope === null) return d$1(); - return scope; - }; - var getDocument = function getDocument(scope) { - if (scope instanceof Document) return scope; - if (scope.ownerDocument) return scope.ownerDocument; - return d$1(); - }; - var setStyle = function setStyle(element, style) { - var currentRules = element.getAttribute("style"); - Object.keys(style).forEach(function (key) { - return element.style[key] = style[key]; - }); - return currentRules; - }; - var restoreStyle = function restoreStyle(element, style) { - element.setAttribute("style", style || ""); - }; - var hide = function hide(e) { - e.style.display = "none"; - return e; - }; - var show = function show(e) { - e.style.display = ""; - return e; - }; - var remove = function remove(elem) { - if (elem === null || elem.parentNode === null) return; - elem.parentNode.removeChild(elem); - }; - var contains = function contains(scope, selector, text) { - var elements = scope.querySelectorAll(selector); - - for (var i = 0; i < elements.length; i++) { - var e = elements[i]; - var content = e.innerText; - if (content && content.trim() === text) return e; - } - - return null; - }; - - var generateTimer = function generateTimer(_ref) { - var pageTest = _ref.pageTest, - bind = _ref.bind, - _ref$interval = _ref.interval, - interval = _ref$interval === void 0 ? 1000 : _ref$interval; - var timer = null; - - var start = function start(config) { - if (!pageTest()) return null; - timer = window.setInterval(function () { - try { - bind(config); - } catch (e) { - stop(); - console.log(e); - } - }, interval); - return timer; - }; - - var stop = function stop() { - if (timer === null) return; - window.clearInterval(timer); - timer = null; - }; - - return { - start: start, - stop: stop - }; - }; - var cssEscape = function cssEscape(value) { - value = String(value); - var length = value.length; - var index = -1; - var codeUnit; - var result = ""; - var firstCodeUnit = value.charCodeAt(0); - - while (++index < length) { - codeUnit = value.charCodeAt(index); - - if (codeUnit == 0x0000) { - result += "\uFFFD"; - continue; - } - - if (codeUnit >= 0x0001 && codeUnit <= 0x001f || codeUnit == 0x007f || index == 0 && codeUnit >= 0x0030 && codeUnit <= 0x0039 || index == 1 && codeUnit >= 0x0030 && codeUnit <= 0x0039 && firstCodeUnit == 0x002d) { - result += "\\" + codeUnit.toString(16) + " "; - continue; - } - - if (index == 0 && length == 1 && codeUnit == 0x002d) { - result += "\\" + value.charAt(index); - continue; - } - - if (codeUnit >= 0x0080 || codeUnit == 0x002d || codeUnit == 0x005f || codeUnit >= 0x0030 && codeUnit <= 0x0039 || codeUnit >= 0x0041 && codeUnit <= 0x005a || codeUnit >= 0x0061 && codeUnit <= 0x007a) { - result += value.charAt(index); - continue; - } - - result += "\\" + value.charAt(index); - } - - return result; - }; - - var loadStyle = function loadStyle(href, document) { - var link = document.createElement("link"); - link.type = "text/css"; - link.rel = "stylesheet"; - link.href = href; - return link; - }; - var injectStyle = function injectStyle(css, document) { - var style = document.createElement("style"); - style.type = "text/css"; - style.appendChild(document.createTextNode(css)); - document.head.appendChild(style); - return style; - }; - - var newEvent = function newEvent(_ref) { - var event = _ref.event, - _ref$bubbles = _ref.bubbles, - bubbles = _ref$bubbles === void 0 ? true : _ref$bubbles, - _ref$cancelable = _ref.cancelable, - cancelable = _ref$cancelable === void 0 ? true : _ref$cancelable; - if (typeof window.Event === "function") return new window.Event(event, { - bubbles: bubbles, - cancelable: cancelable - }); - var e = document.createEvent("Event"); - e.initEvent(event, bubbles, cancelable); - return e; - }; - var trigger = function trigger(e, event) { - return e.dispatchEvent(newEvent({ - event: event - })); - }; - - var isSelect = function isSelect(e) { - if (e === null) return false; - return e instanceof HTMLSelectElement; - }; - var isInput = function isInput(e) { - if (e === null) return false; - return e instanceof HTMLInputElement; - }; - var isTextarea = function isTextarea(e) { - if (e === null) return false; - return e instanceof HTMLTextAreaElement; - }; - var update = function update(input, value) { - var skipTrigger = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - if (!input) return; - if (!isInput(input) && !isTextarea(input)) return; - change({ - e: input, - value: value, - skipTrigger: skipTrigger - }); - }; - var hasValue = function hasValue(select, value) { - if (value === null) return false; - return select.querySelector("[value=\"".concat(value, "\"]")) !== null; - }; - - var updateSelect = function updateSelect(_ref) { - var e = _ref.e, - value = _ref.value, - skipTrigger = _ref.skipTrigger; - if (value === null) return; - if (!isSelect(e)) return; - setValue(e, value); - if (!skipTrigger) trigger(e, "select"); - trigger(e, "change"); - }; - - var setValue = function setValue(e, value) { - var descriptor = Object.getOwnPropertyDescriptor(e.constructor.prototype, "value"); - if (descriptor === undefined) return; - if (descriptor.set === undefined) return; - var setter = descriptor.set; - setter.call(e, value); - }; - - var updateInput = function updateInput(_ref2) { - var e = _ref2.e, - value = _ref2.value, - skipTrigger = _ref2.skipTrigger; - if (value === null) return; - if (!isInput(e) && !isTextarea(e)) return; - setValue(e, value); - if (!skipTrigger) trigger(e, "input"); - trigger(e, "change"); - }; - - var change = function change(options) { - if (options.value === null) return; - updateSelect(options); - updateInput(options); - }; - - var toCiIso = function toCiIso(address) { - if (/^GY/.test(address.postcode)) return "GG"; - if (/^JE/.test(address.postcode)) return "JE"; - return null; - }; - var UK = "United Kingdom"; - var IOM = "Isle of Man"; - var EN = "England"; - var SC = "Scotland"; - var WA = "Wales"; - var NI = "Northern Ireland"; - var CI = "Channel Islands"; - var toIso = function toIso(address) { - var country = address.country; - if (country === EN) return "GB"; - if (country === SC) return "GB"; - if (country === WA) return "GB"; - if (country === NI) return "GB"; - if (country === IOM) return "IM"; - if (country === CI) return toCiIso(address); - return null; - }; - var toCountry = function toCountry(address) { - var country = address.country; - if (country === EN) return UK; - if (country === SC) return UK; - if (country === WA) return UK; - if (country === NI) return UK; - if (country === IOM) return IOM; - - if (country === CI) { - var iso = toCiIso(address); - if (iso === "GG") return "Guernsey"; - if (iso === "JE") return "Jersey"; - } - - return null; - }; - var updateCountry = function updateCountry(select, address) { - if (!select) return; - - if (isSelect(select)) { - var iso = toIso(address); - if (hasValue(select, iso)) change({ - e: select, - value: iso - }); - var bcc = toCountry(address); - if (hasValue(select, bcc)) change({ - e: select, - value: bcc - }); - } - - if (isInput(select)) { - var _bcc = toCountry(address); - - change({ - e: select, - value: _bcc - }); - } - }; - - var g = {}; - - if (hasWindow()) { - if (window.idpcGlobal) { - g = window.idpcGlobal; - } else { - window.idpcGlobal = g; - } - } - - var idpcState = function idpcState() { - return g; - }; - - var idGen = function idGen() { - var prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "idpc_"; - return function () { - var g = idpcState(); - if (!g.idGen) g.idGen = {}; - if (g.idGen[prefix] === undefined) g.idGen[prefix] = 0; - g.idGen[prefix] += 1; - return "".concat(prefix).concat(g.idGen[prefix]); - }; - }; - - function ownKeys$4(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - - function _objectSpread$4(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$4(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$4(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - var numberOfLines = function numberOfLines(targets) { - var line_2 = targets.line_2, - line_3 = targets.line_3; - if (!line_2) return 1; - if (!line_3) return 2; - return 3; - }; - var join = function join(list) { - return list.filter(function (e) { - if (isString$1(e)) return !!e.trim(); - return !!e; - }).join(", "); - }; - var toAddressLines = function toAddressLines(n, address) { - var line_1 = address.line_1, - line_2 = address.line_2, - line_3 = address.line_3; - if (n === 3) return [line_1, line_2, line_3]; - if (n === 2) return [line_1, join([line_2, line_3]), ""]; - return [join([line_1, line_2, line_3]), "", ""]; - }; - var extract = function extract(a, attr) { - var result = a[attr]; - if (typeof result === "number") return result.toString(); - if (result === undefined) return ""; - return result; - }; - var notInAddress = function notInAddress(o, attr) { - return o[attr] === undefined; - }; - var getFields$1 = function getFields(o) { - return _objectSpread$4(_objectSpread$4(_objectSpread$4({}, o.outputFields), searchNames(o.names || {}, o.config.scope)), searchLabels(o.labels || {}, o.config.scope)); - }; - - var updateLines = function updateLines(fields, address, scope) { - var _toAddressLines3 = toAddressLines(numberOfLines(fields), address), - _toAddressLines4 = _slicedToArray(_toAddressLines3, 3), - line_1 = _toAddressLines4[0], - line_2 = _toAddressLines4[1], - line_3 = _toAddressLines4[2]; - - update(toElem(fields.line_1 || null, scope), line_1); - update(toElem(fields.line_2 || null, scope), line_2); - update(toElem(fields.line_3 || null, scope), line_3); - }; - - var searchNames = function searchNames(names, scope) { - var result = {}; - var key; - - for (key in names) { - if (!names.hasOwnProperty(key)) continue; - var name = names[key]; - var named = toElem("[name=\"".concat(name, "\"]"), scope); - - if (named) { - result[key] = named; - continue; - } - - var ariaNamed = toElem("[aria-name=\"".concat(name, "\"]"), scope); - if (ariaNamed) result[key] = ariaNamed; - } - - return result; - }; - var searchLabels = function searchLabels(labels, scope) { - var result = {}; - if (labels === undefined) return labels; - var key; - - for (key in labels) { - if (!labels.hasOwnProperty(key)) continue; - var name = labels[key]; - if (!name) continue; - var first = contains(scope, "label", name); - var label = toElem(first, scope); - if (!label) continue; - var forEl = label.getAttribute("for"); - - if (forEl) { - var byId = scope.querySelector("#".concat(cssEscape(forEl))); - - if (byId) { - result[key] = byId; - continue; - } - } - - var inner = label.querySelector("input"); - if (inner) result[key] = inner; - } - - return result; - }; - var populateAddress = function populateAddress(options) { - var config = options.config; - - var address = _objectSpread$4({}, options.address); - - var scope = config.scope, - titleizePostTown = config.titleizePostTown, - populateOrganisation = config.populateOrganisation, - populateCounty = config.populateCounty; - var fields = getFields$1(options); - if (config.removeOrganisation) removeOrganisation(address); - if (titleizePostTown) address.post_town = capitalisePostTown_1(address.post_town); - updateLines(fields, address, scope); - delete address.line_1; - delete address.line_2; - delete address.line_3; - updateCountry(toElem(fields.country || null, scope), address); - delete address.country; - if (populateOrganisation === false) delete address.organisation_name; - if (populateCounty === false) delete address.county; - var e; - - for (e in fields) { - if (notInAddress(address, e)) continue; - - if (fields.hasOwnProperty(e)) { - var value = fields[e]; - if (!value) continue; - update(toElem(value, scope), extract(address, e)); - } - } - }; - var removeOrganisation = function removeOrganisation(address) { - if (address.organisation_name.length === 0) return address; - if (address.line_2.length === 0 && address.line_3.length === 0) return address; - - if (address.line_1 === address.organisation_name) { - address.line_1 = address.line_2; - address.line_2 = address.line_3; - address.line_3 = ""; - } - - return address; - }; - - var keyCodeMapping = { - 13: "Enter", - 38: "ArrowUp", - 40: "ArrowDown", - 36: "Home", - 35: "End", - 27: "Escape", - 8: "Backspace" - }; - var supportedKeys = ["Enter", "ArrowUp", "ArrowDown", "Home", "End", "Escape", "Backspace"]; - - var supported = function supported(k) { - return supportedKeys.indexOf(k) !== -1; - }; - - var toKey = function toKey(event) { - if (event.keyCode) return keyCodeMapping[event.keyCode] || null; - return supported(event.key) ? event.key : null; - }; - - /** - * Default CSS - * - * @hidden - */ - - var d = ".idpc_af.hidden{display:none}div.idpc_autocomplete{position:relative;margin:0!important;padding:0;border:0;color:#28282b;text-rendering:optimizeLegibility;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}div.idpc_autocomplete>input{display:block}div.idpc_af{position:absolute;left:0;z-index:2000;min-width:100%;box-sizing:border-box;border-radius:3px;background:#fff;border:1px solid rgba(0,0,0,.3);box-shadow:.05em .2em .6em rgba(0,0,0,.2);text-shadow:none;padding:0;margin-top:2px}div.idpc_af>ul{list-style:none;padding:0;max-height:250px;overflow-y:scroll;margin:0!important}div.idpc_af>ul>li{position:relative;padding:.2em .5em;cursor:pointer;margin:0!important}div.idpc_toolbar{padding:.3em .5em;border-top:1px solid rgba(0,0,0,.3);text-align:right}div.idpc_af>ul>li:hover{background-color:#e5e4e2}div.idpc_af>ul>li.idpc_error{padding:.5em;text-align:center;cursor:default!important}div.idpc_af>ul>li.idpc_error:hover{background:#fff;cursor:default!important}div.idpc_af>ul>li[aria-selected=true]{background-color:#e5e4e2;z-index:3000}div.idpc_autocomplete>.idpc-unhide{font-size:.9em;text-decoration:underline;cursor:pointer}div.idpc_af>div>span{padding:.2em .5em;border-radius:3px;cursor:pointer;font-size:110%}span.idpc_icon{font-size:1.2em;line-height:1em;vertical-align:middle}div.idpc_toolbar>span span.idpc_country{margin-right:.3em;max-width:0;font-size:.9em;-webkit-transition:max-width .5s ease-out;transition:max-width .5s ease-out;display:inline-block;vertical-align:middle;white-space:nowrap;overflow:hidden}div.idpc_autocomplete>div>div>span:hover span.idpc_country{max-width:7em}div.idpc_autocomplete>div>div>span:hover{background-color:#e5e4e2;-webkit-transition:background-color .5s ease;-ms-transition:background-color .5s ease;transition:background-color .5s ease}"; - /** - * Injects CSS style into DOM - * - * Idempotent - * - * @hidden - */ - - var addStyle = function addStyle(c) { - var style = c.options.injectStyle; - if (!style) return; - var g = idpcState(); - if (!g.afstyle) g.afstyle = {}; - - if (isString$1(style) && !g.afstyle[style]) { - g.afstyle[style] = true; - var link = loadStyle(style, c.document); - c.document.head.appendChild(link); - return link; - } - - if (style === true && !g.afstyle[""]) { - g.afstyle[""] = true; - return injectStyle(d, c.document); - } - - return; - }; - /** - * Returns a negative offset which can be used to correctly align input box - * @hidden - */ - - var computeOffset = function computeOffset(c) { - var offset; - var input = c.input; - if (c.options.alignToInput === false) return {}; - - try { - var w = c.options.document.defaultView; - if (!w) return {}; - offset = w.getComputedStyle(input).marginBottom; - } catch (_) { - return {}; - } - - if (!offset) return {}; - var nOffset = parseInt(offset.replace("px", ""), 10); - if (isNaN(nOffset)) return {}; - if (nOffset === 0) return {}; - var negativeOffset = nOffset * -1 + c.options.offset; - return { - marginTop: negativeOffset + "px" - }; - }; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - function t(t, n) { - var e = "function" == typeof Symbol && t[Symbol.iterator]; - if (!e) return t; - var r, - o, - i = e.call(t), - a = []; - - try { - for (; (void 0 === n || n-- > 0) && !(r = i.next()).done;) { - a.push(r.value); - } - } catch (t) { - o = { - error: t - }; - } finally { - try { - r && !r.done && (e = i.return) && e.call(i); - } finally { - if (o) throw o.error; - } - } - - return a; - } - - var n; - !function (t) { - t[t.NotStarted = 0] = "NotStarted", t[t.Running = 1] = "Running", t[t.Stopped = 2] = "Stopped"; - }(n || (n = {})); - var e = { - type: "xstate.init" - }; - - function r(t) { - return void 0 === t ? [] : [].concat(t); - } - - function i(t, n) { - return "string" == typeof (t = "string" == typeof t && n && n[t] ? n[t] : t) ? { - type: t - } : "function" == typeof t ? { - type: t.name, - exec: t - } : t; - } - - function a(t) { - return function (n) { - return t === n; - }; - } - - function u(t) { - return "string" == typeof t ? { - type: t - } : t; - } - - function c(t, n) { - return { - value: t, - context: n, - actions: [], - changed: !1, - matches: a(t) - }; - } - - function f(t, n, e) { - var r = n, - o = !1; - return [t.filter(function (t) { - if ("xstate.assign" === t.type) { - o = !0; - var n = Object.assign({}, r); - return "function" == typeof t.assignment ? n = t.assignment(r, e) : Object.keys(t.assignment).forEach(function (o) { - n[o] = "function" == typeof t.assignment[o] ? t.assignment[o](r, e) : t.assignment[o]; - }), r = n, !1; - } - - return !0; - }), r, o]; - } - - function s(n, o) { - void 0 === o && (o = {}); - var s = t(f(r(n.states[n.initial].entry).map(function (t) { - return i(t, o.actions); - }), n.context, e), 2), - l = s[0], - v = s[1], - y = { - config: n, - _options: o, - initialState: { - value: n.initial, - actions: l, - context: v, - matches: a(n.initial) - }, - transition: function transition(e, o) { - var s, - l, - v = "string" == typeof e ? { - value: e, - context: n.context - } : e, - p = v.value, - g = v.context, - d = u(o), - x = n.states[p]; - - if (x.on) { - var m = r(x.on[d.type]); - - try { - for (var h = function (t) { - var n = "function" == typeof Symbol && Symbol.iterator, - e = n && t[n], - r = 0; - if (e) return e.call(t); - if (t && "number" == typeof t.length) return { - next: function next() { - return t && r >= t.length && (t = void 0), { - value: t && t[r++], - done: !t - }; - } - }; - throw new TypeError(n ? "Object is not iterable." : "Symbol.iterator is not defined."); - }(m), b = h.next(); !b.done; b = h.next()) { - var S = b.value; - if (void 0 === S) return c(p, g); - - var w = "string" == typeof S ? { - target: S - } : S, - j = w.target, - E = w.actions, - R = void 0 === E ? [] : E, - N = w.cond, - O = void 0 === N ? function () { - return !0; - } : N, - _ = void 0 === j, - k = null != j ? j : p, - T = n.states[k]; - - if (O(g, d)) { - var q = t(f((_ ? r(R) : [].concat(x.exit, R, T.entry).filter(function (t) { - return t; - })).map(function (t) { - return i(t, y._options.actions); - }), g, d), 3), - z = q[0], - A = q[1], - B = q[2], - C = null != j ? j : p; - return { - value: C, - context: A, - actions: z, - changed: j !== p || z.length > 0 || B, - matches: a(C) - }; - } - } - } catch (t) { - s = { - error: t - }; - } finally { - try { - b && !b.done && (l = h.return) && l.call(h); - } finally { - if (s) throw s.error; - } - } - } - - return c(p, g); - } - }; - return y; - } - - var l = function l(t, n) { - return t.actions.forEach(function (e) { - var r = e.exec; - return r && r(t.context, n); - }); - }; - - function v(t) { - var r = t.initialState, - o = n.NotStarted, - i = new Set(), - c = { - _machine: t, - send: function send(e) { - o === n.Running && (r = t.transition(r, e), l(r, u(e)), i.forEach(function (t) { - return t(r); - })); - }, - subscribe: function subscribe(t) { - return i.add(t), t(r), { - unsubscribe: function unsubscribe() { - return i.delete(t); - } - }; - }, - start: function start(i) { - if (i) { - var u = "object" == _typeof(i) ? i : { - context: t.config.context, - value: i - }; - r = { - value: u.value, - actions: [], - context: u.context, - matches: a(u.value) - }; - } - - return o = n.Running, l(r, e), c; - }, - stop: function stop() { - return o = n.Stopped, i.clear(), c; - }, - - get state() { - return r; - }, - - get status() { - return o; - } - - }; - return c; - } - - function ownKeys$3(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - - function _objectSpread$3(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$3(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$3(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - /** - * @hidden - */ - - var INPUT = { - INPUT: { - actions: "input" - } - }; - /** - * @hidden - */ - - var CLOSE = { - CLOSE: "closed" - }; - /** - * @hidden - */ - - var SUGGEST = { - SUGGEST: { - target: "suggesting", - actions: ["updateSuggestions"] - } - }; - /** - * @hidden - */ - - var NOTIFY = { - NOTIFY: { - target: "notifying", - actions: ["updateMessage"] - } - }; - /** - * @hidden - */ - - var NEXT = { - NEXT: { - actions: ["next", "gotoCurrent"] - } - }; - /** - * @hidden - */ - - var PREVIOUS = { - PREVIOUS: { - actions: ["previous", "gotoCurrent"] - } - }; - /** - * @hidden - */ - - var RESET = { - RESET: { - actions: ["resetCurrent", "gotoCurrent"] - } - }; - /** - * @hidden - */ - - var CHANGE_COUNTRY = { - CHANGE_COUNTRY: { - target: "suggesting_country" - } - }; - /** - * Creates a finite state machine that drives Address Finder UI - * @hidden - */ - - var create = function create(_ref) { - var c = _ref.c; - var machine = s({ - initial: "closed", - states: { - closed: { - entry: ["close"], - exit: ["open"], - on: { - AWAKE: [{ - target: "suggesting", - cond: function cond() { - return c.suggestions.length > 0; - } - }, { - target: "notifying" - }] - } - }, - notifying: { - entry: ["renderNotice"], - exit: ["clearAnnouncement"], - on: _objectSpread$3(_objectSpread$3(_objectSpread$3(_objectSpread$3(_objectSpread$3({}, CLOSE), SUGGEST), NOTIFY), INPUT), CHANGE_COUNTRY) - }, - suggesting_country: { - entry: ["renderContexts", "gotoCurrent", "expand", "addCountryHint"], - exit: ["resetCurrent", "gotoCurrent", "contract", "clearHint"], - on: _objectSpread$3(_objectSpread$3(_objectSpread$3(_objectSpread$3(_objectSpread$3(_objectSpread$3({}, CLOSE), NOTIFY), NEXT), PREVIOUS), RESET), {}, { - INPUT: { - actions: ["countryInput"] - }, - SELECT_COUNTRY: { - target: "notifying", - actions: ["selectCountry"] - } - }) - }, - suggesting: { - entry: ["renderSuggestions", "gotoCurrent", "expand", "addHint"], - exit: ["resetCurrent", "gotoCurrent", "contract", "clearHint"], - on: _objectSpread$3(_objectSpread$3(_objectSpread$3(_objectSpread$3(_objectSpread$3(_objectSpread$3(_objectSpread$3(_objectSpread$3(_objectSpread$3({}, CLOSE), SUGGEST), NOTIFY), INPUT), CHANGE_COUNTRY), NEXT), PREVIOUS), RESET), {}, { - SELECT_ADDRESS: { - target: "closed", - actions: ["selectAddress"] - } - }) - } - } - }, { - actions: { - addHint: function addHint() { - c.setPlaceholder(c.options.msgPlaceholder); - }, - addCountryHint: function addCountryHint() { - c.setPlaceholder(c.options.msgPlaceholderCountry); - }, - clearHint: function clearHint() { - c.unsetPlaceholder(); - }, - - /** - * Updates current li in list to active descendant - */ - gotoCurrent: function gotoCurrent() { - c.goToCurrent(); - }, - - /** - * Unhighlights a suggestion - */ - resetCurrent: function resetCurrent() { - c.current = -1; - }, - - /** - * Triggers onInput callback - */ - input: function input(_, e) { - if (e.type !== "INPUT") return; - c.retrieveSuggestions(e.event); - }, - - /** - * Narrows country search box - */ - countryInput: function countryInput() {}, - - /** - * Clears ARIA announcement fields - */ - clearAnnouncement: function clearAnnouncement() { - c.announce(""); - }, - - /** - * Renders suggestion within list - */ - renderContexts: function renderContexts(_, e) { - if (e.type !== "CHANGE_COUNTRY") return; - c.renderContexts(); - }, - - /** - * Renders suggestion within list - */ - renderSuggestions: function renderSuggestions(_, e) { - if (e.type !== "SUGGEST") return; - c.renderSuggestions(); - }, - - /** - * Update suggestions - */ - updateSuggestions: function updateSuggestions(_, e) { - if (e.type !== "SUGGEST") return; - c.updateSuggestions(e.suggestions); - }, - - /** - * Hides list and runs callback - */ - close: function close(_, e) { - if (e.type === "CLOSE") return c.close(e.reason); - c.close(); - }, - - /** - * Makes list visible and run callback - */ - open: function open() { - c.open(); - }, - - /** - * Marks aria component as expanded - */ - expand: function expand() { - c.ariaExpand(); - }, - - /** - * Marks aria component as closed - */ - contract: function contract() { - c.ariaContract(); - }, - - /** - * Assigns notification message - */ - updateMessage: function updateMessage(_, e) { - if (e.type !== "NOTIFY") return; - c.notification = e.notification; - }, - - /** - * Renders message container and current message - */ - renderNotice: function renderNotice() { - c.renderNotice(); - }, - - /** - * Selects next element in list. Wraps to top if at bottom - */ - next: function next() { - c.next(); - }, - - /** - * Selects previous element in list. Wraps to bottom if at top - */ - previous: function previous() { - c.previous(); - }, - - /** - * Triggers select on current context or clicked element - */ - selectCountry: function selectCountry(_, e) { - if (e.type !== "SELECT_COUNTRY") return; - var co = e.contextDetails; - if (!co) return; - c.applyContext(co); - c.notification = "Country switched to ".concat(co.name, " ").concat(co.icon); - }, - - /** - * Triggers select on current suggestion or clicked element - */ - selectAddress: function selectAddress(_, e) { - if (e.type !== "SELECT_ADDRESS") return; - var s = e.suggestion; - if (!s) return; - c.applySuggestion(s); - } - } - }); - return v(machine); - }; - - function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - - function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - /** - * @hidden - */ - - var NOOP$1 = function NOOP() {}; - /** - * Default options assigned to controller instances - */ - - var defaults$5 = { - // DOM - outputScope: null, - // Client - apiKey: "", - checkKey: true, - // WAI-ARIA compliance settings - aria: "1.0", - // Behaviour - titleizePostTown: true, - outputFields: {}, - names: {}, - labels: {}, - removeOrganisation: false, - injectStyle: true, - inputField: "", - autocomplete: "none", - populateCounty: true, - populateOrganisation: true, - queryOptions: {}, - alignToInput: true, - offset: 2, - hideToolbar: false, - // Country - defaultCountry: "GBR", - restrictCountries: [], - contexts: defaultContexts, - // Messages - msgFallback: "Please enter your address manually", - msgInitial: "Start typing to find address", - msgNoMatch: "No matches found", - msgList: "Select your address", - msgCountryToggle: "Change Country", - // Placeholder Messages - msgPlaceholder: "Type the first line or postal code of your address", - msgPlaceholderCountry: "Select your country", - // View classes - messageClass: "idpc_error", - containerClass: "idpc_autocomplete", - mainClass: "idpc_af", - listClass: "idpc_ul", - toolbarClass: "idpc_toolbar", - countryToggleClass: "idpc_country", - // Syles - mainStyle: {}, - inputStyle: {}, - listStyle: {}, - liStyle: {}, - containerStyle: {}, - // Hide / unhide - unhide: null, - unhideClass: "idpc-unhide", - msgUnhide: "Enter address manually", - hide: [], - // Callbacks - onOpen: NOOP$1, - onSelect: NOOP$1, - onBlur: NOOP$1, - onClose: NOOP$1, - onFocus: NOOP$1, - onInput: NOOP$1, - onLoaded: NOOP$1, - onSearchError: NOOP$1, - onSuggestionError: NOOP$1, - onMounted: NOOP$1, - onRemove: NOOP$1, - onSuggestionsRetrieved: NOOP$1, - onAddressSelected: NOOP$1, - onAddressRetrieved: NOOP$1, - onAddressPopulated: NOOP$1, - onFailedCheck: NOOP$1, - onMouseDown: NOOP$1, - onKeyDown: NOOP$1, - onUnhide: NOOP$1, - onCountrySelected: NOOP$1 - }; - /** - * # Controller - * - * The Autocomplete Controller class acts as the public class which you may - * wield to enable address autocomplete on your HTML address forms - * - * When instantiated, the controller will serve as a bridge beteen the - * address suggestion view presented on the DOM and the Ideal - * Postcodes Address resolution HTTP APIs - * - * The role of the controller is to bind to events produced by the user - * interface and take appropriate action including querying the API, - * modifying other aspects of the DOM. - */ - - var Controller = /*#__PURE__*/function () { - function Controller(options) { - var _this = this; - - _classCallCheck(this, Controller); - - this.options = _objectSpread$2(_objectSpread$2(_objectSpread$2({}, { - scope: window.document, - document: window.document - }), defaults$5), options); // Default inputField to line_1 if `inputField` not specified - - if (!options.inputField) this.options.inputField = this.options.outputFields.line_1 || ""; // To overcome config overload - idpcConfig global config object already - // defines autocomplete (boolean) - //@ts-ignore - - if (this.options.autocomplete === true) this.options.autocomplete = defaults$5.autocomplete; // Scope the operations of this controller to a document or DOM subtree - - this.scope = getScope(this.options.scope); // Assign a parent Document for elem creation - - this.document = getDocument(this.scope); // Assign a document or DOM subtree to scope outputs. Defaults to controller scope - - this.outputScope = findOrCreate(this.scope, this.options.outputScope, function () { - return _this.scope; - }); // Initialise state - - this.context = this.options.defaultCountry; - this.notification = this.options.msgInitial; - this.current = -1; - this.suggestions = []; - this.contextSuggestions = toContextList(this.options.contexts, this.options.restrictCountries); - this.client = new Client(_objectSpread$2(_objectSpread$2({}, this.options), {}, { - api_key: this.options.apiKey - })); - this.cache = new ApiCache(this.client); - this.retrieveSuggestions = debounce_1(function (event) { - _this.options.onInput.call(_this, event); - - var query = _this.query(); - - if (query.trim().length === 0) { - _this.setMessage(_this.options.msgInitial); - - return Promise.resolve(_this); - } - - return _this.cache.query(query, _objectSpread$2(_objectSpread$2({}, _this.options.queryOptions), {}, { - context: _this.context - })).then(function (suggestions) { - _this.options.onSuggestionsRetrieved.call(_this, suggestions); - - return _this.setSuggestions(suggestions, query); - }).catch(function (error) { - if (_this.query() === query) _this.setMessage(_this.options.msgFallback); - - _this.options.onSuggestionError.call(_this, error); - - return _this; - }); - }, 100, { - leading: true, - trailing: true, - maxWait: 100 - }); - this.ids = idGen("idpcaf"); // Configure container - - this.container = this.options.document.createElement("div"); - this.container.className = this.options.containerClass; - this.container.id = this.ids(); - this.container.setAttribute("aria-haspopup", "listbox"); // Create message element - - this.message = this.options.document.createElement("li"); - this.message.textContent = this.options.msgInitial; - this.message.className = this.options.messageClass; // Create button to toggle country selection - - this.countryToggle = this.options.document.createElement("span"); - this.countryToggle.className = this.options.countryToggleClass; - this.countryToggle.addEventListener("mousedown", _onCountryToggle(this)); - this.countryIcon = this.options.document.createElement("span"); - this.countryIcon.className = "idpc_icon"; - this.countryIcon.innerText = this.currentContext().icon; - this.countryMessage = this.options.document.createElement("span"); - this.countryMessage.innerText = "Select Country"; - this.countryMessage.className = "idpc_country"; - this.countryToggle.appendChild(this.countryMessage); - this.countryToggle.appendChild(this.countryIcon); // Create toolbar (for country selection) - - this.toolbar = this.options.document.createElement("div"); - this.toolbar.className = this.options.toolbarClass; - this.toolbar.appendChild(this.countryToggle); - if (this.options.hideToolbar) hide(this.toolbar); // Configure UL - - this.list = this.options.document.createElement("ul"); - this.list.className = this.options.listClass; - this.list.id = this.ids(); - this.list.setAttribute("aria-label", this.options.msgList); - this.list.setAttribute("role", "listbox"); - this.mainComponent = this.options.document.createElement("div"); - this.mainComponent.appendChild(this.list); - this.mainComponent.appendChild(this.toolbar); - this.mainComponent.className = this.options.mainClass; - hide(this.mainComponent); //configure unhide - - this.unhideEvent = this.unhideFields.bind(this); - this.unhide = this.createUnhide(); // Configure input - - var input; - - if (isString$1(this.options.inputField)) { - input = this.scope.querySelector(this.options.inputField); - } else { - input = this.options.inputField; - } - - if (!input) throw new Error("Address Finder: Unable to find valid input field"); - this.input = input; - this.input.setAttribute("autocomplete", this.options.autocomplete); - this.input.setAttribute("aria-autocomplete", "list"); - this.input.setAttribute("aria-controls", this.list.id); - this.input.setAttribute("aria-autocomplete", "list"); - this.input.setAttribute("aria-activedescendant", ""); - this.input.setAttribute("autocorrect", "off"); - this.input.setAttribute("autocapitalize", "off"); - this.input.setAttribute("spellcheck", "false"); - if (!this.input.id) this.input.id = this.ids(); // Apply additional accessibility improvments - - this.ariaAnchor().setAttribute("role", "combobox"); - this.ariaAnchor().setAttribute("aria-expanded", "false"); - this.ariaAnchor().setAttribute("aria-owns", this.list.id); - this.placeholderCache = this.input.placeholder; // Create listeners - - this.inputListener = _onInput(this); - this.blurListener = _onBlur(this); - this.focusListener = _onFocus(this); - this.keydownListener = _onKeyDown(this); - - var _announcer = announcer({ - idA: this.ids(), - idB: this.ids(), - document: this.options.document - }), - container = _announcer.container, - announce = _announcer.announce; - - this.announce = announce; - this.alerts = container; - this.inputStyle = setStyle(this.input, this.options.inputStyle); - setStyle(this.container, this.options.containerStyle); - setStyle(this.list, this.options.listStyle); // Apply an offset based off any margin - - var offset = computeOffset(this); - setStyle(this.mainComponent, _objectSpread$2(_objectSpread$2({}, offset), this.options.mainStyle)); - this.fsm = create({ - c: this - }); - this.init(); - } - /** - * Sets placeholder and caches previous result - * @hidden - */ - - - _createClass(Controller, [{ - key: "setPlaceholder", - value: function setPlaceholder(msg) { - this.input.placeholder = msg; - } - /** - * Unsets any placeholder value to original - * @hidden - */ - - }, { - key: "unsetPlaceholder", - value: function unsetPlaceholder() { - if (this.placeholderCache === undefined) return this.input.removeAttribute("placeholder"); - this.input.placeholder = this.placeholderCache; - } - /** - * Returns current highlighted context - * @hidden - */ - - }, { - key: "currentContext", - value: function currentContext() { - var c = this.options.contexts[this.context]; - return { - code: this.context, - name: c.name, - icon: c.icon - }; - } - /** - * Binds to DOM and begin DOM mutations - * @hidden - */ - - }, { - key: "load", - value: function load() { - this.attach(); - addStyle(this); - this.options.onLoaded.call(this); - } - /** - * Attaches Controller to the DOM. - * - * If `checkKey` is enabled, a key check will be performed prioer to binding. Use the `onLoaded` and `onFailedCheck` callbacks to define follow up behaviour if the key check succeeds or fails - */ - - }, { - key: "init", - value: function init() { - var _this2 = this; - - return new Promise(function (resolve) { - if (!_this2.options.checkKey) { - _this2.load(); - - resolve(); - return; - } - - checkKeyUsability({ - client: _this2.client, - api_key: _this2.options.apiKey - }).then(function (response) { - if (!response.available) throw new Error("Key currently not usable"); - - _this2.load(); - - resolve(); - }).catch(function (error) { - _this2.options.onFailedCheck.call(_this2, error); - - resolve(); - }); - }); - } - /** - * Render available country options - */ - - }, { - key: "renderContexts", - value: function renderContexts() { - var _this3 = this; - - this.list.innerHTML = ""; - this.contextSuggestions.forEach(function (contextDetails, i) { - var name = contextDetails.name; - - var li = _this3.options.document.createElement("li"); - - li.textContent = name; - li.setAttribute("aria-selected", "false"); - li.setAttribute("tabindex", "-1"); - li.setAttribute("aria-posinset", "".concat(i + 1)); - li.setAttribute("aria-setsize", _this3.contextSuggestions.length.toString()); - li.setAttribute("role", "option"); - setStyle(li, _this3.options.liStyle); - li.addEventListener("mousedown", function (e) { - e.preventDefault(); - - _this3.options.onMouseDown.call(_this3, e); - - _this3.fsm.send({ - type: "SELECT_COUNTRY", - contextDetails: contextDetails - }); - }); - li.id = "".concat(_this3.list.id, "_").concat(i); - - _this3.list.appendChild(li); - }); - this.announce("".concat(this.contextSuggestions.length, " countries available")); - } - /** - * Render current address suggestions - */ - - }, { - key: "renderSuggestions", - value: function renderSuggestions() { - var _this4 = this; - - this.list.innerHTML = ""; - var s = this.suggestions; - s.forEach(function (suggestion, i) { - var li = _this4.options.document.createElement("li"); - - li.textContent = suggestion.suggestion; - li.setAttribute("aria-selected", "false"); - li.setAttribute("tabindex", "-1"); - li.setAttribute("title", suggestion.suggestion); - li.setAttribute("aria-posinset", "".concat(i + 1)); - li.setAttribute("aria-setsize", s.length.toString()); - li.setAttribute("role", "option"); - setStyle(li, _this4.options.liStyle); - li.addEventListener("mousedown", function (e) { - e.preventDefault(); - - _this4.options.onMouseDown.call(_this4, e); - - _this4.fsm.send({ - type: "SELECT_ADDRESS", - suggestion: suggestion - }); - }); - li.id = "".concat(_this4.list.id, "_").concat(i); - - _this4.list.appendChild(li); - }); - this.announce("".concat(s.length, " addresses available")); - } - /** - * Updates current li in list to active descendant - */ - - }, { - key: "goToCurrent", - value: function goToCurrent() { - var lis = this.list.children; - this.input.setAttribute("aria-activedescendant", ""); - - for (var i = 0; i < lis.length; i += 1) { - if (i === this.current) { - this.input.setAttribute("aria-activedescendant", lis[i].id); - lis[i].setAttribute("aria-selected", "true"); - this.goto(i); - } else { - lis[i].setAttribute("aria-selected", "false"); - } - } - } - /** - * Marks aria component as opened - */ - - }, { - key: "ariaExpand", - value: function ariaExpand() { - this.ariaAnchor().setAttribute("aria-expanded", "true"); - } - /** - * Marks aria component as closed - */ - - }, { - key: "ariaContract", - value: function ariaContract() { - this.ariaAnchor().setAttribute("aria-expanded", "false"); - } - /** - * Resolves a suggestion to full address and apply results to form - */ - - }, { - key: "applySuggestion", - value: function applySuggestion(suggestion) { - var _this5 = this; - - this.options.onSelect.call(this, suggestion); - this.options.onAddressSelected.call(this, suggestion); - this.announce("The address ".concat(suggestion.suggestion, " has been applied to this form")); - return this.cache.resolve(suggestion).then(function (address) { - if (address === null) throw "Unable to retrieve address"; - - _this5.options.onAddressRetrieved.call(_this5, address); - - _this5.populateAddress(address); - - return _this5; - }).catch(function (error) { - _this5.open(); - - _this5.setMessage(_this5.options.msgFallback); - - _this5.options.onSearchError.call(_this5, error); - - return error; - }); - } - /** - * Writes a selected to the input fields specified in the controller config - */ - - }, { - key: "populateAddress", - value: function populateAddress$1(address) { - this.unhideFields(); - - populateAddress({ - address: address, - config: _objectSpread$2(_objectSpread$2({}, this.options), {}, { - scope: this.outputScope - }), - outputFields: this.options.outputFields, - names: this.options.names, - labels: this.options.labels - }); - - this.options.onAddressPopulated.call(this, address); - } - /** - * Applies new query options to search. This process clears the existing - * cache to prevent stale searches - */ - - }, { - key: "setQueryOptions", - value: function setQueryOptions(options) { - this.cache.clear(); - this.options.queryOptions = options; - } - /** - * Adds Address Finder to DOM - * - Wraps input with container - * - Appends suggestion list to container - * - Enables listeners - * - Starts FSM - */ - - }, { - key: "attach", - value: function attach() { - if (this.fsm.status === n.Running) return this; - this.input.addEventListener("input", this.inputListener); - this.input.addEventListener("blur", this.blurListener); - this.input.addEventListener("focus", this.focusListener); - this.input.addEventListener("keydown", this.keydownListener); - var parent = this.input.parentNode; - - if (parent) { - // Wrap input in a div and append suggestion list - parent.insertBefore(this.container, this.input); - this.container.appendChild(this.input); - this.container.appendChild(this.mainComponent); - this.container.appendChild(this.alerts); - if (this.options.hide.length > 0 && this.options.unhide == null) this.container.appendChild(this.unhide); - } - - this.fsm.start(); - this.options.onMounted.call(this); - this.hideFields(); - return this; - } - /** - * Removes Address Finder from DOM - * - Disable listeners - * - Removes sugestion list from container - * - Appends suggestion list to container - * - Enables listeners - * - Stops FSM - */ - - }, { - key: "detach", - value: function detach() { - if (this.fsm.status !== n.Running) return this; - this.input.removeEventListener("input", this.inputListener); - this.input.removeEventListener("blur", this.blurListener); - this.input.removeEventListener("focus", this.focusListener); - this.input.removeEventListener("keydown", this.keydownListener); - this.container.removeChild(this.mainComponent); - this.container.removeChild(this.alerts); - var parent = this.container.parentNode; - - if (parent) { - parent.insertBefore(this.input, this.container); - parent.removeChild(this.container); - } - - this.unmountUnhide(); - this.unhideFields(); - this.fsm.stop(); - restoreStyle(this.input, this.inputStyle); - this.options.onRemove.call(this); - this.unsetPlaceholder(); - return this; - } - /** - * Sets message as a list item, no or empty string removes any message - */ - - }, { - key: "setMessage", - value: function setMessage(notification) { - this.fsm.send({ - type: "NOTIFY", - notification: notification - }); - return this; - } - /** - * Returns HTML Element which recevies key aria attributes - * - * @hidden - */ - - }, { - key: "ariaAnchor", - value: function ariaAnchor() { - if (this.options.aria === "1.0") return this.input; - return this.container; - } - /** - * Returns current address query - */ - - }, { - key: "query", - value: function query() { - return this.input.value; - } - /** - * Set address finder suggestions - */ - - }, { - key: "setSuggestions", - value: function setSuggestions(suggestions, query) { - if (query !== this.query()) return this; - if (suggestions.length === 0) return this.setMessage(this.options.msgNoMatch); - this.fsm.send({ - type: "SUGGEST", - suggestions: suggestions - }); - return this; - } - /** - * Close address finder - */ - - }, { - key: "close", - value: function close() { - var reason = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "blur"; - hide(this.mainComponent); - if (reason === "esc") update(this.input, ""); - this.options.onClose.call(this, reason); - } - /** - * Updates suggestions and resets current selection - * @hidden - */ - - }, { - key: "updateSuggestions", - value: function updateSuggestions(s) { - this.suggestions = s; - this.current = -1; - } - /** - * Applies context to API cache - * @hidden - */ - - }, { - key: "applyContext", - value: function applyContext(details) { - var context = details.code; - this.context = context; - this.countryIcon.innerText = details.icon; - this.announce("Country switched to ".concat(details.name)); - } - /** - * Renders notification box - * @hidden - */ - - }, { - key: "renderNotice", - value: function renderNotice() { - this.list.innerHTML = ""; - this.input.setAttribute("aria-activedescendant", ""); - this.message.textContent = this.notification; - this.announce(this.notification); - this.list.appendChild(this.message); - } - /** - * Open address finder - * @hidden - */ - - }, { - key: "open", - value: function open() { - show(this.mainComponent); - this.options.onOpen.call(this); - } - /** - * Sets next suggestion as current - * @hidden - */ - - }, { - key: "next", - value: function next() { - if (this.current + 1 > this.list.children.length - 1) { - // Goes over edge of list and back to start - this.current = 0; - } else { - this.current += 1; - } - - return this; - } - /** - * Sets previous suggestion as current - * @hidden - */ - - }, { - key: "previous", - value: function previous() { - if (this.current - 1 < 0) { - this.current = this.list.children.length - 1; // Wrap to last elem - } else { - this.current += -1; - } - - return this; - } - /** - * Given a HTMLLiElement, scroll parent until it is in view - * @hidden - */ - - }, { - key: "scrollToView", - value: function scrollToView(li) { - var liOffset = li.offsetTop; - var ulScrollTop = this.list.scrollTop; - - if (liOffset < ulScrollTop) { - this.list.scrollTop = liOffset; - } - - var ulHeight = this.list.clientHeight; - var liHeight = li.clientHeight; - - if (liOffset + liHeight > ulScrollTop + ulHeight) { - this.list.scrollTop = liOffset - ulHeight + liHeight; - } - - return this; - } - /** - * Moves currently selected li into view - * @hidden - */ - - }, { - key: "goto", - value: function goto(i) { - var lis = this.list.children; - var suggestion = lis[i]; - - if (i > -1 && lis.length > 0) { - this.scrollToView(suggestion); - } else { - this.scrollToView(lis[0]); - } - - return this; - } - /** - * Returns true if address finder is open - */ - - }, { - key: "opened", - value: function opened() { - return !this.closed(); - } - /** - * Returs false if address finder is closed - */ - - }, { - key: "closed", - value: function closed() { - return this.fsm.state.matches("closed"); - } - /** - * Creates a clickable element that can trigger unhiding of fields - */ - - }, { - key: "createUnhide", - value: function createUnhide() { - var _this6 = this; - - var e = findOrCreate(this.scope, this.options.unhide, function () { - var e = _this6.options.document.createElement("p"); - - e.innerText = _this6.options.msgUnhide; - e.setAttribute("role", "button"); - e.setAttribute("tabindex", "0"); - if (_this6.options.unhideClass) e.className = _this6.options.unhideClass; - return e; - }); - e.addEventListener("click", this.unhideEvent); - return e; - } - /** - * Removes unhide elem from DOM - */ - - }, { - key: "unmountUnhide", - value: function unmountUnhide() { - this.unhide.removeEventListener("click", this.unhideEvent); - if (this.options.unhide == null && this.options.hide.length) remove(this.unhide); - } - }, { - key: "hiddenFields", - value: function hiddenFields() { - var _this7 = this; - - return this.options.hide.map(function (e) { - if (isString$1(e)) return toHtmlElem(_this7.options.scope, e); - return e; - }).filter(function (e) { - return e !== null; - }); - } - /** - * Hides fields marked for hiding - */ - - }, { - key: "hideFields", - value: function hideFields() { - this.hiddenFields().forEach(hide); - } - /** - * Unhides fields marked for hiding - */ - - }, { - key: "unhideFields", - value: function unhideFields() { - this.hiddenFields().forEach(show); - this.options.onUnhide.call(this); - } - }]); - - return Controller; - }(); - /** - * Event handler: Fires when focus moves away from input field - * @hidden - */ - - var _onBlur = function _onBlur(c) { - return function () { - c.options.onBlur.call(c); - c.fsm.send({ - type: "CLOSE", - reason: "blur" - }); - }; - }; - /** - * Event handler: Fires when input field is focused - * @hidden - */ - - - var _onFocus = function _onFocus(c) { - return function (_) { - c.options.onFocus.call(c); - c.fsm.send("AWAKE"); - }; - }; - /** - * Event handler: Fires when input is detected on input field - * @hidden - */ - - - var _onInput = function _onInput(c) { - return function (event) { - if (c.query().toLowerCase() === ":c") { - update(c.input, ""); - return c.fsm.send({ - type: "CHANGE_COUNTRY" - }); - } - - c.fsm.send({ - type: "INPUT", - event: event - }); - }; - }; - /** - * Event handler: Fires when country selection is clicked - * Triggers: - * - Country selection menu - * - * @hidden - */ - - - var _onCountryToggle = function _onCountryToggle(c) { - return function (e) { - e.preventDefault(); - c.fsm.send({ - type: "CHANGE_COUNTRY" - }); - }; - }; - /** - * Event handler: Fires on "keyDown" event of search field - * @hidden - */ - - - var _onKeyDown = function _onKeyDown(c) { - return function (event) { - // Dispatch events based on keys - var key = toKey(event); - if (key === "Enter") event.preventDefault(); - c.options.onKeyDown.call(c, event); - if (c.closed()) return c.fsm.send("AWAKE"); // When suggesting country - - if (c.fsm.state.matches("suggesting_country")) { - if (key === "Enter") { - var contextDetails = c.contextSuggestions[c.current]; - if (contextDetails) c.fsm.send({ - type: "SELECT_COUNTRY", - contextDetails: contextDetails - }); - } - - if (key === "Backspace") c.fsm.send({ - type: "INPUT", - event: event - }); - - if (key === "ArrowUp") { - event.preventDefault(); - c.fsm.send("PREVIOUS"); - } - - if (key === "ArrowDown") { - event.preventDefault(); - c.fsm.send("NEXT"); - } - } // When suggesting address - - - if (c.fsm.state.matches("suggesting")) { - if (key === "Enter") { - var suggestion = c.suggestions[c.current]; - if (suggestion) c.fsm.send({ - type: "SELECT_ADDRESS", - suggestion: suggestion - }); - } - - if (key === "Backspace") c.fsm.send({ - type: "INPUT", - event: event - }); - - if (key === "ArrowUp") { - event.preventDefault(); - c.fsm.send("PREVIOUS"); - } - - if (key === "ArrowDown") { - event.preventDefault(); - c.fsm.send("NEXT"); - } - } - - if (key === "Escape") c.fsm.send({ - type: "CLOSE", - reason: "esc" - }); - if (key === "Home") c.fsm.send({ - type: "RESET" - }); - if (key === "End") c.fsm.send({ - type: "RESET" - }); - }; - }; - /** - * Retrieve Element - * - If string, assumes is valid and returns first match within scope - * - If null, invokes the create method to return a default - * - If HTMLElement returns instance - * @hidden - */ - - var findOrCreate = function findOrCreate(scope, q, create) { - if (isString$1(q)) return scope.querySelector(q); - if (create && q === null) return create(); - return q; - }; - - /** - * Configure and launch an instance of the Address Finder - * - * This method will create and return a new AddressFinder instance. It will also add a global reference to the controller at `AddressFinder.controllers` - */ - - var setup = function setup(config) { - var c = new Controller(config); - controllers.push(c); - return c; - }; - /** - * Configure and launch an instance of the Address Finder - * - * This is equivalent to invoking `setup` except inside a DOMContentLoaded event callback - */ - - var go = function go(config, d) { - return new Promise(function (resolve, _) { - (d || document).addEventListener("DOMContentLoaded", function (_) { - var c = setup(config); - return resolve(c); - }); - }).catch(function (_) { - return null; - }); - }; - /** - * Cache of Address Finder controllers - */ - - var controllers = []; - - function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - - function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - - var isTrue = function isTrue() { - return true; - }; - - var getAnchors = function getAnchors(config, marker) { - var scope = getScope(config.scope || null); - var matches = scope.querySelectorAll(config.anchor || config.inputField || (config.outputFields || {}).line_1); - return toArray(matches).filter(function (e) { - return !loaded(e, marker); - }); - }; - - var DEFAULT_INTERVAL = 1000; - - var formScope = function formScope(anchor) { - return getParent(anchor, "FORM"); - }; - /** - * Dynamically apply AddressFinder when relevant fields appear - * - Exits if page test is fails - * - Check if key usable - * - Creates a bind method - * - Retrives parent scope - * - Marks anchor if completed - * - Creates timer tools - */ - - - var watch = function watch(config) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var client = new Client({ - api_key: config.apiKey - }); - var _options$pageTest = options.pageTest, - pageTest = _options$pageTest === void 0 ? isTrue : _options$pageTest; - if (!pageTest()) return Promise.resolve(null); - return checkKeyUsability({ - client: client - }).then(function (key) { - if (!key.available) return null; - var _options$getScope = options.getScope, - getScope = _options$getScope === void 0 ? formScope : _options$getScope, - _options$interval = options.interval, - interval = _options$interval === void 0 ? DEFAULT_INTERVAL : _options$interval, - anchor = options.anchor, - _options$onBind = options.onBind, - onBind = _options$onBind === void 0 ? NOOP$1 : _options$onBind, - _options$onAnchorFoun = options.onAnchorFound, - onAnchorFound = _options$onAnchorFoun === void 0 ? NOOP$1 : _options$onAnchorFoun, - _options$onBindAttemp = options.onBindAttempt, - onBindAttempt = _options$onBindAttemp === void 0 ? NOOP$1 : _options$onBindAttemp, - _options$immediate = options.immediate, - immediate = _options$immediate === void 0 ? true : _options$immediate, - _options$marker = options.marker, - marker = _options$marker === void 0 ? "idpc" : _options$marker; - - var bind = function bind() { - onBindAttempt({ - config: config, - options: options - }); - getAnchors(_objectSpread$1({ - anchor: anchor - }, config), marker).forEach(function (anchor) { - var scope = getScope(anchor); - if (!scope) return; - - var newConfig = _objectSpread$1(_objectSpread$1({ - scope: scope - }, config), {}, { - checkKey: false - }); - - onAnchorFound({ - anchor: anchor, - scope: scope, - config: newConfig - }); - var c = setup(newConfig); - markLoaded(anchor, marker); - onBind(c); - }); - }; - - var _generateTimer = generateTimer({ - bind: bind, - pageTest: pageTest, - interval: interval - }), - start = _generateTimer.start, - stop = _generateTimer.stop; - - if (immediate) start(); - return { - start: start, - stop: stop, - bind: bind - }; - }).catch(function (e) { - // Swallow promise errors and raise via optionall onError callback - if (options.onError) options.onError(e); - return null; - }); - }; - - /** - * @module Address-Finder Exports - */ - /** - * Namespace that exports Address Finder methods and classes - */ - - var AddressFinder = { - setup: setup, - controllers: controllers, - Controller: Controller, - defaults: defaults$5, - watch: watch, - go: go - }; - - var axios$1 = {exports: {}}; - - var bind$6 = function bind(fn, thisArg) { - return function wrap() { - var args = new Array(arguments.length); - - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } - - return fn.apply(thisArg, args); - }; - }; - - var bind$5 = bind$6; // utils is a library of generic helper functions non-specific to axios - - var toString = Object.prototype.toString; - /** - * Determine if a value is an Array - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an Array, otherwise false - */ - - function isArray(val) { - return toString.call(val) === '[object Array]'; - } - /** - * Determine if a value is undefined - * - * @param {Object} val The value to test - * @returns {boolean} True if the value is undefined, otherwise false - */ - - - function isUndefined(val) { - return typeof val === 'undefined'; - } - /** - * Determine if a value is a Buffer - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Buffer, otherwise false - */ - - - function isBuffer(val) { - return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); - } - /** - * Determine if a value is an ArrayBuffer - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an ArrayBuffer, otherwise false - */ - - - function isArrayBuffer(val) { - return toString.call(val) === '[object ArrayBuffer]'; - } - /** - * Determine if a value is a FormData - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an FormData, otherwise false - */ - - - function isFormData(val) { - return typeof FormData !== 'undefined' && val instanceof FormData; - } - /** - * Determine if a value is a view on an ArrayBuffer - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false - */ - - - function isArrayBufferView(val) { - var result; - - if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) { - result = ArrayBuffer.isView(val); - } else { - result = val && val.buffer && val.buffer instanceof ArrayBuffer; - } - - return result; - } - /** - * Determine if a value is a String - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a String, otherwise false - */ - - - function isString(val) { - return typeof val === 'string'; - } - /** - * Determine if a value is a Number - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Number, otherwise false - */ - - - function isNumber(val) { - return typeof val === 'number'; - } - /** - * Determine if a value is an Object - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an Object, otherwise false - */ - - - function isObject(val) { - return val !== null && _typeof(val) === 'object'; - } - /** - * Determine if a value is a plain Object - * - * @param {Object} val The value to test - * @return {boolean} True if value is a plain Object, otherwise false - */ - - - function isPlainObject(val) { - if (toString.call(val) !== '[object Object]') { - return false; - } - - var prototype = Object.getPrototypeOf(val); - return prototype === null || prototype === Object.prototype; - } - /** - * Determine if a value is a Date - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Date, otherwise false - */ - - - function isDate(val) { - return toString.call(val) === '[object Date]'; - } - /** - * Determine if a value is a File - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a File, otherwise false - */ - - - function isFile(val) { - return toString.call(val) === '[object File]'; - } - /** - * Determine if a value is a Blob - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Blob, otherwise false - */ - - - function isBlob(val) { - return toString.call(val) === '[object Blob]'; - } - /** - * Determine if a value is a Function - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Function, otherwise false - */ - - - function isFunction(val) { - return toString.call(val) === '[object Function]'; - } - /** - * Determine if a value is a Stream - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Stream, otherwise false - */ - - - function isStream(val) { - return isObject(val) && isFunction(val.pipe); - } - /** - * Determine if a value is a URLSearchParams object - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a URLSearchParams object, otherwise false - */ - - - function isURLSearchParams(val) { - return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; - } - /** - * Trim excess whitespace off the beginning and end of a string - * - * @param {String} str The String to trim - * @returns {String} The String freed of excess whitespace - */ - - - function trim(str) { - return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, ''); - } - /** - * Determine if we're running in a standard browser environment - * - * This allows axios to run in a web worker, and react-native. - * Both environments support XMLHttpRequest, but not fully standard globals. - * - * web workers: - * typeof window -> undefined - * typeof document -> undefined - * - * react-native: - * navigator.product -> 'ReactNative' - * nativescript - * navigator.product -> 'NativeScript' or 'NS' - */ - - - function isStandardBrowserEnv() { - if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || navigator.product === 'NativeScript' || navigator.product === 'NS')) { - return false; - } - - return typeof window !== 'undefined' && typeof document !== 'undefined'; - } - /** - * Iterate over an Array or an Object invoking a function for each item. - * - * If `obj` is an Array callback will be called passing - * the value, index, and complete array for each item. - * - * If 'obj' is an Object callback will be called passing - * the value, key, and complete object for each property. - * - * @param {Object|Array} obj The object to iterate - * @param {Function} fn The callback to invoke for each item - */ - - - function forEach(obj, fn) { - // Don't bother if no value provided - if (obj === null || typeof obj === 'undefined') { - return; - } // Force an array if not already something iterable - - - if (_typeof(obj) !== 'object') { - /*eslint no-param-reassign:0*/ - obj = [obj]; - } - - if (isArray(obj)) { - // Iterate over array values - for (var i = 0, l = obj.length; i < l; i++) { - fn.call(null, obj[i], i, obj); - } - } else { - // Iterate over object keys - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - fn.call(null, obj[key], key, obj); - } - } - } - } - /** - * Accepts varargs expecting each argument to be an object, then - * immutably merges the properties of each object and returns result. - * - * When multiple objects contain the same key the later object in - * the arguments list will take precedence. - * - * Example: - * - * ```js - * var result = merge({foo: 123}, {foo: 456}); - * console.log(result.foo); // outputs 456 - * ``` - * - * @param {Object} obj1 Object to merge - * @returns {Object} Result of all merge properties - */ - - - function merge() { - var result = {}; - - function assignValue(val, key) { - if (isPlainObject(result[key]) && isPlainObject(val)) { - result[key] = merge(result[key], val); - } else if (isPlainObject(val)) { - result[key] = merge({}, val); - } else if (isArray(val)) { - result[key] = val.slice(); - } else { - result[key] = val; - } - } - - for (var i = 0, l = arguments.length; i < l; i++) { - forEach(arguments[i], assignValue); - } - - return result; - } - /** - * Extends object a by mutably adding to it the properties of object b. - * - * @param {Object} a The object to be extended - * @param {Object} b The object to copy properties from - * @param {Object} thisArg The object to bind function to - * @return {Object} The resulting value of object a - */ - - - function extend(a, b, thisArg) { - forEach(b, function assignValue(val, key) { - if (thisArg && typeof val === 'function') { - a[key] = bind$5(val, thisArg); - } else { - a[key] = val; - } - }); - return a; - } - /** - * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) - * - * @param {string} content with BOM - * @return {string} content value without BOM - */ - - - function stripBOM(content) { - if (content.charCodeAt(0) === 0xFEFF) { - content = content.slice(1); - } - - return content; - } - - var utils$d = { - isArray: isArray, - isArrayBuffer: isArrayBuffer, - isBuffer: isBuffer, - isFormData: isFormData, - isArrayBufferView: isArrayBufferView, - isString: isString, - isNumber: isNumber, - isObject: isObject, - isPlainObject: isPlainObject, - isUndefined: isUndefined, - isDate: isDate, - isFile: isFile, - isBlob: isBlob, - isFunction: isFunction, - isStream: isStream, - isURLSearchParams: isURLSearchParams, - isStandardBrowserEnv: isStandardBrowserEnv, - forEach: forEach, - merge: merge, - extend: extend, - trim: trim, - stripBOM: stripBOM - }; - - var utils$c = utils$d; - - function encode(val) { - return encodeURIComponent(val).replace(/%3A/gi, ':').replace(/%24/g, '$').replace(/%2C/gi, ',').replace(/%20/g, '+').replace(/%5B/gi, '[').replace(/%5D/gi, ']'); - } - /** - * Build a URL by appending params to the end - * - * @param {string} url The base of the url (e.g., http://www.google.com) - * @param {object} [params] The params to be appended - * @returns {string} The formatted url - */ - - - var buildURL$2 = function buildURL(url, params, paramsSerializer) { - /*eslint no-param-reassign:0*/ - if (!params) { - return url; - } - - var serializedParams; - - if (paramsSerializer) { - serializedParams = paramsSerializer(params); - } else if (utils$c.isURLSearchParams(params)) { - serializedParams = params.toString(); - } else { - var parts = []; - utils$c.forEach(params, function serialize(val, key) { - if (val === null || typeof val === 'undefined') { - return; - } - - if (utils$c.isArray(val)) { - key = key + '[]'; - } else { - val = [val]; - } - - utils$c.forEach(val, function parseValue(v) { - if (utils$c.isDate(v)) { - v = v.toISOString(); - } else if (utils$c.isObject(v)) { - v = JSON.stringify(v); - } - - parts.push(encode(key) + '=' + encode(v)); - }); - }); - serializedParams = parts.join('&'); - } - - if (serializedParams) { - var hashmarkIndex = url.indexOf('#'); - - if (hashmarkIndex !== -1) { - url = url.slice(0, hashmarkIndex); - } - - url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; - } - - return url; - }; - - var utils$b = utils$d; - - function InterceptorManager$1() { - this.handlers = []; - } - /** - * Add a new interceptor to the stack - * - * @param {Function} fulfilled The function to handle `then` for a `Promise` - * @param {Function} rejected The function to handle `reject` for a `Promise` - * - * @return {Number} An ID used to remove interceptor later - */ - - - InterceptorManager$1.prototype.use = function use(fulfilled, rejected, options) { - this.handlers.push({ - fulfilled: fulfilled, - rejected: rejected, - synchronous: options ? options.synchronous : false, - runWhen: options ? options.runWhen : null - }); - return this.handlers.length - 1; - }; - /** - * Remove an interceptor from the stack - * - * @param {Number} id The ID that was returned by `use` - */ - - - InterceptorManager$1.prototype.eject = function eject(id) { - if (this.handlers[id]) { - this.handlers[id] = null; - } - }; - /** - * Iterate over all the registered interceptors - * - * This method is particularly useful for skipping over any - * interceptors that may have become `null` calling `eject`. - * - * @param {Function} fn The function to call for each interceptor - */ - - - InterceptorManager$1.prototype.forEach = function forEach(fn) { - utils$b.forEach(this.handlers, function forEachHandler(h) { - if (h !== null) { - fn(h); - } - }); - }; - - var InterceptorManager_1 = InterceptorManager$1; - - var utils$a = utils$d; - - var normalizeHeaderName$1 = function normalizeHeaderName(headers, normalizedName) { - utils$a.forEach(headers, function processHeader(value, name) { - if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { - headers[normalizedName] = value; - delete headers[name]; - } - }); - }; - - /** - * Update an Error with the specified config, error code, and response. - * - * @param {Error} error The error to update. - * @param {Object} config The config. - * @param {string} [code] The error code (for example, 'ECONNABORTED'). - * @param {Object} [request] The request. - * @param {Object} [response] The response. - * @returns {Error} The error. - */ - - - var enhanceError$2 = function enhanceError(error, config, code, request, response) { - error.config = config; - - if (code) { - error.code = code; - } - - error.request = request; - error.response = response; - error.isAxiosError = true; - - error.toJSON = function toJSON() { - return { - // Standard - message: this.message, - name: this.name, - // Microsoft - description: this.description, - number: this.number, - // Mozilla - fileName: this.fileName, - lineNumber: this.lineNumber, - columnNumber: this.columnNumber, - stack: this.stack, - // Axios - config: this.config, - code: this.code, - status: this.response && this.response.status ? this.response.status : null - }; - }; - - return error; - }; - - var enhanceError$1 = enhanceError$2; - /** - * Create an Error with the specified message, config, error code, request and response. - * - * @param {string} message The error message. - * @param {Object} config The config. - * @param {string} [code] The error code (for example, 'ECONNABORTED'). - * @param {Object} [request] The request. - * @param {Object} [response] The response. - * @returns {Error} The created error. - */ - - var createError$2 = function createError(message, config, code, request, response) { - var error = new Error(message); - return enhanceError$1(error, config, code, request, response); - }; - - var createError$1 = createError$2; - /** - * Resolve or reject a Promise based on response status. - * - * @param {Function} resolve A function that resolves the promise. - * @param {Function} reject A function that rejects the promise. - * @param {object} response The response. - */ - - var settle$1 = function settle(resolve, reject, response) { - var validateStatus = response.config.validateStatus; - - if (!response.status || !validateStatus || validateStatus(response.status)) { - resolve(response); - } else { - reject(createError$1('Request failed with status code ' + response.status, response.config, null, response.request, response)); - } - }; - - var utils$9 = utils$d; - var cookies$1 = utils$9.isStandardBrowserEnv() ? // Standard browser envs support document.cookie - function standardBrowserEnv() { - return { - write: function write(name, value, expires, path, domain, secure) { - var cookie = []; - cookie.push(name + '=' + encodeURIComponent(value)); - - if (utils$9.isNumber(expires)) { - cookie.push('expires=' + new Date(expires).toGMTString()); - } - - if (utils$9.isString(path)) { - cookie.push('path=' + path); - } - - if (utils$9.isString(domain)) { - cookie.push('domain=' + domain); - } - - if (secure === true) { - cookie.push('secure'); - } - - document.cookie = cookie.join('; '); - }, - read: function read(name) { - var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); - return match ? decodeURIComponent(match[3]) : null; - }, - remove: function remove(name) { - this.write(name, '', Date.now() - 86400000); - } - }; - }() : // Non standard browser env (web workers, react-native) lack needed support. - function nonStandardBrowserEnv() { - return { - write: function write() {}, - read: function read() { - return null; - }, - remove: function remove() {} - }; - }(); - - /** - * Determines whether the specified URL is absolute - * - * @param {string} url The URL to test - * @returns {boolean} True if the specified URL is absolute, otherwise false - */ - - - var isAbsoluteURL$1 = function isAbsoluteURL(url) { - // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). - // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed - // by any combination of letters, digits, plus, period, or hyphen. - return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); - }; - - /** - * Creates a new URL by combining the specified URLs - * - * @param {string} baseURL The base URL - * @param {string} relativeURL The relative URL - * @returns {string} The combined URL - */ - - - var combineURLs$1 = function combineURLs(baseURL, relativeURL) { - return relativeURL ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') : baseURL; - }; - - var isAbsoluteURL = isAbsoluteURL$1; - var combineURLs = combineURLs$1; - /** - * Creates a new URL by combining the baseURL with the requestedURL, - * only when the requestedURL is not already an absolute URL. - * If the requestURL is absolute, this function returns the requestedURL untouched. - * - * @param {string} baseURL The base URL - * @param {string} requestedURL Absolute or relative URL to combine - * @returns {string} The combined full path - */ - - var buildFullPath$1 = function buildFullPath(baseURL, requestedURL) { - if (baseURL && !isAbsoluteURL(requestedURL)) { - return combineURLs(baseURL, requestedURL); - } - - return requestedURL; - }; - - var utils$8 = utils$d; // Headers whose duplicates are ignored by node - // c.f. https://nodejs.org/api/http.html#http_message_headers - - var ignoreDuplicateOf = ['age', 'authorization', 'content-length', 'content-type', 'etag', 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', 'last-modified', 'location', 'max-forwards', 'proxy-authorization', 'referer', 'retry-after', 'user-agent']; - /** - * Parse headers into an object - * - * ``` - * Date: Wed, 27 Aug 2014 08:58:49 GMT - * Content-Type: application/json - * Connection: keep-alive - * Transfer-Encoding: chunked - * ``` - * - * @param {String} headers Headers needing to be parsed - * @returns {Object} Headers parsed into an object - */ - - var parseHeaders$1 = function parseHeaders(headers) { - var parsed = {}; - var key; - var val; - var i; - - if (!headers) { - return parsed; - } - - utils$8.forEach(headers.split('\n'), function parser(line) { - i = line.indexOf(':'); - key = utils$8.trim(line.substr(0, i)).toLowerCase(); - val = utils$8.trim(line.substr(i + 1)); - - if (key) { - if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { - return; - } - - if (key === 'set-cookie') { - parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); - } else { - parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; - } - } - }); - return parsed; - }; - - var utils$7 = utils$d; - var isURLSameOrigin$1 = utils$7.isStandardBrowserEnv() ? // Standard browser envs have full support of the APIs needed to test - // whether the request URL is of the same origin as current location. - function standardBrowserEnv() { - var msie = /(msie|trident)/i.test(navigator.userAgent); - var urlParsingNode = document.createElement('a'); - var originURL; - /** - * Parse a URL to discover it's components - * - * @param {String} url The URL to be parsed - * @returns {Object} - */ - - function resolveURL(url) { - var href = url; - - if (msie) { - // IE needs attribute set twice to normalize properties - urlParsingNode.setAttribute('href', href); - href = urlParsingNode.href; - } - - urlParsingNode.setAttribute('href', href); // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils - - return { - href: urlParsingNode.href, - protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', - host: urlParsingNode.host, - search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', - hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', - hostname: urlParsingNode.hostname, - port: urlParsingNode.port, - pathname: urlParsingNode.pathname.charAt(0) === '/' ? urlParsingNode.pathname : '/' + urlParsingNode.pathname - }; - } - - originURL = resolveURL(window.location.href); - /** - * Determine if a URL shares the same origin as the current location - * - * @param {String} requestURL The URL to test - * @returns {boolean} True if URL shares the same origin, otherwise false - */ - - return function isURLSameOrigin(requestURL) { - var parsed = utils$7.isString(requestURL) ? resolveURL(requestURL) : requestURL; - return parsed.protocol === originURL.protocol && parsed.host === originURL.host; - }; - }() : // Non standard browser envs (web workers, react-native) lack needed support. - function nonStandardBrowserEnv() { - return function isURLSameOrigin() { - return true; - }; - }(); - - /** - * A `Cancel` is an object that is thrown when an operation is canceled. - * - * @class - * @param {string=} message The message. - */ - - - function Cancel$3(message) { - this.message = message; - } - - Cancel$3.prototype.toString = function toString() { - return 'Cancel' + (this.message ? ': ' + this.message : ''); - }; - - Cancel$3.prototype.__CANCEL__ = true; - var Cancel_1 = Cancel$3; - - var utils$6 = utils$d; - var settle = settle$1; - var cookies = cookies$1; - var buildURL$1 = buildURL$2; - var buildFullPath = buildFullPath$1; - var parseHeaders = parseHeaders$1; - var isURLSameOrigin = isURLSameOrigin$1; - var createError = createError$2; - var defaults$4 = defaults_1; - var Cancel$2 = Cancel_1; - - var xhr = function xhrAdapter(config) { - return new Promise(function dispatchXhrRequest(resolve, reject) { - var requestData = config.data; - var requestHeaders = config.headers; - var responseType = config.responseType; - var onCanceled; - - function done() { - if (config.cancelToken) { - config.cancelToken.unsubscribe(onCanceled); - } - - if (config.signal) { - config.signal.removeEventListener('abort', onCanceled); - } - } - - if (utils$6.isFormData(requestData)) { - delete requestHeaders['Content-Type']; // Let the browser set it - } - - var request = new XMLHttpRequest(); // HTTP basic authentication - - if (config.auth) { - var username = config.auth.username || ''; - var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; - requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); - } - - var fullPath = buildFullPath(config.baseURL, config.url); - request.open(config.method.toUpperCase(), buildURL$1(fullPath, config.params, config.paramsSerializer), true); // Set the request timeout in MS - - request.timeout = config.timeout; - - function onloadend() { - if (!request) { - return; - } // Prepare the response - - - var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; - var responseData = !responseType || responseType === 'text' || responseType === 'json' ? request.responseText : request.response; - var response = { - data: responseData, - status: request.status, - statusText: request.statusText, - headers: responseHeaders, - config: config, - request: request - }; - settle(function _resolve(value) { - resolve(value); - done(); - }, function _reject(err) { - reject(err); - done(); - }, response); // Clean up request - - request = null; - } - - if ('onloadend' in request) { - // Use onloadend if available - request.onloadend = onloadend; - } else { - // Listen for ready state to emulate onloadend - request.onreadystatechange = function handleLoad() { - if (!request || request.readyState !== 4) { - return; - } // The request errored out and we didn't get a response, this will be - // handled by onerror instead - // With one exception: request that using file: protocol, most browsers - // will return status as 0 even though it's a successful request - - - if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { - return; - } // readystate handler is calling before onerror or ontimeout handlers, - // so we should call onloadend on the next 'tick' - - - setTimeout(onloadend); - }; - } // Handle browser request cancellation (as opposed to a manual cancellation) - - - request.onabort = function handleAbort() { - if (!request) { - return; - } - - reject(createError('Request aborted', config, 'ECONNABORTED', request)); // Clean up request - - request = null; - }; // Handle low level network errors - - - request.onerror = function handleError() { - // Real errors are hidden from us by the browser - // onerror should only fire if it's a network error - reject(createError('Network Error', config, null, request)); // Clean up request - - request = null; - }; // Handle timeout - - - request.ontimeout = function handleTimeout() { - var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded'; - var transitional = config.transitional || defaults$4.transitional; - - if (config.timeoutErrorMessage) { - timeoutErrorMessage = config.timeoutErrorMessage; - } - - reject(createError(timeoutErrorMessage, config, transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED', request)); // Clean up request - - request = null; - }; // Add xsrf header - // This is only done if running in a standard browser environment. - // Specifically not if we're in a web worker, or react-native. - - - if (utils$6.isStandardBrowserEnv()) { - // Add xsrf header - var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? cookies.read(config.xsrfCookieName) : undefined; - - if (xsrfValue) { - requestHeaders[config.xsrfHeaderName] = xsrfValue; - } - } // Add headers to the request - - - if ('setRequestHeader' in request) { - utils$6.forEach(requestHeaders, function setRequestHeader(val, key) { - if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { - // Remove Content-Type if data is undefined - delete requestHeaders[key]; - } else { - // Otherwise add header to the request - request.setRequestHeader(key, val); - } - }); - } // Add withCredentials to request if needed - - - if (!utils$6.isUndefined(config.withCredentials)) { - request.withCredentials = !!config.withCredentials; - } // Add responseType to request if needed - - - if (responseType && responseType !== 'json') { - request.responseType = config.responseType; - } // Handle progress if needed - - - if (typeof config.onDownloadProgress === 'function') { - request.addEventListener('progress', config.onDownloadProgress); - } // Not all browsers support upload events - - - if (typeof config.onUploadProgress === 'function' && request.upload) { - request.upload.addEventListener('progress', config.onUploadProgress); - } - - if (config.cancelToken || config.signal) { - // Handle cancellation - // eslint-disable-next-line func-names - onCanceled = function onCanceled(cancel) { - if (!request) { - return; - } - - reject(!cancel || cancel && cancel.type ? new Cancel$2('canceled') : cancel); - request.abort(); - request = null; - }; - - config.cancelToken && config.cancelToken.subscribe(onCanceled); - - if (config.signal) { - config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled); - } - } - - if (!requestData) { - requestData = null; - } // Send the request - - - request.send(requestData); - }); - }; - - var utils$5 = utils$d; - var normalizeHeaderName = normalizeHeaderName$1; - var enhanceError = enhanceError$2; - var DEFAULT_CONTENT_TYPE = { - 'Content-Type': 'application/x-www-form-urlencoded' - }; - - function setContentTypeIfUnset(headers, value) { - if (!utils$5.isUndefined(headers) && utils$5.isUndefined(headers['Content-Type'])) { - headers['Content-Type'] = value; - } - } - - function getDefaultAdapter() { - var adapter; - - if (typeof XMLHttpRequest !== 'undefined') { - // For browsers use XHR adapter - adapter = xhr; - } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { - // For node use HTTP adapter - adapter = xhr; - } - - return adapter; - } - - function stringifySafely(rawValue, parser, encoder) { - if (utils$5.isString(rawValue)) { - try { - (parser || JSON.parse)(rawValue); - return utils$5.trim(rawValue); - } catch (e) { - if (e.name !== 'SyntaxError') { - throw e; - } - } - } - - return (encoder || JSON.stringify)(rawValue); - } - - var defaults$3 = { - transitional: { - silentJSONParsing: true, - forcedJSONParsing: true, - clarifyTimeoutError: false - }, - adapter: getDefaultAdapter(), - transformRequest: [function transformRequest(data, headers) { - normalizeHeaderName(headers, 'Accept'); - normalizeHeaderName(headers, 'Content-Type'); - - if (utils$5.isFormData(data) || utils$5.isArrayBuffer(data) || utils$5.isBuffer(data) || utils$5.isStream(data) || utils$5.isFile(data) || utils$5.isBlob(data)) { - return data; - } - - if (utils$5.isArrayBufferView(data)) { - return data.buffer; - } - - if (utils$5.isURLSearchParams(data)) { - setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); - return data.toString(); - } - - if (utils$5.isObject(data) || headers && headers['Content-Type'] === 'application/json') { - setContentTypeIfUnset(headers, 'application/json'); - return stringifySafely(data); - } - - return data; - }], - transformResponse: [function transformResponse(data) { - var transitional = this.transitional || defaults$3.transitional; - var silentJSONParsing = transitional && transitional.silentJSONParsing; - var forcedJSONParsing = transitional && transitional.forcedJSONParsing; - var strictJSONParsing = !silentJSONParsing && this.responseType === 'json'; - - if (strictJSONParsing || forcedJSONParsing && utils$5.isString(data) && data.length) { - try { - return JSON.parse(data); - } catch (e) { - if (strictJSONParsing) { - if (e.name === 'SyntaxError') { - throw enhanceError(e, this, 'E_JSON_PARSE'); - } - - throw e; - } - } - } - - return data; - }], - - /** - * A timeout in milliseconds to abort a request. If set to 0 (default) a - * timeout is not created. - */ - timeout: 0, - xsrfCookieName: 'XSRF-TOKEN', - xsrfHeaderName: 'X-XSRF-TOKEN', - maxContentLength: -1, - maxBodyLength: -1, - validateStatus: function validateStatus(status) { - return status >= 200 && status < 300; - }, - headers: { - common: { - 'Accept': 'application/json, text/plain, */*' - } - } - }; - utils$5.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { - defaults$3.headers[method] = {}; - }); - utils$5.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { - defaults$3.headers[method] = utils$5.merge(DEFAULT_CONTENT_TYPE); - }); - var defaults_1 = defaults$3; - - var utils$4 = utils$d; - var defaults$2 = defaults_1; - /** - * Transform the data for a request or a response - * - * @param {Object|String} data The data to be transformed - * @param {Array} headers The headers for the request or response - * @param {Array|Function} fns A single function or Array of functions - * @returns {*} The resulting transformed data - */ - - var transformData$1 = function transformData(data, headers, fns) { - var context = this || defaults$2; - /*eslint no-param-reassign:0*/ - - utils$4.forEach(fns, function transform(fn) { - data = fn.call(context, data, headers); - }); - return data; - }; - - var isCancel$1 = function isCancel(value) { - return !!(value && value.__CANCEL__); - }; - - var utils$3 = utils$d; - var transformData = transformData$1; - var isCancel = isCancel$1; - var defaults$1 = defaults_1; - var Cancel$1 = Cancel_1; - /** - * Throws a `Cancel` if cancellation has been requested. - */ - - function throwIfCancellationRequested(config) { - if (config.cancelToken) { - config.cancelToken.throwIfRequested(); - } - - if (config.signal && config.signal.aborted) { - throw new Cancel$1('canceled'); - } - } - /** - * Dispatch a request to the server using the configured adapter. - * - * @param {object} config The config that is to be used for the request - * @returns {Promise} The Promise to be fulfilled - */ - - - var dispatchRequest$1 = function dispatchRequest(config) { - throwIfCancellationRequested(config); // Ensure headers exist - - config.headers = config.headers || {}; // Transform request data - - config.data = transformData.call(config, config.data, config.headers, config.transformRequest); // Flatten headers - - config.headers = utils$3.merge(config.headers.common || {}, config.headers[config.method] || {}, config.headers); - utils$3.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], function cleanHeaderConfig(method) { - delete config.headers[method]; - }); - var adapter = config.adapter || defaults$1.adapter; - return adapter(config).then(function onAdapterResolution(response) { - throwIfCancellationRequested(config); // Transform response data - - response.data = transformData.call(config, response.data, response.headers, config.transformResponse); - return response; - }, function onAdapterRejection(reason) { - if (!isCancel(reason)) { - throwIfCancellationRequested(config); // Transform response data - - if (reason && reason.response) { - reason.response.data = transformData.call(config, reason.response.data, reason.response.headers, config.transformResponse); - } - } - - return Promise.reject(reason); - }); - }; - - var utils$2 = utils$d; - /** - * Config-specific merge-function which creates a new config-object - * by merging two configuration objects together. - * - * @param {Object} config1 - * @param {Object} config2 - * @returns {Object} New object resulting from merging config2 to config1 - */ - - var mergeConfig$2 = function mergeConfig(config1, config2) { - // eslint-disable-next-line no-param-reassign - config2 = config2 || {}; - var config = {}; - - function getMergedValue(target, source) { - if (utils$2.isPlainObject(target) && utils$2.isPlainObject(source)) { - return utils$2.merge(target, source); - } else if (utils$2.isPlainObject(source)) { - return utils$2.merge({}, source); - } else if (utils$2.isArray(source)) { - return source.slice(); - } - - return source; - } // eslint-disable-next-line consistent-return - - - function mergeDeepProperties(prop) { - if (!utils$2.isUndefined(config2[prop])) { - return getMergedValue(config1[prop], config2[prop]); - } else if (!utils$2.isUndefined(config1[prop])) { - return getMergedValue(undefined, config1[prop]); - } - } // eslint-disable-next-line consistent-return - - - function valueFromConfig2(prop) { - if (!utils$2.isUndefined(config2[prop])) { - return getMergedValue(undefined, config2[prop]); - } - } // eslint-disable-next-line consistent-return - - - function defaultToConfig2(prop) { - if (!utils$2.isUndefined(config2[prop])) { - return getMergedValue(undefined, config2[prop]); - } else if (!utils$2.isUndefined(config1[prop])) { - return getMergedValue(undefined, config1[prop]); - } - } // eslint-disable-next-line consistent-return - - - function mergeDirectKeys(prop) { - if (prop in config2) { - return getMergedValue(config1[prop], config2[prop]); - } else if (prop in config1) { - return getMergedValue(undefined, config1[prop]); - } - } - - var mergeMap = { - 'url': valueFromConfig2, - 'method': valueFromConfig2, - 'data': valueFromConfig2, - 'baseURL': defaultToConfig2, - 'transformRequest': defaultToConfig2, - 'transformResponse': defaultToConfig2, - 'paramsSerializer': defaultToConfig2, - 'timeout': defaultToConfig2, - 'timeoutMessage': defaultToConfig2, - 'withCredentials': defaultToConfig2, - 'adapter': defaultToConfig2, - 'responseType': defaultToConfig2, - 'xsrfCookieName': defaultToConfig2, - 'xsrfHeaderName': defaultToConfig2, - 'onUploadProgress': defaultToConfig2, - 'onDownloadProgress': defaultToConfig2, - 'decompress': defaultToConfig2, - 'maxContentLength': defaultToConfig2, - 'maxBodyLength': defaultToConfig2, - 'transport': defaultToConfig2, - 'httpAgent': defaultToConfig2, - 'httpsAgent': defaultToConfig2, - 'cancelToken': defaultToConfig2, - 'socketPath': defaultToConfig2, - 'responseEncoding': defaultToConfig2, - 'validateStatus': mergeDirectKeys - }; - utils$2.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) { - var merge = mergeMap[prop] || mergeDeepProperties; - var configValue = merge(prop); - utils$2.isUndefined(configValue) && merge !== mergeDirectKeys || (config[prop] = configValue); - }); - return config; - }; - - var data = { - "version": "0.24.0" - }; - - var VERSION = data.version; - var validators$1 = {}; // eslint-disable-next-line func-names - - ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function (type, i) { - validators$1[type] = function validator(thing) { - return _typeof(thing) === type || 'a' + (i < 1 ? 'n ' : ' ') + type; - }; - }); - var deprecatedWarnings = {}; - /** - * Transitional option validator - * @param {function|boolean?} validator - set to false if the transitional option has been removed - * @param {string?} version - deprecated version / removed since version - * @param {string?} message - some message with additional info - * @returns {function} - */ - - validators$1.transitional = function transitional(validator, version, message) { - function formatMessage(opt, desc) { - return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); - } // eslint-disable-next-line func-names - - - return function (value, opt, opts) { - if (validator === false) { - throw new Error(formatMessage(opt, ' has been removed' + (version ? ' in ' + version : ''))); - } - - if (version && !deprecatedWarnings[opt]) { - deprecatedWarnings[opt] = true; // eslint-disable-next-line no-console - - console.warn(formatMessage(opt, ' has been deprecated since v' + version + ' and will be removed in the near future')); - } - - return validator ? validator(value, opt, opts) : true; - }; - }; - /** - * Assert object's properties type - * @param {object} options - * @param {object} schema - * @param {boolean?} allowUnknown - */ - - - function assertOptions(options, schema, allowUnknown) { - if (_typeof(options) !== 'object') { - throw new TypeError('options must be an object'); - } - - var keys = Object.keys(options); - var i = keys.length; - - while (i-- > 0) { - var opt = keys[i]; - var validator = schema[opt]; - - if (validator) { - var value = options[opt]; - var result = value === undefined || validator(value, opt, options); - - if (result !== true) { - throw new TypeError('option ' + opt + ' must be ' + result); - } - - continue; - } - - if (allowUnknown !== true) { - throw Error('Unknown option ' + opt); - } - } - } - - var validator$1 = { - assertOptions: assertOptions, - validators: validators$1 - }; - - var utils$1 = utils$d; - var buildURL = buildURL$2; - var InterceptorManager = InterceptorManager_1; - var dispatchRequest = dispatchRequest$1; - var mergeConfig$1 = mergeConfig$2; - var validator = validator$1; - var validators = validator.validators; - /** - * Create a new instance of Axios - * - * @param {Object} instanceConfig The default config for the instance - */ - - function Axios$1(instanceConfig) { - this.defaults = instanceConfig; - this.interceptors = { - request: new InterceptorManager(), - response: new InterceptorManager() - }; - } - /** - * Dispatch a request - * - * @param {Object} config The config specific for this request (merged with this.defaults) - */ - - - Axios$1.prototype.request = function request(config) { - /*eslint no-param-reassign:0*/ - // Allow for axios('example/url'[, config]) a la fetch API - if (typeof config === 'string') { - config = arguments[1] || {}; - config.url = arguments[0]; - } else { - config = config || {}; - } - - config = mergeConfig$1(this.defaults, config); // Set config.method - - if (config.method) { - config.method = config.method.toLowerCase(); - } else if (this.defaults.method) { - config.method = this.defaults.method.toLowerCase(); - } else { - config.method = 'get'; - } - - var transitional = config.transitional; - - if (transitional !== undefined) { - validator.assertOptions(transitional, { - silentJSONParsing: validators.transitional(validators.boolean), - forcedJSONParsing: validators.transitional(validators.boolean), - clarifyTimeoutError: validators.transitional(validators.boolean) - }, false); - } // filter out skipped interceptors - - - var requestInterceptorChain = []; - var synchronousRequestInterceptors = true; - this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { - if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { - return; - } - - synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; - requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); - }); - var responseInterceptorChain = []; - this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { - responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); - }); - var promise; - - if (!synchronousRequestInterceptors) { - var chain = [dispatchRequest, undefined]; - Array.prototype.unshift.apply(chain, requestInterceptorChain); - chain = chain.concat(responseInterceptorChain); - promise = Promise.resolve(config); - - while (chain.length) { - promise = promise.then(chain.shift(), chain.shift()); - } - - return promise; - } - - var newConfig = config; - - while (requestInterceptorChain.length) { - var onFulfilled = requestInterceptorChain.shift(); - var onRejected = requestInterceptorChain.shift(); - - try { - newConfig = onFulfilled(newConfig); - } catch (error) { - onRejected(error); - break; - } - } - - try { - promise = dispatchRequest(newConfig); - } catch (error) { - return Promise.reject(error); - } - - while (responseInterceptorChain.length) { - promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift()); - } - - return promise; - }; - - Axios$1.prototype.getUri = function getUri(config) { - config = mergeConfig$1(this.defaults, config); - return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, ''); - }; // Provide aliases for supported request methods - - - utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { - /*eslint func-names:0*/ - Axios$1.prototype[method] = function (url, config) { - return this.request(mergeConfig$1(config || {}, { - method: method, - url: url, - data: (config || {}).data - })); - }; - }); - utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { - /*eslint func-names:0*/ - Axios$1.prototype[method] = function (url, data, config) { - return this.request(mergeConfig$1(config || {}, { - method: method, - url: url, - data: data - })); - }; - }); - var Axios_1 = Axios$1; - - var Cancel = Cancel_1; - /** - * A `CancelToken` is an object that can be used to request cancellation of an operation. - * - * @class - * @param {Function} executor The executor function. - */ - - function CancelToken(executor) { - if (typeof executor !== 'function') { - throw new TypeError('executor must be a function.'); - } - - var resolvePromise; - this.promise = new Promise(function promiseExecutor(resolve) { - resolvePromise = resolve; - }); - var token = this; // eslint-disable-next-line func-names - - this.promise.then(function (cancel) { - if (!token._listeners) return; - var i; - var l = token._listeners.length; - - for (i = 0; i < l; i++) { - token._listeners[i](cancel); - } - - token._listeners = null; - }); // eslint-disable-next-line func-names - - this.promise.then = function (onfulfilled) { - var _resolve; // eslint-disable-next-line func-names - - - var promise = new Promise(function (resolve) { - token.subscribe(resolve); - _resolve = resolve; - }).then(onfulfilled); - - promise.cancel = function reject() { - token.unsubscribe(_resolve); - }; - - return promise; - }; - - executor(function cancel(message) { - if (token.reason) { - // Cancellation has already been requested - return; - } - - token.reason = new Cancel(message); - resolvePromise(token.reason); - }); - } - /** - * Throws a `Cancel` if cancellation has been requested. - */ - - - CancelToken.prototype.throwIfRequested = function throwIfRequested() { - if (this.reason) { - throw this.reason; - } - }; - /** - * Subscribe to the cancel signal - */ - - - CancelToken.prototype.subscribe = function subscribe(listener) { - if (this.reason) { - listener(this.reason); - return; - } - - if (this._listeners) { - this._listeners.push(listener); - } else { - this._listeners = [listener]; - } - }; - /** - * Unsubscribe from the cancel signal - */ - - - CancelToken.prototype.unsubscribe = function unsubscribe(listener) { - if (!this._listeners) { - return; - } - - var index = this._listeners.indexOf(listener); - - if (index !== -1) { - this._listeners.splice(index, 1); - } - }; - /** - * Returns an object that contains a new `CancelToken` and a function that, when called, - * cancels the `CancelToken`. - */ - - - CancelToken.source = function source() { - var cancel; - var token = new CancelToken(function executor(c) { - cancel = c; - }); - return { - token: token, - cancel: cancel - }; - }; - - var CancelToken_1 = CancelToken; - - /** - * Syntactic sugar for invoking a function and expanding an array for arguments. - * - * Common use case would be to use `Function.prototype.apply`. - * - * ```js - * function f(x, y, z) {} - * var args = [1, 2, 3]; - * f.apply(null, args); - * ``` - * - * With `spread` this example can be re-written. - * - * ```js - * spread(function(x, y, z) {})([1, 2, 3]); - * ``` - * - * @param {Function} callback - * @returns {Function} - */ - - - var spread = function spread(callback) { - return function wrap(arr) { - return callback.apply(null, arr); - }; - }; - - /** - * Determines whether the payload is an error thrown by Axios - * - * @param {*} payload The value to test - * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false - */ - - - var isAxiosError = function isAxiosError(payload) { - return _typeof(payload) === 'object' && payload.isAxiosError === true; - }; - - var utils = utils$d; - var bind$4 = bind$6; - var Axios = Axios_1; - var mergeConfig = mergeConfig$2; - var defaults = defaults_1; - /** - * Create an instance of Axios - * - * @param {Object} defaultConfig The default config for the instance - * @return {Axios} A new instance of Axios - */ - - function createInstance(defaultConfig) { - var context = new Axios(defaultConfig); - var instance = bind$4(Axios.prototype.request, context); // Copy axios.prototype to instance - - utils.extend(instance, Axios.prototype, context); // Copy context to instance - - utils.extend(instance, context); // Factory for creating new instances - - instance.create = function create(instanceConfig) { - return createInstance(mergeConfig(defaultConfig, instanceConfig)); - }; - - return instance; - } // Create the default instance to be exported - - - var axios = createInstance(defaults); // Expose Axios class to allow class inheritance - - axios.Axios = Axios; // Expose Cancel & CancelToken - - axios.Cancel = Cancel_1; - axios.CancelToken = CancelToken_1; - axios.isCancel = isCancel$1; - axios.VERSION = data.version; // Expose all/spread - - axios.all = function all(promises) { - return Promise.all(promises); - }; - - axios.spread = spread; // Expose isAxiosError - - axios.isAxiosError = isAxiosError; - axios$1.exports = axios; // Allow use of default import syntax in TypeScript - - axios$1.exports.default = axios; - - function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - - function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - var hoistCountry = function hoistCountry(config, outputFields, linesIdentifier) { - if (config.hoistCountry !== true) return; - if (!outputFields.country) return; - if (!outputFields.line_1) return; - var elem = getParent$1(outputFields.country, "div", function (e) { - return e.classList.contains("field"); - }); - if (!elem) return; - var target = getLinesContainer(outputFields, linesIdentifier); - if (!target) return; - - if (!elem.hasAttribute("country-hoist")) { - elem.setAttribute("country-hoist", "true"); - insertBefore({ - elem: elem, - target: target - }); - } - }; - var getLinesContainer = function getLinesContainer(_ref, linesIdentifier) { - var line_1 = _ref.line_1; - if (line_1 === null) return null; - var parentScope = linesIdentifier ? linesIdentifier.parentScope : "fieldset"; - var parentTest = linesIdentifier ? linesIdentifier.parentTest : function (e) { - return e.classList.contains("field"); - }; - return getParent$1(line_1, parentScope, parentTest); - }; - var SUPPORTED_COUNTRIES = ["England", "Scotland", "Wales", "Northern Ireland", "Channel Islands", "Isle of Man", "United Kingdom", "Jersey", "Guernsey", "GB", "IM", "JE", "GG"]; - var EXTENDED_COUNTRIES = ["United States of America", "US"]; - var supportedCountries = function supportedCountries(extended) { - //@ts-expect-error - if (extended) return SUPPORTED_COUNTRIES.concat(EXTENDED_COUNTRIES); - return SUPPORTED_COUNTRIES; - }; - var countryIsSupported = function countryIsSupported(e) { - var extended = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - var country = e.value; - return supportedCountries(extended).reduce(function (prev, supported) { - if (country === supported) return true; - return prev; - }, false); - }; - - var NOOP = function NOOP() {}; - - var watchCountry = function watchCountry(_ref2, activate, deactivate) { - var country = _ref2.country; - var extended = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; - if (!country) return NOOP; - - var checkCountry = function checkCountry(target) { - if (countryIsSupported(target, extended)) return activate(); - deactivate(); - }; - - country.addEventListener("change", function (event) { - checkCountry(event.target); - }); - return checkCountry(country); - }; - - var getFields = function getFields(outputFields, scope) { - var result = {}; - Object.keys(outputFields).forEach(function (key) { - //@ts-expect-error - result[key] = toElem$1(outputFields[key], scope); - }); - return result; - }; - var setupAutocomplete = /*#__PURE__*/function () { - var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(config, outputFields) { - var options, - linesIdentifier, - _args = arguments; - return _regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - options = _args.length > 2 && _args[2] !== undefined ? _args[2] : {}; - linesIdentifier = _args.length > 3 ? _args[3] : undefined; - console.log(config, outputFields, options); - - if (!(config.autocomplete !== true)) { - _context.next = 5; - break; - } - - return _context.abrupt("return"); - - case 5: - if (!(outputFields.line_1 === undefined)) { - _context.next = 7; - break; - } - - return _context.abrupt("return"); - - case 7: - _context.next = 9; - return AddressFinder.watch(_objectSpread({ - apiKey: config.apiKey, - checkKey: true, - onLoaded: function onLoaded() { - var _this2 = this; - - //@ts-expect-error - this.options.outputFields = getFields(outputFields, this.scope); //@ts-expect-error - - //@ts-expect-error - hoistCountry(config, this.options.outputFields, linesIdentifier); - watchCountry(this.options.outputFields, function () { - return _this2.attach(); - }, function () { - return _this2.detach(); - }, true); - }, - outputFields: outputFields - }, config.autocompleteOverride), options); - - case 9: - case "end": - return _context.stop(); - } - } - }, _callee); - })); - - return function setupAutocomplete(_x, _x2) { - return _ref3.apply(this, arguments); - }; - }(); - var includes = function includes(haystack, needle) { - return haystack.indexOf(needle) !== -1; - }; - - var billing = { - line_1: '[name="order[billing_address][street][0]"]', - line_2: '[name="order[billing_address][street][1]"]', - line_3: '[name="order[billing_address][street][2]"]', - postcode: '[name="order[billing_address][postcode]"]', - post_town: '[name="order[billing_address][city]"]', - organisation_name: '[name="order[billing_address][company]"]', - county: '[name="order[billing_address][region]"]', - country: '[name="order[billing_address][country_id]"]' - }; - var shipping = { - line_1: '[name="order[shipping_address][street][0]"]', - line_2: '[name="order[shipping_address][street][1]"]', - line_3: '[name="order[shipping_address][street][2]"]', - postcode: '[name="order[shipping_address][postcode]"]', - post_town: '[name="order[shipping_address][city]"]', - organisation_name: '[name="order[shipping_address][company]"]', - county: '[name="order[shipping_address][region]"]', - country: '[name="order[shipping_address][country_id]"]' - }; - var selectorList = [billing, shipping]; - var parentScope$2 = "fieldset"; - var bind$3 = function bind(config) { - selectorList.forEach(function (selectors) { - setupAutocomplete(config, selectors, { - pageTest: pageTest$3, - getScope: function getScope(anchor) { - return getParent$1(anchor, parentScope$2); - } - }); - }); - }; - - var pageTest$3 = function pageTest() { - return includes(window.location.pathname, "/sales"); - }; - - var selectors = { - line_1: '[name="street[0]"]', - line_2: '[name="street[1]"]', - line_3: '[name="street[2]"]', - postcode: '[name="postcode"]', - post_town: '[name="city"]', - organisation_name: '[name="company"]', - county: '[name="region"]', - country: '[name="country_id"]' - }; - - var bind$2 = function bind(config) { - setupAutocomplete(config, selectors, { - pageTest: pageTest$2 - }); - }; - - var pageTest$2 = function pageTest() { - return includes(window.location.pathname, "/sales/order"); - }; - - var parentScope$1 = "fieldset"; - - var parentTest$1 = function parentTest(e) { - return e.className === "admin__fieldset"; - }; - - var pageTest$1 = function pageTest() { - return includes(window.location.pathname, "/customer"); - }; - - var bind$1 = function bind(config) { - setupAutocomplete(config, selectors, { - pageTest: pageTest$1, - getScope: function getScope(anchor) { - return getParent$1(anchor, parentScope$1, parentTest$1); - } - }); - }; - - var parentScope = "fieldset"; - - var parentTest = function parentTest(e) { - return e.className === "admin__fieldset"; - }; - - var pageTest = function pageTest() { - return true; - }; - - var bind = function bind(config) { - var fields = config.customFields || []; - fields.forEach(function (selectors) { - setupAutocomplete(config, selectors, { - pageTest: pageTest, - getScope: function getScope(anchor) { - return getParent$1(anchor, parentScope, parentTest); - } - }); - }); - }; - - window.idpcStart = function () { - return [bind$3, bind$1, bind$2, bind].forEach(function (bind) { - var conf = config(); - if (conf) bind(conf); - }); - }; - -})(); +!function(){"use strict";function t(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}var e=function(){return!0},n=function(t,n){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e,o=t,i=n.toUpperCase();"HTML"!==o.tagName;){if(o.tagName===i&&r(o))return o;if(null===o.parentNode)return null;o=o.parentNode}return null};function r(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function o(e){for(var n=1;nt.length)&&(e=t.length);for(var n=0,r=new Array(e);n=0;--r){var o=this.tryEntries[r],i=o.completion;if("root"===o.tryLoc)return n("end");if(o.tryLoc<=this.prev){var s=j.call(o,"catchLoc"),a=j.call(o,"finallyLoc");if(s&&a){if(this.prev=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&j.call(r,"finallyLoc")&&this.prev=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),Y(n),D}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var o=r.arg;Y(n)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,n){return this.delegate={iterator:X(t),resultName:e,nextLoc:n},"next"===this.method&&(this.arg=S),D}};var Z={wrap:T,isGeneratorFunction:z,AsyncIterator:K,mark:function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,F):(t.__proto__=F,_ in t||(t[_]="GeneratorFunction")),t.prototype=Object.create(H),t},awrap:function(t){return{__await:t}},async:function(t,e,n,r,o){void 0===o&&(o=Promise);var i=new K(T(t,e,n,r),o);return z(e)?i:i.next().then((function(t){return t.done?t.value:i.next()}))},keys:function(t){var e=[];for(var n in t)e.push(n);return e.reverse(),function n(){for(;e.length;){var r=e.pop();if(r in t)return n.value=r,n.done=!1,n}return n.done=!0,n}},values:X};function tt(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function et(t,e){for(var n=0;n=e||n<0||f&&t-c>=i}function v(){var t=Rt();if(y(t))return m(t);a=setTimeout(v,function(t){var n=e-(t-u);return f?Bt(n,i-(t-c)):n}(t))}function m(t){return a=void 0,p&&r?d(t):(r=o=void 0,s)}function g(){var t=Rt(),n=y(t);if(r=arguments,o=this,u=t,n){if(void 0===a)return h(u);if(f)return clearTimeout(a),a=setTimeout(v,e),d(u)}return void 0===a&&(a=setTimeout(v,e)),s}return e=Ut(e)||0,Lt(n)&&(l=!!n.leading,i=(f="maxWait"in n)?Dt(Ut(n.maxWait)||0,e):i,p="trailing"in n?!!n.trailing:p),g.cancel=function(){void 0!==a&&clearTimeout(a),c=0,r=u=o=a=void 0},g.flush=function(){return void 0===a?s:m(Rt())},g},Ft=function(t,e){return t.id=e,t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.setAttribute("aria-atomic","true"),t};function It(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function Mt(e){for(var n=1;n0&&(e[n]=o),e}),{})},Wt=function(t){return"string"==typeof t},Vt=function(t){var e=[];return function(t){return Array.isArray(t)}(t)?(t.forEach((function(t){Yt(t)&&e.push(t.toString()),Wt(t)&&e.push(t)})),e.join(",")):Yt(t)?t.toString():Wt(t)?t:""},Yt=function(t){return"number"==typeof t},$t=function(t,e){var n=t.timeout;return Yt(n)?n:e.config.timeout},Xt=function(t,e){var n=t.header,r=void 0===n?{}:n;return zt(zt({},e.config.header),Kt(r))};function Qt(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function Zt(t,e){return Zt=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t},Zt(t,e)}function te(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&Zt(t,e)}function ee(t,e){if(e&&("object"===O(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return Qt(t)}function ne(t){return ne=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},ne(t)}function re(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function oe(t,e,n){return oe=re()?Reflect.construct:function(t,e,n){var r=[null];r.push.apply(r,e);var o=new(Function.bind.apply(t,r));return n&&Zt(o,n.prototype),o},oe.apply(null,arguments)}function ie(t){var e="function"==typeof Map?new Map:void 0;return ie=function(t){if(null===t||(n=t,-1===Function.toString.call(n).indexOf("[native code]")))return t;var n;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,r)}function r(){return oe(t,arguments,ne(this).constructor)}return r.prototype=Object.create(t.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),Zt(r,t)},ie(t)}function se(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var n,r=ne(t);if(e){var o=ne(this).constructor;n=Reflect.construct(r,arguments,o)}else n=r.apply(this,arguments);return ee(this,n)}}var ae=function(t){te(n,t);var e=se(n);function n(t){var r;tt(this,n);var o=(this instanceof n?this.constructor:void 0).prototype;(r=e.call(this)).__proto__=o;var i=t.message,s=t.httpStatus,a=t.metadata,u=void 0===a?{}:a;return r.message=i,r.name="Ideal Postcodes Error",r.httpStatus=s,r.metadata=u,Error.captureStackTrace&&Error.captureStackTrace(Qt(r),n),r}return n}(ie(Error)),ue=function(t){te(n,t);var e=se(n);function n(t){var r;return tt(this,n),(r=e.call(this,{httpStatus:t.httpStatus,message:t.body.message})).response=t,r}return n}(ae),ce=function(t){te(n,t);var e=se(n);function n(){return tt(this,n),e.apply(this,arguments)}return n}(ue),le=function(t){te(n,t);var e=se(n);function n(){return tt(this,n),e.apply(this,arguments)}return n}(ue),fe=function(t){te(n,t);var e=se(n);function n(){return tt(this,n),e.apply(this,arguments)}return n}(le),pe=function(t){te(n,t);var e=se(n);function n(){return tt(this,n),e.apply(this,arguments)}return n}(ue),de=function(t){te(n,t);var e=se(n);function n(){return tt(this,n),e.apply(this,arguments)}return n}(pe),he=function(t){te(n,t);var e=se(n);function n(){return tt(this,n),e.apply(this,arguments)}return n}(pe),ye=function(t){te(n,t);var e=se(n);function n(){return tt(this,n),e.apply(this,arguments)}return n}(ue),ve=function(t){te(n,t);var e=se(n);function n(){return tt(this,n),e.apply(this,arguments)}return n}(ye),me=function(t){te(n,t);var e=se(n);function n(){return tt(this,n),e.apply(this,arguments)}return n}(ye),ge=function(t){te(n,t);var e=se(n);function n(){return tt(this,n),e.apply(this,arguments)}return n}(ye),be=function(t){te(n,t);var e=se(n);function n(){return tt(this,n),e.apply(this,arguments)}return n}(ye),we=function(t){te(n,t);var e=se(n);function n(){return tt(this,n),e.apply(this,arguments)}return n}(ue),Oe=function(t){return null!==(e=t)&&"object"===O(e)&&("string"==typeof t.message&&"number"==typeof t.code);var e},Ee=function(t){var e=t.httpStatus,n=t.body;if(!function(t){return!(t<200||t>=300)}(e)){if(Oe(n)){var r=n.code;if(4010===r)return new fe(t);if(4040===r)return new ve(t);if(4042===r)return new me(t);if(4044===r)return new ge(t);if(4046===r)return new be(t);if(4020===r)return new de(t);if(4021===r)return new he(t);if(404===e)return new ye(t);if(400===e)return new ce(t);if(402===e)return new pe(t);if(401===e)return new le(t);if(500===e)return new we(t)}return new ae({httpStatus:e,message:JSON.stringify(n)})}},Se=function(t,e){return[t.client.url(),t.resource,encodeURIComponent(e),t.action].filter((function(t){return void 0!==t})).join("/")},xe=function(t){var e=t.client;return function(n,r){return e.config.agent.http({method:"GET",url:Se(t,n),query:Kt(r.query),header:Xt(r,e),timeout:$t(r,e)}).then((function(t){var e=Ee(t);if(e)throw e;return t}))}},je=function(t){var e=t.client,n=t.timeout,r=t.api_key||t.client.config.api_key,o=t.licensee,i={query:void 0===o?{}:{licensee:o},header:{}};return void 0!==n&&(i.timeout=n),function(t,e,n){return xe({resource:"keys",client:t})(e,n)}(e,r,i).then((function(t){return t.body.result}))},Ce="autocomplete/addresses",Pe=function(t,e){return function(t){var e=t.client,n=t.resource;return function(t){return e.config.agent.http({method:"GET",url:"".concat(e.url(),"/").concat(n),query:Kt(t.query),header:Xt(t,e),timeout:$t(t,e)}).then((function(t){var e=Ee(t);if(e)throw e;return t}))}}({resource:Ce,client:t})(e)},Ae={exports:{}},_e=function(t,e){return function(){for(var n=new Array(arguments.length),r=0;r=0)return;o[e]="set-cookie"===e?(o[e]?o[e]:[]).concat([n]):o[e]?o[e]+", "+n:n}})),o):o},dn=rn,hn=Ve,yn=jn,vn=sn,mn=function(t){return new Promise((function(e,n){var r,o=t.data,i=t.headers,s=t.responseType;function a(){t.cancelToken&&t.cancelToken.unsubscribe(r),t.signal&&t.signal.removeEventListener("abort",r)}an.isFormData(o)&&delete i["Content-Type"];var u=new XMLHttpRequest;if(t.auth){var c=t.auth.username||"",l=t.auth.password?unescape(encodeURIComponent(t.auth.password)):"";i.Authorization="Basic "+btoa(c+":"+l)}var f=fn(t.baseURL,t.url);function p(){if(u){var r="getAllResponseHeaders"in u?pn(u.getAllResponseHeaders()):null,o={data:s&&"text"!==s&&"json"!==s?u.response:u.responseText,status:u.status,statusText:u.statusText,headers:r,config:t,request:u};un((function(t){e(t),a()}),(function(t){n(t),a()}),o),u=null}}if(u.open(t.method.toUpperCase(),ln(f,t.params,t.paramsSerializer),!0),u.timeout=t.timeout,"onloadend"in u?u.onloadend=p:u.onreadystatechange=function(){u&&4===u.readyState&&(0!==u.status||u.responseURL&&0===u.responseURL.indexOf("file:"))&&setTimeout(p)},u.onabort=function(){u&&(n(hn("Request aborted",t,"ECONNABORTED",u)),u=null)},u.onerror=function(){n(hn("Network Error",t,null,u)),u=null},u.ontimeout=function(){var e=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",r=t.transitional||yn.transitional;t.timeoutErrorMessage&&(e=t.timeoutErrorMessage),n(hn(e,t,r.clarifyTimeoutError?"ETIMEDOUT":"ECONNABORTED",u)),u=null},an.isStandardBrowserEnv()){var d=(t.withCredentials||dn(f))&&t.xsrfCookieName?cn.read(t.xsrfCookieName):void 0;d&&(i[t.xsrfHeaderName]=d)}"setRequestHeader"in u&&an.forEach(i,(function(t,e){void 0===o&&"content-type"===e.toLowerCase()?delete i[e]:u.setRequestHeader(e,t)})),an.isUndefined(t.withCredentials)||(u.withCredentials=!!t.withCredentials),s&&"json"!==s&&(u.responseType=t.responseType),"function"==typeof t.onDownloadProgress&&u.addEventListener("progress",t.onDownloadProgress),"function"==typeof t.onUploadProgress&&u.upload&&u.upload.addEventListener("progress",t.onUploadProgress),(t.cancelToken||t.signal)&&(r=function(t){u&&(n(!t||t&&t.type?new vn("canceled"):t),u.abort(),u=null)},t.cancelToken&&t.cancelToken.subscribe(r),t.signal&&(t.signal.aborted?r():t.signal.addEventListener("abort",r))),o||(o=null),u.send(o)}))},gn=qe,bn=function(t,e){ze.forEach(t,(function(n,r){r!==e&&r.toUpperCase()===e.toUpperCase()&&(t[e]=n,delete t[r])}))},wn=Ke,On={"Content-Type":"application/x-www-form-urlencoded"};function En(t,e){!gn.isUndefined(t)&&gn.isUndefined(t["Content-Type"])&&(t["Content-Type"]=e)}var Sn,xn={transitional:{silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},adapter:(("undefined"!=typeof XMLHttpRequest||"undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process))&&(Sn=mn),Sn),transformRequest:[function(t,e){return bn(e,"Accept"),bn(e,"Content-Type"),gn.isFormData(t)||gn.isArrayBuffer(t)||gn.isBuffer(t)||gn.isStream(t)||gn.isFile(t)||gn.isBlob(t)?t:gn.isArrayBufferView(t)?t.buffer:gn.isURLSearchParams(t)?(En(e,"application/x-www-form-urlencoded;charset=utf-8"),t.toString()):gn.isObject(t)||e&&"application/json"===e["Content-Type"]?(En(e,"application/json"),function(t,e,n){if(gn.isString(t))try{return(e||JSON.parse)(t),gn.trim(t)}catch(t){if("SyntaxError"!==t.name)throw t}return(n||JSON.stringify)(t)}(t)):t}],transformResponse:[function(t){var e=this.transitional||xn.transitional,n=e&&e.silentJSONParsing,r=e&&e.forcedJSONParsing,o=!n&&"json"===this.responseType;if(o||r&&gn.isString(t)&&t.length)try{return JSON.parse(t)}catch(t){if(o){if("SyntaxError"===t.name)throw wn(t,this,"E_JSON_PARSE");throw t}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};gn.forEach(["delete","get","head"],(function(t){xn.headers[t]={}})),gn.forEach(["post","put","patch"],(function(t){xn.headers[t]=gn.merge(On)}));var jn=xn,Cn=qe,Pn=jn,An=function(t){return!(!t||!t.__CANCEL__)},_n=qe,Tn=function(t,e,n){var r=this||Pn;return Cn.forEach(n,(function(n){t=n.call(r,t,e)})),t},kn=An,Nn=jn,Ln=sn;function Rn(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new Ln("canceled")}var Un=qe,Dn=function(t,e){e=e||{};var n={};function r(t,e){return Un.isPlainObject(t)&&Un.isPlainObject(e)?Un.merge(t,e):Un.isPlainObject(e)?Un.merge({},e):Un.isArray(e)?e.slice():e}function o(n){return Un.isUndefined(e[n])?Un.isUndefined(t[n])?void 0:r(void 0,t[n]):r(t[n],e[n])}function i(t){if(!Un.isUndefined(e[t]))return r(void 0,e[t])}function s(n){return Un.isUndefined(e[n])?Un.isUndefined(t[n])?void 0:r(void 0,t[n]):r(void 0,e[n])}function a(n){return n in e?r(t[n],e[n]):n in t?r(void 0,t[n]):void 0}var u={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:a};return Un.forEach(Object.keys(t).concat(Object.keys(e)),(function(t){var e=u[t]||o,r=e(t);Un.isUndefined(r)&&e!==a||(n[t]=r)})),n},Bn="0.24.0",qn=Bn,Fn={};["object","boolean","number","function","string","symbol"].forEach((function(t,e){Fn[t]=function(n){return O(n)===t||"a"+(e<1?"n ":" ")+t}}));var In={};Fn.transitional=function(t,e,n){function r(t,e){return"[Axios v"+qn+"] Transitional option '"+t+"'"+e+(n?". "+n:"")}return function(n,o,i){if(!1===t)throw new Error(r(o," has been removed"+(e?" in "+e:"")));return e&&!In[o]&&(In[o]=!0,console.warn(r(o," has been deprecated since v"+e+" and will be removed in the near future"))),!t||t(n,o,i)}};var Mn={assertOptions:function(t,e,n){if("object"!==O(t))throw new TypeError("options must be an object");for(var r=Object.keys(t),o=r.length;o-- >0;){var i=r[o],s=e[i];if(s){var a=t[i],u=void 0===a||s(a,i,t);if(!0!==u)throw new TypeError("option "+i+" must be "+u)}else if(!0!==n)throw Error("Unknown option "+i)}},validators:Fn},Gn=qe,Hn=Me,Jn=Je,zn=function(t){return Rn(t),t.headers=t.headers||{},t.data=Tn.call(t,t.data,t.headers,t.transformRequest),t.headers=_n.merge(t.headers.common||{},t.headers[t.method]||{},t.headers),_n.forEach(["delete","get","head","post","put","patch","common"],(function(e){delete t.headers[e]})),(t.adapter||Nn.adapter)(t).then((function(e){return Rn(t),e.data=Tn.call(t,e.data,e.headers,t.transformResponse),e}),(function(e){return kn(e)||(Rn(t),e&&e.response&&(e.response.data=Tn.call(t,e.response.data,e.response.headers,t.transformResponse))),Promise.reject(e)}))},Kn=Dn,Wn=Mn,Vn=Wn.validators;function Yn(t){this.defaults=t,this.interceptors={request:new Jn,response:new Jn}}Yn.prototype.request=function(t){"string"==typeof t?(t=arguments[1]||{}).url=arguments[0]:t=t||{},(t=Kn(this.defaults,t)).method?t.method=t.method.toLowerCase():this.defaults.method?t.method=this.defaults.method.toLowerCase():t.method="get";var e=t.transitional;void 0!==e&&Wn.assertOptions(e,{silentJSONParsing:Vn.transitional(Vn.boolean),forcedJSONParsing:Vn.transitional(Vn.boolean),clarifyTimeoutError:Vn.transitional(Vn.boolean)},!1);var n=[],r=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(r=r&&e.synchronous,n.unshift(e.fulfilled,e.rejected))}));var o,i=[];if(this.interceptors.response.forEach((function(t){i.push(t.fulfilled,t.rejected)})),!r){var s=[zn,void 0];for(Array.prototype.unshift.apply(s,n),s=s.concat(i),o=Promise.resolve(t);s.length;)o=o.then(s.shift(),s.shift());return o}for(var a=t;n.length;){var u=n.shift(),c=n.shift();try{a=u(a)}catch(t){c(t);break}}try{o=zn(a)}catch(t){return Promise.reject(t)}for(;i.length;)o=o.then(i.shift(),i.shift());return o},Yn.prototype.getUri=function(t){return t=Kn(this.defaults,t),Hn(t.url,t.params,t.paramsSerializer).replace(/^\?/,"")},Gn.forEach(["delete","get","head","options"],(function(t){Yn.prototype[t]=function(e,n){return this.request(Kn(n||{},{method:t,url:e,data:(n||{}).data}))}})),Gn.forEach(["post","put","patch"],(function(t){Yn.prototype[t]=function(e,n,r){return this.request(Kn(r||{},{method:t,url:e,data:n}))}}));var $n=Yn,Xn=sn;function Qn(t){if("function"!=typeof t)throw new TypeError("executor must be a function.");var e;this.promise=new Promise((function(t){e=t}));var n=this;this.promise.then((function(t){if(n._listeners){var e,r=n._listeners.length;for(e=0;e1&&void 0!==arguments[1]?arguments[1]:{},r=this.retrieve(t);if(r)return Promise.resolve(r);var o=Pe(this.client,{query:yr({query:t,api_key:this.client.config.api_key},n)}).then((function(n){var r=n.body.result.hits;return e.store(t,r),r}));return this.store(t,o),o}},{key:"resolve",value:function(t){return(e=this.client,n=t.id,r={query:{api_key:this.client.config.api_key}},xe({resource:Ce,client:e,action:"gbr"})(n,r)).then((function(t){return t.body.result}));var e,n,r}}]),t}(),mr=function(t){return"string"==typeof t},gr=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"idpc";return t.setAttribute(e,"true")},br=function(){return!0},wr=function(t,e){return mr(t)?e.querySelector(t):t},Or=function(){return window.document},Er=function(t){return mr(t)?Or().querySelector(t):null===t?Or():t},Sr=function(t,e){var n=t.getAttribute("style");return Object.keys(e).forEach((function(n){return t.style[n]=e[n]})),n},xr=function(t){return t.style.display="none",t},jr=function(t){return t.style.display="",t},Cr=function(t,e,n){for(var r=t.querySelectorAll(e),o=0;o=1&&e<=31||127==e||0==r&&e>=48&&e<=57||1==r&&e>=48&&e<=57&&45==i?"\\"+e.toString(16)+" ":(0!=r||1!=n||45!=e)&&(e>=128||45==e||95==e||e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122)?t.charAt(r):"\\"+t.charAt(r):o+="οΏ½";return o},_r=function(t,e){return t.dispatchEvent(function(t){var e=t.event,n=t.bubbles,r=void 0===n||n,o=t.cancelable,i=void 0===o||o;if("function"==typeof window.Event)return new window.Event(e,{bubbles:r,cancelable:i});var s=document.createEvent("Event");return s.initEvent(e,r,i),s}({event:e}))},Tr=function(t){return null!==t&&t instanceof HTMLSelectElement},kr=function(t){return null!==t&&t instanceof HTMLInputElement},Nr=function(t){return null!==t&&t instanceof HTMLTextAreaElement},Lr=function(t,e){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];t&&(kr(t)||Nr(t))&&Dr({e:t,value:e,skipTrigger:n})},Rr=function(t,e){return null!==e&&null!==t.querySelector('[value="'.concat(e,'"]'))},Ur=function(t,e){var n=Object.getOwnPropertyDescriptor(t.constructor.prototype,"value");void 0!==n&&(void 0!==n.set&&n.set.call(t,e))},Dr=function(t){null!==t.value&&(function(t){var e=t.e,n=t.value,r=t.skipTrigger;null!==n&&Tr(e)&&(Ur(e,n),r||_r(e,"select"),_r(e,"change"))}(t),function(t){var e=t.e,n=t.value,r=t.skipTrigger;null!==n&&(kr(e)||Nr(e))&&(Ur(e,n),r||_r(e,"input"),_r(e,"change"))}(t))},Br=function(t){return/^GY/.test(t.postcode)?"GG":/^JE/.test(t.postcode)?"JE":null},qr="United Kingdom",Fr="Isle of Man",Ir="England",Mr="Scotland",Gr="Wales",Hr="Northern Ireland",Jr="Channel Islands",zr=function(t){var e=t.country;if(e===Ir)return qr;if(e===Mr)return qr;if(e===Gr)return qr;if(e===Hr)return qr;if(e===Fr)return Fr;if(e===Jr){var n=Br(t);if("GG"===n)return"Guernsey";if("JE"===n)return"Jersey"}return null},Kr=function(t,e){if(t){if(Tr(t)){var n=function(t){var e=t.country;return e===Ir||e===Mr||e===Gr||e===Hr?"GB":e===Fr?"IM":e===Jr?Br(t):null}(e);Rr(t,n)&&Dr({e:t,value:n});var r=zr(e);Rr(t,r)&&Dr({e:t,value:r})}if(kr(t)){var o=zr(e);Dr({e:t,value:o})}}},Wr={};"undefined"!=typeof window&&(window.idpcGlobal?Wr=window.idpcGlobal:window.idpcGlobal=Wr);var Vr=function(){return Wr};function Yr(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function $r(e){for(var n=1;n0)&&!(r=i.next()).done;)s.push(r.value)}catch(t){o={error:t}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return s}!function(t){t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped"}(Xr||(Xr={}));var lo={type:"xstate.init"};function fo(t){return void 0===t?[]:[].concat(t)}function po(t,e){return"string"==typeof(t="string"==typeof t&&e&&e[t]?e[t]:t)?{type:t}:"function"==typeof t?{type:t.name,exec:t}:t}function ho(t){return function(e){return t===e}}function yo(t){return"string"==typeof t?{type:t}:t}function vo(t,e){return{value:t,context:e,actions:[],changed:!1,matches:ho(t)}}function mo(t,e,n){var r=e,o=!1;return[t.filter((function(t){if("xstate.assign"===t.type){o=!0;var e=Object.assign({},r);return"function"==typeof t.assignment?e=t.assignment(r,n):Object.keys(t.assignment).forEach((function(o){e[o]="function"==typeof t.assignment[o]?t.assignment[o](r,n):t.assignment[o]})),r=e,!1}return!0})),r,o]}function go(t,e){void 0===e&&(e={});var n=co(mo(fo(t.states[t.initial].entry).map((function(t){return po(t,e.actions)})),t.context,lo),2),r=n[0],o=n[1],i={config:t,_options:e,initialState:{value:t.initial,actions:r,context:o,matches:ho(t.initial)},transition:function(e,n){var r,o,s="string"==typeof e?{value:e,context:t.context}:e,a=s.value,u=s.context,c=yo(n),l=t.states[a];if(l.on){var f=fo(l.on[c.type]);try{for(var p=function(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}(f),d=p.next();!d.done;d=p.next()){var h=d.value;if(void 0===h)return vo(a,u);var y="string"==typeof h?{target:h}:h,v=y.target,m=y.actions,g=void 0===m?[]:m,b=y.cond,w=void 0===b?function(){return!0}:b,O=void 0===v,E=null!=v?v:a,S=t.states[E];if(w(u,c)){var x=co(mo((O?fo(g):[].concat(l.exit,g,S.entry).filter((function(t){return t}))).map((function(t){return po(t,i._options.actions)})),u,c),3),j=x[0],C=x[1],P=x[2],A=null!=v?v:a;return{value:A,context:C,actions:j,changed:v!==a||j.length>0||P,matches:ho(A)}}}}catch(t){r={error:t}}finally{try{d&&!d.done&&(o=p.return)&&o.call(p)}finally{if(r)throw r.error}}}return vo(a,u)}};return i}var bo=function(t,e){return t.actions.forEach((function(n){var r=n.exec;return r&&r(t.context,e)}))};function wo(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function Oo(e){for(var n=1;n0}},{target:"notifying"}]}},notifying:{entry:["renderNotice"],exit:["clearAnnouncement"],on:Oo(Oo(Oo(Oo(Oo({},So),xo),jo),Eo),_o)},suggesting_country:{entry:["renderContexts","gotoCurrent","expand","addCountryHint"],exit:["resetCurrent","gotoCurrent","contract","clearHint"],on:Oo(Oo(Oo(Oo(Oo(Oo({},So),jo),Co),Po),Ao),{},{INPUT:{actions:["countryInput"]},SELECT_COUNTRY:{target:"notifying",actions:["selectCountry"]}})},suggesting:{entry:["renderSuggestions","gotoCurrent","expand","addHint"],exit:["resetCurrent","gotoCurrent","contract","clearHint"],on:Oo(Oo(Oo(Oo(Oo(Oo(Oo(Oo(Oo({},So),xo),jo),Eo),_o),Co),Po),Ao),{},{SELECT_ADDRESS:{target:"closed",actions:["selectAddress"]}})}}},{actions:{addHint:function(){e.setPlaceholder(e.options.msgPlaceholder)},addCountryHint:function(){e.setPlaceholder(e.options.msgPlaceholderCountry)},clearHint:function(){e.unsetPlaceholder()},gotoCurrent:function(){e.goToCurrent()},resetCurrent:function(){e.current=-1},input:function(t,n){"INPUT"===n.type&&e.retrieveSuggestions(n.event)},countryInput:function(){},clearAnnouncement:function(){e.announce("")},renderContexts:function(t,n){"CHANGE_COUNTRY"===n.type&&e.renderContexts()},renderSuggestions:function(t,n){"SUGGEST"===n.type&&e.renderSuggestions()},updateSuggestions:function(t,n){"SUGGEST"===n.type&&e.updateSuggestions(n.suggestions)},close:function(t,n){if("CLOSE"===n.type)return e.close(n.reason);e.close()},open:function(){e.open()},expand:function(){e.ariaExpand()},contract:function(){e.ariaContract()},updateMessage:function(t,n){"NOTIFY"===n.type&&(e.notification=n.notification)},renderNotice:function(){e.renderNotice()},next:function(){e.next()},previous:function(){e.previous()},selectCountry:function(t,n){if("SELECT_COUNTRY"===n.type){var r=n.contextDetails;r&&(e.applyContext(r),e.notification="Country switched to ".concat(r.name," ").concat(r.icon))}},selectAddress:function(t,n){if("SELECT_ADDRESS"===n.type){var r=n.suggestion;r&&e.applySuggestion(r)}}}});return function(t){var e=t.initialState,n=Xr.NotStarted,r=new Set,o={_machine:t,send:function(o){n===Xr.Running&&(e=t.transition(e,o),bo(e,yo(o)),r.forEach((function(t){return t(e)})))},subscribe:function(t){return r.add(t),t(e),{unsubscribe:function(){return r.delete(t)}}},start:function(r){if(r){var i="object"==O(r)?r:{context:t.config.context,value:r};e={value:i.value,actions:[],context:i.context,matches:ho(i.value)}}return n=Xr.Running,bo(e,lo),o},stop:function(){return n=Xr.Stopped,r.clear(),o},get state(){return e},get status(){return n}};return o}(n)};function ko(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function No(e){for(var n=1;n0&&!e.some((function(t){return t===r})))return"continue";var o=t[r],a=o.name,u=o.icon;n.push({code:r,name:a,icon:u})},i=0,s=r;i0&&void 0!==arguments[0]?arguments[0]:"idpc_";return function(){var e=Vr();return e.idGen||(e.idGen={}),void 0===e.idGen[t]&&(e.idGen[t]=0),e.idGen[t]+=1,"".concat(t).concat(e.idGen[t])}}("idpcaf"),this.container=this.options.document.createElement("div"),this.container.className=this.options.containerClass,this.container.id=this.ids(),this.container.setAttribute("aria-haspopup","listbox"),this.message=this.options.document.createElement("li"),this.message.textContent=this.options.msgInitial,this.message.className=this.options.messageClass,this.countryToggle=this.options.document.createElement("span"),this.countryToggle.className=this.options.countryToggleClass,this.countryToggle.addEventListener("mousedown",Fo(this)),this.countryIcon=this.options.document.createElement("span"),this.countryIcon.className="idpc_icon",this.countryIcon.innerText=this.currentContext().icon,this.countryMessage=this.options.document.createElement("span"),this.countryMessage.innerText="Select Country",this.countryMessage.className="idpc_country",this.countryToggle.appendChild(this.countryMessage),this.countryToggle.appendChild(this.countryIcon),this.toolbar=this.options.document.createElement("div"),this.toolbar.className=this.options.toolbarClass,this.toolbar.appendChild(this.countryToggle),this.options.hideToolbar&&xr(this.toolbar),this.list=this.options.document.createElement("ul"),this.list.className=this.options.listClass,this.list.id=this.ids(),this.list.setAttribute("aria-label",this.options.msgList),this.list.setAttribute("role","listbox"),this.mainComponent=this.options.document.createElement("div"),this.mainComponent.appendChild(this.list),this.mainComponent.appendChild(this.toolbar),this.mainComponent.className=this.options.mainClass,xr(this.mainComponent),this.unhideEvent=this.unhideFields.bind(this),this.unhide=this.createUnhide(),!(r=mr(this.options.inputField)?this.scope.querySelector(this.options.inputField):this.options.inputField))throw new Error("Address Finder: Unable to find valid input field");this.input=r,this.input.setAttribute("autocomplete",this.options.autocomplete),this.input.setAttribute("aria-autocomplete","list"),this.input.setAttribute("aria-controls",this.list.id),this.input.setAttribute("aria-autocomplete","list"),this.input.setAttribute("aria-activedescendant",""),this.input.setAttribute("autocorrect","off"),this.input.setAttribute("autocapitalize","off"),this.input.setAttribute("spellcheck","false"),this.input.id||(this.input.id=this.ids()),this.ariaAnchor().setAttribute("role","combobox"),this.ariaAnchor().setAttribute("aria-expanded","false"),this.ariaAnchor().setAttribute("aria-owns",this.list.id),this.placeholderCache=this.input.placeholder,this.inputListener=qo(this),this.blurListener=Do(this),this.focusListener=Bo(this),this.keydownListener=Io(this);var i=function(t){var e=t.document,n=t.idA,r=t.idB,o=e.createElement("div");o.setAttribute("style","border:0px;padding:0px;clip:rect(0px,0px,0px,0px);height:1px;margin-bottom:-1px;margin-right:-1px;overflow:hidden;position:absolute;white-space:nowrap;width:1px");var i=Ft(e.createElement("div"),n),s=Ft(e.createElement("div"),r);o.appendChild(i),o.appendChild(s);var a=!0,u=qt((function(t){var e=a?i:s,n=a?s:i;a=!a,e.textContent=t,n.textContent=""}),1500,{});return{container:o,announce:u}}({idA:this.ids(),idB:this.ids(),document:this.options.document}),s=i.container,a=i.announce;this.announce=a,this.alerts=s,this.inputStyle=Sr(this.input,this.options.inputStyle),Sr(this.container,this.options.containerStyle),Sr(this.list,this.options.listStyle);var u=function(t){var e,n=t.input;if(!1===t.options.alignToInput)return{};try{var r=t.options.document.defaultView;if(!r)return{};e=r.getComputedStyle(n).marginBottom}catch(t){return{}}if(!e)return{};var o=parseInt(e.replace("px",""),10);return isNaN(o)||0===o?{}:{marginTop:-1*o+t.options.offset+"px"}}(this);Sr(this.mainComponent,No(No({},u),this.options.mainStyle)),this.fsm=To({c:this}),this.init()}return nt(t,[{key:"setPlaceholder",value:function(t){this.input.placeholder=t}},{key:"unsetPlaceholder",value:function(){if(void 0===this.placeholderCache)return this.input.removeAttribute("placeholder");this.input.placeholder=this.placeholderCache}},{key:"currentContext",value:function(){var t=this.options.contexts[this.context];return{code:this.context,name:t.name,icon:t.icon}}},{key:"load",value:function(){this.attach(),function(t){var e=t.options.injectStyle;if(e){var n=Vr();if(n.afstyle||(n.afstyle={}),mr(e)&&!n.afstyle[e]){n.afstyle[e]=!0;var r=function(t,e){var n=e.createElement("link");return n.type="text/css",n.rel="stylesheet",n.href=t,n}(e,t.document);return t.document.head.appendChild(r),r}!0!==e||n.afstyle[""]||(n.afstyle[""]=!0,function(t,e){var n=e.createElement("style");n.type="text/css",n.appendChild(e.createTextNode(t)),e.head.appendChild(n)}(".idpc_af.hidden{display:none}div.idpc_autocomplete{position:relative;margin:0!important;padding:0;border:0;color:#28282b;text-rendering:optimizeLegibility;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}div.idpc_autocomplete>input{display:block}div.idpc_af{position:absolute;left:0;z-index:2000;min-width:100%;box-sizing:border-box;border-radius:3px;background:#fff;border:1px solid rgba(0,0,0,.3);box-shadow:.05em .2em .6em rgba(0,0,0,.2);text-shadow:none;padding:0;margin-top:2px}div.idpc_af>ul{list-style:none;padding:0;max-height:250px;overflow-y:scroll;margin:0!important}div.idpc_af>ul>li{position:relative;padding:.2em .5em;cursor:pointer;margin:0!important}div.idpc_toolbar{padding:.3em .5em;border-top:1px solid rgba(0,0,0,.3);text-align:right}div.idpc_af>ul>li:hover{background-color:#e5e4e2}div.idpc_af>ul>li.idpc_error{padding:.5em;text-align:center;cursor:default!important}div.idpc_af>ul>li.idpc_error:hover{background:#fff;cursor:default!important}div.idpc_af>ul>li[aria-selected=true]{background-color:#e5e4e2;z-index:3000}div.idpc_autocomplete>.idpc-unhide{font-size:.9em;text-decoration:underline;cursor:pointer}div.idpc_af>div>span{padding:.2em .5em;border-radius:3px;cursor:pointer;font-size:110%}span.idpc_icon{font-size:1.2em;line-height:1em;vertical-align:middle}div.idpc_toolbar>span span.idpc_country{margin-right:.3em;max-width:0;font-size:.9em;-webkit-transition:max-width .5s ease-out;transition:max-width .5s ease-out;display:inline-block;vertical-align:middle;white-space:nowrap;overflow:hidden}div.idpc_autocomplete>div>div>span:hover span.idpc_country{max-width:7em}div.idpc_autocomplete>div>div>span:hover{background-color:#e5e4e2;-webkit-transition:background-color .5s ease;-ms-transition:background-color .5s ease;transition:background-color .5s ease}",t.document))}}(this),this.options.onLoaded.call(this)}},{key:"init",value:function(){var t=this;return new Promise((function(e){if(!t.options.checkKey)return t.load(),void e();je({client:t.client,api_key:t.options.apiKey}).then((function(n){if(!n.available)throw new Error("Key currently not usable");t.load(),e()})).catch((function(n){t.options.onFailedCheck.call(t,n),e()}))}))}},{key:"renderContexts",value:function(){var t=this;this.list.innerHTML="",this.contextSuggestions.forEach((function(e,n){var r=e.name,o=t.options.document.createElement("li");o.textContent=r,o.setAttribute("aria-selected","false"),o.setAttribute("tabindex","-1"),o.setAttribute("aria-posinset","".concat(n+1)),o.setAttribute("aria-setsize",t.contextSuggestions.length.toString()),o.setAttribute("role","option"),Sr(o,t.options.liStyle),o.addEventListener("mousedown",(function(n){n.preventDefault(),t.options.onMouseDown.call(t,n),t.fsm.send({type:"SELECT_COUNTRY",contextDetails:e})})),o.id="".concat(t.list.id,"_").concat(n),t.list.appendChild(o)})),this.announce("".concat(this.contextSuggestions.length," countries available"))}},{key:"renderSuggestions",value:function(){var t=this;this.list.innerHTML="";var e=this.suggestions;e.forEach((function(n,r){var o=t.options.document.createElement("li");o.textContent=n.suggestion,o.setAttribute("aria-selected","false"),o.setAttribute("tabindex","-1"),o.setAttribute("title",n.suggestion),o.setAttribute("aria-posinset","".concat(r+1)),o.setAttribute("aria-setsize",e.length.toString()),o.setAttribute("role","option"),Sr(o,t.options.liStyle),o.addEventListener("mousedown",(function(e){e.preventDefault(),t.options.onMouseDown.call(t,e),t.fsm.send({type:"SELECT_ADDRESS",suggestion:n})})),o.id="".concat(t.list.id,"_").concat(r),t.list.appendChild(o)})),this.announce("".concat(e.length," addresses available"))}},{key:"goToCurrent",value:function(){var t=this.list.children;this.input.setAttribute("aria-activedescendant","");for(var e=0;e0&&null==this.options.unhide&&this.container.appendChild(this.unhide)),this.fsm.start(),this.options.onMounted.call(this),this.hideFields(),this}},{key:"detach",value:function(){if(this.fsm.status!==Xr.Running)return this;this.input.removeEventListener("input",this.inputListener),this.input.removeEventListener("blur",this.blurListener),this.input.removeEventListener("focus",this.focusListener),this.input.removeEventListener("keydown",this.keydownListener),this.container.removeChild(this.mainComponent),this.container.removeChild(this.alerts);var t,e,n=this.container.parentNode;return n&&(n.insertBefore(this.input,this.container),n.removeChild(this.container)),this.unmountUnhide(),this.unhideFields(),this.fsm.stop(),t=this.input,e=this.inputStyle,t.setAttribute("style",e||""),this.options.onRemove.call(this),this.unsetPlaceholder(),this}},{key:"setMessage",value:function(t){return this.fsm.send({type:"NOTIFY",notification:t}),this}},{key:"ariaAnchor",value:function(){return"1.0"===this.options.aria?this.input:this.container}},{key:"query",value:function(){return this.input.value}},{key:"setSuggestions",value:function(t,e){return e!==this.query()?this:0===t.length?this.setMessage(this.options.msgNoMatch):(this.fsm.send({type:"SUGGEST",suggestions:t}),this)}},{key:"close",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"blur";xr(this.mainComponent),"esc"===t&&Lr(this.input,""),this.options.onClose.call(this,t)}},{key:"updateSuggestions",value:function(t){this.suggestions=t,this.current=-1}},{key:"applyContext",value:function(t){var e=t.code;this.context=e,this.countryIcon.innerText=t.icon,this.announce("Country switched to ".concat(t.name))}},{key:"renderNotice",value:function(){this.list.innerHTML="",this.input.setAttribute("aria-activedescendant",""),this.message.textContent=this.notification,this.announce(this.notification),this.list.appendChild(this.message)}},{key:"open",value:function(){jr(this.mainComponent),this.options.onOpen.call(this)}},{key:"next",value:function(){return this.current+1>this.list.children.length-1?this.current=0:this.current+=1,this}},{key:"previous",value:function(){return this.current-1<0?this.current=this.list.children.length-1:this.current+=-1,this}},{key:"scrollToView",value:function(t){var e=t.offsetTop,n=this.list.scrollTop;en+r&&(this.list.scrollTop=e-r+o),this}},{key:"goto",value:function(t){var e=this.list.children,n=e[t];return t>-1&&e.length>0?this.scrollToView(n):this.scrollToView(e[0]),this}},{key:"opened",value:function(){return!this.closed()}},{key:"closed",value:function(){return this.fsm.state.matches("closed")}},{key:"createUnhide",value:function(){var t=this,e=Mo(this.scope,this.options.unhide,(function(){var e=t.options.document.createElement("p");return e.innerText=t.options.msgUnhide,e.setAttribute("role","button"),e.setAttribute("tabindex","0"),t.options.unhideClass&&(e.className=t.options.unhideClass),e}));return e.addEventListener("click",this.unhideEvent),e}},{key:"unmountUnhide",value:function(){var t;this.unhide.removeEventListener("click",this.unhideEvent),null==this.options.unhide&&this.options.hide.length&&(null!==(t=this.unhide)&&null!==t.parentNode&&t.parentNode.removeChild(t))}},{key:"hiddenFields",value:function(){var t=this;return this.options.hide.map((function(e){return mr(e)?(n=t.options.scope,(r=e)?n.querySelector(r):null):e;var n,r})).filter((function(t){return null!==t}))}},{key:"hideFields",value:function(){this.hiddenFields().forEach(xr)}},{key:"unhideFields",value:function(){this.hiddenFields().forEach(jr),this.options.onUnhide.call(this)}}]),t}(),Do=function(t){return function(){t.options.onBlur.call(t),t.fsm.send({type:"CLOSE",reason:"blur"})}},Bo=function(t){return function(e){t.options.onFocus.call(t),t.fsm.send("AWAKE")}},qo=function(t){return function(e){if(":c"===t.query().toLowerCase())return Lr(t.input,""),t.fsm.send({type:"CHANGE_COUNTRY"});t.fsm.send({type:"INPUT",event:e})}},Fo=function(t){return function(e){e.preventDefault(),t.fsm.send({type:"CHANGE_COUNTRY"})}},Io=function(t){return function(e){var n=uo(e);if("Enter"===n&&e.preventDefault(),t.options.onKeyDown.call(t,e),t.closed())return t.fsm.send("AWAKE");if(t.fsm.state.matches("suggesting_country")){if("Enter"===n){var r=t.contextSuggestions[t.current];r&&t.fsm.send({type:"SELECT_COUNTRY",contextDetails:r})}"Backspace"===n&&t.fsm.send({type:"INPUT",event:e}),"ArrowUp"===n&&(e.preventDefault(),t.fsm.send("PREVIOUS")),"ArrowDown"===n&&(e.preventDefault(),t.fsm.send("NEXT"))}if(t.fsm.state.matches("suggesting")){if("Enter"===n){var o=t.suggestions[t.current];o&&t.fsm.send({type:"SELECT_ADDRESS",suggestion:o})}"Backspace"===n&&t.fsm.send({type:"INPUT",event:e}),"ArrowUp"===n&&(e.preventDefault(),t.fsm.send("PREVIOUS")),"ArrowDown"===n&&(e.preventDefault(),t.fsm.send("NEXT"))}"Escape"===n&&t.fsm.send({type:"CLOSE",reason:"esc"}),"Home"===n&&t.fsm.send({type:"RESET"}),"End"===n&&t.fsm.send({type:"RESET"})}},Mo=function(t,e,n){return mr(e)?t.querySelector(e):n&&null===e?n():e},Go=function(t){var e=new Uo(t);return Ho.push(e),e},Ho=[];function Jo(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function zo(e){for(var n=1;n1&&void 0!==arguments[1]?arguments[1]:"idpc";return"true"===t.getAttribute(e)}(t,e)}))},Vo=function(t){return function(t,e){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:br,r=t,o=e.toUpperCase();"HTML"!==r.tagName;){if(r.tagName===o&&n(r))return r;if(null===r.parentNode)return null;r=r.parentNode}return null}(t,"FORM")},Yo=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=new dr({api_key:t.apiKey}),r=e.pageTest,o=void 0===r?Ko:r;return o()?je({client:n}).then((function(n){if(!n.available)return null;var r=e.getScope,i=void 0===r?Vo:r,s=e.interval,a=void 0===s?1e3:s,u=e.anchor,c=e.onBind,l=void 0===c?Lo:c,f=e.onAnchorFound,p=void 0===f?Lo:f,d=e.onBindAttempt,h=void 0===d?Lo:d,y=e.immediate,v=void 0===y||y,m=e.marker,g=void 0===m?"idpc":m,b=function(){h({config:t,options:e}),Wo(zo({anchor:u},t),g).forEach((function(e){var n=i(e);if(n){var r=zo(zo({scope:n},t),{},{checkKey:!1});p({anchor:e,scope:n,config:r});var o=Go(r);gr(e,g),l(o)}}))},w=Pr({bind:b,pageTest:o,interval:a}),O=w.start,E=w.stop;return v&&O(),{start:O,stop:E,bind:b}})).catch((function(t){return e.onError&&e.onError(t),null})):Promise.resolve(null)},$o={exports:{}},Xo=function(t,e){return function(){for(var n=new Array(arguments.length),r=0;r=0)return;o[e]="set-cookie"===e?(o[e]?o[e]:[]).concat([n]):o[e]?o[e]+", "+n:n}})),o):o},Ri=ji,Ui=vi,Di=zi,Bi=Pi,qi=function(t){return new Promise((function(e,n){var r,o=t.data,i=t.headers,s=t.responseType;function a(){t.cancelToken&&t.cancelToken.unsubscribe(r),t.signal&&t.signal.removeEventListener("abort",r)}Ai.isFormData(o)&&delete i["Content-Type"];var u=new XMLHttpRequest;if(t.auth){var c=t.auth.username||"",l=t.auth.password?unescape(encodeURIComponent(t.auth.password)):"";i.Authorization="Basic "+btoa(c+":"+l)}var f=Ni(t.baseURL,t.url);function p(){if(u){var r="getAllResponseHeaders"in u?Li(u.getAllResponseHeaders()):null,o={data:s&&"text"!==s&&"json"!==s?u.response:u.responseText,status:u.status,statusText:u.statusText,headers:r,config:t,request:u};_i((function(t){e(t),a()}),(function(t){n(t),a()}),o),u=null}}if(u.open(t.method.toUpperCase(),ki(f,t.params,t.paramsSerializer),!0),u.timeout=t.timeout,"onloadend"in u?u.onloadend=p:u.onreadystatechange=function(){u&&4===u.readyState&&(0!==u.status||u.responseURL&&0===u.responseURL.indexOf("file:"))&&setTimeout(p)},u.onabort=function(){u&&(n(Ui("Request aborted",t,"ECONNABORTED",u)),u=null)},u.onerror=function(){n(Ui("Network Error",t,null,u)),u=null},u.ontimeout=function(){var e=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",r=t.transitional||Di.transitional;t.timeoutErrorMessage&&(e=t.timeoutErrorMessage),n(Ui(e,t,r.clarifyTimeoutError?"ETIMEDOUT":"ECONNABORTED",u)),u=null},Ai.isStandardBrowserEnv()){var d=(t.withCredentials||Ri(f))&&t.xsrfCookieName?Ti.read(t.xsrfCookieName):void 0;d&&(i[t.xsrfHeaderName]=d)}"setRequestHeader"in u&&Ai.forEach(i,(function(t,e){void 0===o&&"content-type"===e.toLowerCase()?delete i[e]:u.setRequestHeader(e,t)})),Ai.isUndefined(t.withCredentials)||(u.withCredentials=!!t.withCredentials),s&&"json"!==s&&(u.responseType=t.responseType),"function"==typeof t.onDownloadProgress&&u.addEventListener("progress",t.onDownloadProgress),"function"==typeof t.onUploadProgress&&u.upload&&u.upload.addEventListener("progress",t.onUploadProgress),(t.cancelToken||t.signal)&&(r=function(t){u&&(n(!t||t&&t.type?new Bi("canceled"):t),u.abort(),u=null)},t.cancelToken&&t.cancelToken.subscribe(r),t.signal&&(t.signal.aborted?r():t.signal.addEventListener("abort",r))),o||(o=null),u.send(o)}))},Fi=si,Ii=function(t,e){di.forEach(t,(function(n,r){r!==e&&r.toUpperCase()===e.toUpperCase()&&(t[e]=n,delete t[r])}))},Mi=hi,Gi={"Content-Type":"application/x-www-form-urlencoded"};function Hi(t,e){!Fi.isUndefined(t)&&Fi.isUndefined(t["Content-Type"])&&(t["Content-Type"]=e)}var Ji={transitional:{silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},adapter:function(){var t;return("undefined"!=typeof XMLHttpRequest||"undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process))&&(t=qi),t}(),transformRequest:[function(t,e){return Ii(e,"Accept"),Ii(e,"Content-Type"),Fi.isFormData(t)||Fi.isArrayBuffer(t)||Fi.isBuffer(t)||Fi.isStream(t)||Fi.isFile(t)||Fi.isBlob(t)?t:Fi.isArrayBufferView(t)?t.buffer:Fi.isURLSearchParams(t)?(Hi(e,"application/x-www-form-urlencoded;charset=utf-8"),t.toString()):Fi.isObject(t)||e&&"application/json"===e["Content-Type"]?(Hi(e,"application/json"),function(t,e,n){if(Fi.isString(t))try{return(e||JSON.parse)(t),Fi.trim(t)}catch(t){if("SyntaxError"!==t.name)throw t}return(n||JSON.stringify)(t)}(t)):t}],transformResponse:[function(t){var e=this.transitional||Ji.transitional,n=e&&e.silentJSONParsing,r=e&&e.forcedJSONParsing,o=!n&&"json"===this.responseType;if(o||r&&Fi.isString(t)&&t.length)try{return JSON.parse(t)}catch(t){if(o){if("SyntaxError"===t.name)throw Mi(t,this,"E_JSON_PARSE");throw t}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};Fi.forEach(["delete","get","head"],(function(t){Ji.headers[t]={}})),Fi.forEach(["post","put","patch"],(function(t){Ji.headers[t]=Fi.merge(Gi)}));var zi=Ji,Ki=si,Wi=zi,Vi=function(t){return!(!t||!t.__CANCEL__)},Yi=si,$i=function(t,e,n){var r=this||Wi;return Ki.forEach(n,(function(n){t=n.call(r,t,e)})),t},Xi=Vi,Qi=zi,Zi=Pi;function ts(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new Zi("canceled")}var es=si,ns=function(t,e){e=e||{};var n={};function r(t,e){return es.isPlainObject(t)&&es.isPlainObject(e)?es.merge(t,e):es.isPlainObject(e)?es.merge({},e):es.isArray(e)?e.slice():e}function o(n){return es.isUndefined(e[n])?es.isUndefined(t[n])?void 0:r(void 0,t[n]):r(t[n],e[n])}function i(t){if(!es.isUndefined(e[t]))return r(void 0,e[t])}function s(n){return es.isUndefined(e[n])?es.isUndefined(t[n])?void 0:r(void 0,t[n]):r(void 0,e[n])}function a(n){return n in e?r(t[n],e[n]):n in t?r(void 0,t[n]):void 0}var u={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:a};return es.forEach(Object.keys(t).concat(Object.keys(e)),(function(t){var e=u[t]||o,r=e(t);es.isUndefined(r)&&e!==a||(n[t]=r)})),n},rs="0.24.0",os=rs,is={};["object","boolean","number","function","string","symbol"].forEach((function(t,e){is[t]=function(n){return O(n)===t||"a"+(e<1?"n ":" ")+t}}));var ss={};is.transitional=function(t,e,n){function r(t,e){return"[Axios v"+os+"] Transitional option '"+t+"'"+e+(n?". "+n:"")}return function(n,o,i){if(!1===t)throw new Error(r(o," has been removed"+(e?" in "+e:"")));return e&&!ss[o]&&(ss[o]=!0,console.warn(r(o," has been deprecated since v"+e+" and will be removed in the near future"))),!t||t(n,o,i)}};var as={assertOptions:function(t,e,n){if("object"!==O(t))throw new TypeError("options must be an object");for(var r=Object.keys(t),o=r.length;o-- >0;){var i=r[o],s=e[i];if(s){var a=t[i],u=void 0===a||s(a,i,t);if(!0!==u)throw new TypeError("option "+i+" must be "+u)}else if(!0!==n)throw Error("Unknown option "+i)}},validators:is},us=si,cs=ci,ls=pi,fs=function(t){return ts(t),t.headers=t.headers||{},t.data=$i.call(t,t.data,t.headers,t.transformRequest),t.headers=Yi.merge(t.headers.common||{},t.headers[t.method]||{},t.headers),Yi.forEach(["delete","get","head","post","put","patch","common"],(function(e){delete t.headers[e]})),(t.adapter||Qi.adapter)(t).then((function(e){return ts(t),e.data=$i.call(t,e.data,e.headers,t.transformResponse),e}),(function(e){return Xi(e)||(ts(t),e&&e.response&&(e.response.data=$i.call(t,e.response.data,e.response.headers,t.transformResponse))),Promise.reject(e)}))},ps=ns,ds=as,hs=ds.validators;function ys(t){this.defaults=t,this.interceptors={request:new ls,response:new ls}}ys.prototype.request=function(t){"string"==typeof t?(t=arguments[1]||{}).url=arguments[0]:t=t||{},(t=ps(this.defaults,t)).method?t.method=t.method.toLowerCase():this.defaults.method?t.method=this.defaults.method.toLowerCase():t.method="get";var e=t.transitional;void 0!==e&&ds.assertOptions(e,{silentJSONParsing:hs.transitional(hs.boolean),forcedJSONParsing:hs.transitional(hs.boolean),clarifyTimeoutError:hs.transitional(hs.boolean)},!1);var n=[],r=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(r=r&&e.synchronous,n.unshift(e.fulfilled,e.rejected))}));var o,i=[];if(this.interceptors.response.forEach((function(t){i.push(t.fulfilled,t.rejected)})),!r){var s=[fs,void 0];for(Array.prototype.unshift.apply(s,n),s=s.concat(i),o=Promise.resolve(t);s.length;)o=o.then(s.shift(),s.shift());return o}for(var a=t;n.length;){var u=n.shift(),c=n.shift();try{a=u(a)}catch(t){c(t);break}}try{o=fs(a)}catch(t){return Promise.reject(t)}for(;i.length;)o=o.then(i.shift(),i.shift());return o},ys.prototype.getUri=function(t){return t=ps(this.defaults,t),cs(t.url,t.params,t.paramsSerializer).replace(/^\?/,"")},us.forEach(["delete","get","head","options"],(function(t){ys.prototype[t]=function(e,n){return this.request(ps(n||{},{method:t,url:e,data:(n||{}).data}))}})),us.forEach(["post","put","patch"],(function(t){ys.prototype[t]=function(e,n,r){return this.request(ps(r||{},{method:t,url:e,data:n}))}}));var vs=ys,ms=Pi;function gs(t){if("function"!=typeof t)throw new TypeError("executor must be a function.");var e;this.promise=new Promise((function(t){e=t}));var n=this;this.promise.then((function(t){if(n._listeners){var e,r=n._listeners.length;for(e=0;e1&&void 0!==arguments[1]&&arguments[1],n=t.value;return ks(e).reduce((function(t,e){return n===e||t}),!1)},Ls=function(){},Rs=function(t,e,n){var r=t.country,o=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(!r)return Ls;var i=function(t){if(Ns(t,o))return e();n()};return r.addEventListener("change",(function(t){i(t.target)})),i(r)},Us=function(t,e){var n={};return Object.keys(t).forEach((function(r){var o,i;n[r]=(o=t[r],i=e,"string"==typeof o?i.querySelector(o):o)})),n},Ds=function(){var t,e=(t=Z.mark((function t(e,n){var r,o,i=arguments;return Z.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(r=i.length>2&&void 0!==i[2]?i[2]:{},o=i.length>3?i[3]:void 0,!0===e.autocomplete){t.next=4;break}return t.abrupt("return");case 4:if(void 0!==n.line_1){t.next=6;break}return t.abrupt("return");case 6:return t.next=8,Yo(Cs({apiKey:e.apiKey,checkKey:!0,onLoaded:function(){var t=this;this.options.outputFields=Us(n,this.scope),Ps(e,this.options.outputFields,o),Rs(this.options.outputFields,(function(){return t.attach()}),(function(){return t.detach()}),!0)},outputFields:n},e.autocompleteOverride),r);case 8:case"end":return t.stop()}}),t)})),function(){var e=this,n=arguments;return new Promise((function(r,o){var i=t.apply(e,n);function s(t){E(i,r,o,s,a,"next",t)}function a(t){E(i,r,o,s,a,"throw",t)}s(void 0)}))});return function(t,n){return e.apply(this,arguments)}}(),Bs=function(t,e){return-1!==t.indexOf(e)},qs=[{line_1:'[name="order[billing_address][street][0]"]',line_2:'[name="order[billing_address][street][1]"]',line_3:'[name="order[billing_address][street][2]"]',postcode:'[name="order[billing_address][postcode]"]',post_town:'[name="order[billing_address][city]"]',organisation_name:'[name="order[billing_address][company]"]',county:'[name="order[billing_address][region]"]',country:'[name="order[billing_address][country_id]"]'},{line_1:'[name="order[shipping_address][street][0]"]',line_2:'[name="order[shipping_address][street][1]"]',line_3:'[name="order[shipping_address][street][2]"]',postcode:'[name="order[shipping_address][postcode]"]',post_town:'[name="order[shipping_address][city]"]',organisation_name:'[name="order[shipping_address][company]"]',county:'[name="order[shipping_address][region]"]',country:'[name="order[shipping_address][country_id]"]'}],Fs=function(t){qs.forEach((function(e){Ds(t,e,{pageTest:Is,getScope:function(t){return n(t,"fieldset")}})}))},Is=function(){return Bs(window.location.pathname,"/sales")},Ms={line_1:'[name="street[0]"]',line_2:'[name="street[1]"]',line_3:'[name="street[2]"]',postcode:'[name="postcode"]',post_town:'[name="city"]',organisation_name:'[name="company"]',county:'[name="region"]',country:'[name="country_id"]'},Gs=function(t){Ds(t,Ms,{pageTest:Hs})},Hs=function(){return Bs(window.location.pathname,"/sales/order")},Js=function(t){return"admin__fieldset"===t.className},zs=function(){return Bs(window.location.pathname,"/customer")},Ks=function(t){Ds(t,Ms,{pageTest:zs,getScope:function(t){return n(t,"fieldset",Js)}})},Ws=function(t){return"admin__fieldset"===t.className},Vs=function(){return!0},Ys=function(t){(t.customFields||[]).forEach((function(e){Ds(t,e,{pageTest:Vs,getScope:function(t){return n(t,"fieldset",Ws)}})}))};window.idpcStart=function(){return[Fs,Ks,Gs,Ys].forEach((function(t){var e=function(){var t=window.idpcConfig;if(void 0!==t)return o(o({},i),t)}();e&&t(e)}))}}(); diff --git a/view/base/web/binding.js b/view/base/web/binding.js index b203a4e0..0f4ce0bf 100644 --- a/view/base/web/binding.js +++ b/view/base/web/binding.js @@ -4,11138 +4,4 @@ * Magento Integration * Copyright IDDQD Limited, all rights reserved */ -(function () { - 'use strict'; - - function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; - } - - var isString$5 = function isString(input) { - return typeof input === "string"; - }; - - var hasWindow$1 = function hasWindow() { - return typeof window !== "undefined"; - }; - var toArray$1 = function toArray(nodeList) { - return Array.prototype.slice.call(nodeList); - }; - var loaded$1 = function loaded(elem) { - return elem.getAttribute("idpc") === "true"; - }; - var markLoaded$1 = function markLoaded(elem) { - return elem.setAttribute("idpc", "true"); - }; - - var isTrue$3 = function isTrue() { - return true; - }; - - var getParent$1 = function getParent(node, entity) { - var test = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : isTrue$3; - var parent = node; - var tagName = entity.toUpperCase(); - - while (parent.tagName !== "HTML") { - if (parent.tagName === tagName && test(parent)) return parent; - if (parent.parentNode === null) return null; - parent = parent.parentNode; - } - - return null; - }; - var toHtmlElem$1 = function toHtmlElem(parent, selector) { - return selector ? parent.querySelector(selector) : null; - }; - var insertBefore = function insertBefore(_ref) { - var elem = _ref.elem, - target = _ref.target; - var parent = target.parentNode; - if (parent === null) return; - parent.insertBefore(elem, target); - return elem; - }; - var toElem$1 = function toElem(elem, context) { - if (isString$5(elem)) return context.querySelector(elem); - return elem; - }; - - var d$2 = function d() { - return window.document; - }; - - var getScope$2 = function getScope(scope) { - if (isString$5(scope)) return d$2().querySelector(scope); - if (scope === null) return d$2(); - return scope; - }; - var getDocument$1 = function getDocument(scope) { - if (scope instanceof Document) return scope; - if (scope.ownerDocument) return scope.ownerDocument; - return d$2(); - }; - var setStyle$1 = function setStyle(element, style) { - var currentRules = element.getAttribute("style"); - Object.keys(style).forEach(function (key) { - return element.style[key] = style[key]; - }); - return currentRules; - }; - var restoreStyle$1 = function restoreStyle(element, style) { - element.setAttribute("style", style || ""); - }; - var hide$1 = function hide(e) { - e.style.display = "none"; - return e; - }; - var show$1 = function show(e) { - e.style.display = ""; - return e; - }; - var remove$1 = function remove(elem) { - if (elem === null || elem.parentNode === null) return; - elem.parentNode.removeChild(elem); - }; - var contains$1 = function contains(scope, selector, text) { - var elements = scope.querySelectorAll(selector); - - for (var i = 0; i < elements.length; i++) { - var e = elements[i]; - var content = e.innerText; - if (content && content.trim() === text) return e; - } - - return null; - }; - - function ownKeys$f(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - - function _objectSpread$f(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$f(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$f(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - var defaults$e = { - enabled: true, - apiKey: "", - populateOrganisation: true, - populateCounty: false, - autocomplete: true, - autocompleteOverride: {}, - postcodeLookup: true, - postcodeLookupOverride: {} - }; - var config = function config() { - var c = window.idpcConfig; - if (c === undefined) return; - return _objectSpread$f(_objectSpread$f({}, defaults$e), c); - }; - var cssEscape$1 = function cssEscape(value) { - value = String(value); - var length = value.length; - var index = -1; - var codeUnit; - var result = ""; - var firstCodeUnit = value.charCodeAt(0); - - while (++index < length) { - codeUnit = value.charCodeAt(index); - - if (codeUnit == 0x0000) { - result += "\uFFFD"; - continue; - } - - if (codeUnit >= 0x0001 && codeUnit <= 0x001f || codeUnit == 0x007f || index == 0 && codeUnit >= 0x0030 && codeUnit <= 0x0039 || index == 1 && codeUnit >= 0x0030 && codeUnit <= 0x0039 && firstCodeUnit == 0x002d) { - result += "\\" + codeUnit.toString(16) + " "; - continue; - } - - if (index == 0 && length == 1 && codeUnit == 0x002d) { - result += "\\" + value.charAt(index); - continue; - } - - if (codeUnit >= 0x0080 || codeUnit == 0x002d || codeUnit == 0x005f || codeUnit >= 0x0030 && codeUnit <= 0x0039 || codeUnit >= 0x0041 && codeUnit <= 0x005a || codeUnit >= 0x0061 && codeUnit <= 0x007a) { - result += value.charAt(index); - continue; - } - - result += "\\" + value.charAt(index); - } - - return result; - }; - - var newEvent$1 = function newEvent(_ref) { - var event = _ref.event, - _ref$bubbles = _ref.bubbles, - bubbles = _ref$bubbles === void 0 ? true : _ref$bubbles, - _ref$cancelable = _ref.cancelable, - cancelable = _ref$cancelable === void 0 ? true : _ref$cancelable; - if (typeof window.Event === "function") return new window.Event(event, { - bubbles: bubbles, - cancelable: cancelable - }); - var e = document.createEvent("Event"); - e.initEvent(event, bubbles, cancelable); - return e; - }; - var trigger$1 = function trigger(e, event) { - return e.dispatchEvent(newEvent$1({ - event: event - })); - }; - - var isSelect$1 = function isSelect(e) { - if (e === null) return false; - return e instanceof HTMLSelectElement; - }; - var isInput$1 = function isInput(e) { - if (e === null) return false; - return e instanceof HTMLInputElement; - }; - var isTextarea$1 = function isTextarea(e) { - if (e === null) return false; - return e instanceof HTMLTextAreaElement; - }; - var update$2 = function update(input, value) { - var skipTrigger = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - if (!input) return; - if (!isInput$1(input) && !isTextarea$1(input)) return; - change$1({ - e: input, - value: value, - skipTrigger: skipTrigger - }); - }; - var hasValue$1 = function hasValue(select, value) { - if (value === null) return false; - return select.querySelector("[value=\"".concat(value, "\"]")) !== null; - }; - - var updateSelect$1 = function updateSelect(_ref) { - var e = _ref.e, - value = _ref.value, - skipTrigger = _ref.skipTrigger; - if (value === null) return; - if (!isSelect$1(e)) return; - setValue$1(e, value); - if (!skipTrigger) trigger$1(e, "select"); - trigger$1(e, "change"); - }; - - var setValue$1 = function setValue(e, value) { - var descriptor = Object.getOwnPropertyDescriptor(e.constructor.prototype, "value"); - if (descriptor === undefined) return; - if (descriptor.set === undefined) return; - var setter = descriptor.set; - setter.call(e, value); - }; - - var updateInput$1 = function updateInput(_ref2) { - var e = _ref2.e, - value = _ref2.value, - skipTrigger = _ref2.skipTrigger; - if (value === null) return; - if (!isInput$1(e) && !isTextarea$1(e)) return; - setValue$1(e, value); - if (!skipTrigger) trigger$1(e, "input"); - trigger$1(e, "change"); - }; - - var change$1 = function change(options) { - if (options.value === null) return; - updateSelect$1(options); - updateInput$1(options); - }; - - var toCiIso$1 = function toCiIso(address) { - if (/^GY/.test(address.postcode)) return "GG"; - if (/^JE/.test(address.postcode)) return "JE"; - return null; - }; - var UK$1 = "United Kingdom"; - var IOM$1 = "Isle of Man"; - var EN$1 = "England"; - var SC$1 = "Scotland"; - var WA$1 = "Wales"; - var NI$1 = "Northern Ireland"; - var CI$1 = "Channel Islands"; - var toIso$1 = function toIso(address) { - var country = address.country; - if (country === EN$1) return "GB"; - if (country === SC$1) return "GB"; - if (country === WA$1) return "GB"; - if (country === NI$1) return "GB"; - if (country === IOM$1) return "IM"; - if (country === CI$1) return toCiIso$1(address); - return null; - }; - var toCountry$1 = function toCountry(address) { - var country = address.country; - if (country === EN$1) return UK$1; - if (country === SC$1) return UK$1; - if (country === WA$1) return UK$1; - if (country === NI$1) return UK$1; - if (country === IOM$1) return IOM$1; - - if (country === CI$1) { - var iso = toCiIso$1(address); - if (iso === "GG") return "Guernsey"; - if (iso === "JE") return "Jersey"; - } - - return null; - }; - var updateCountry$1 = function updateCountry(select, address) { - if (!select) return; - - if (isSelect$1(select)) { - var iso = toIso$1(address); - if (hasValue$1(select, iso)) change$1({ - e: select, - value: iso - }); - var bcc = toCountry$1(address); - if (hasValue$1(select, bcc)) change$1({ - e: select, - value: bcc - }); - } - - if (isInput$1(select)) { - var _bcc = toCountry$1(address); - - change$1({ - e: select, - value: _bcc - }); - } - }; - - var g$1 = {}; - - if (hasWindow$1()) { - if (window.idpcGlobal) { - g$1 = window.idpcGlobal; - } else { - window.idpcGlobal = g$1; - } - } - - function _arrayWithHoles(arr) { - if (Array.isArray(arr)) return arr; - } - - function _iterableToArrayLimit(arr, i) { - var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; - - if (_i == null) return; - var _arr = []; - var _n = true; - var _d = false; - - var _s, _e; - - try { - for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { - _arr.push(_s.value); - - if (i && _arr.length === i) break; - } - } catch (err) { - _d = true; - _e = err; - } finally { - try { - if (!_n && _i["return"] != null) _i["return"](); - } finally { - if (_d) throw _e; - } - } - - return _arr; - } - - function _arrayLikeToArray(arr, len) { - if (len == null || len > arr.length) len = arr.length; - - for (var i = 0, arr2 = new Array(len); i < len; i++) { - arr2[i] = arr[i]; - } - - return arr2; - } - - function _unsupportedIterableToArray(o, minLen) { - if (!o) return; - if (typeof o === "string") return _arrayLikeToArray(o, minLen); - var n = Object.prototype.toString.call(o).slice(8, -1); - if (n === "Object" && o.constructor) n = o.constructor.name; - if (n === "Map" || n === "Set") return Array.from(o); - if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); - } - - function _nonIterableRest() { - throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); - } - - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - - var dist = {}; - - Object.defineProperty(dist, "__esModule", { - value: true - }); - var capitalisePostTown_1 = dist.capitalisePostTown = void 0; - var exclusion = /^(of|le|upon|on|the)$/; - var containsAmpersand = /\w+&\w+/; // capitalise word with exceptions on exclusion list - - var capitaliseWord = function capitaliseWord(word) { - word = word.toLowerCase(); - if (word.match(exclusion)) return word; - if (word.match(containsAmpersand)) return word.toUpperCase(); - return word.charAt(0).toUpperCase() + word.slice(1); - }; - - var joiner = /-/; - var joinerWord = /^(in|de|under|upon|y|on|over|the|by)$/; // Check for names connected with hyphens - - var checkJoins = function checkJoins(string) { - if (string.match(joiner) === null) return string; - return string.split("-").map(function (str) { - if (str.match(joinerWord)) return str.toLowerCase(); - return capitaliseWord(str); - }).join("-"); - }; - - var boness = /bo'ness/i; - var bfpo = /bfpo/i; // Handles unusual names which cannot be easily generalised into a rule - - var exceptions = function exceptions(str) { - if (str.match(boness)) return "Bo'Ness"; - if (str.match(bfpo)) return "BFPO"; - return str; - }; - - var capitalisePostTown = function capitalisePostTown(postTown) { - return postTown.split(" ").map(capitaliseWord).map(checkJoins).map(exceptions).join(" "); - }; - - capitalisePostTown_1 = dist.capitalisePostTown = capitalisePostTown; - - function ownKeys$e(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - - function _objectSpread$e(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$e(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$e(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - var numberOfLines$1 = function numberOfLines(targets) { - var line_2 = targets.line_2, - line_3 = targets.line_3; - if (!line_2) return 1; - if (!line_3) return 2; - return 3; - }; - var join$1 = function join(list) { - return list.filter(function (e) { - if (isString$5(e)) return !!e.trim(); - return !!e; - }).join(", "); - }; - var toAddressLines$1 = function toAddressLines(n, address) { - var line_1 = address.line_1, - line_2 = address.line_2, - line_3 = address.line_3; - if (n === 3) return [line_1, line_2, line_3]; - if (n === 2) return [line_1, join$1([line_2, line_3]), ""]; - return [join$1([line_1, line_2, line_3]), "", ""]; - }; - var extract$1 = function extract(a, attr) { - var result = a[attr]; - if (typeof result === "number") return result.toString(); - if (result === undefined) return ""; - return result; - }; - var notInAddress$1 = function notInAddress(o, attr) { - return o[attr] === undefined; - }; - var getFields$2 = function getFields(o) { - return _objectSpread$e(_objectSpread$e(_objectSpread$e({}, o.outputFields), searchNames$1(o.names || {}, o.config.scope)), searchLabels$1(o.labels || {}, o.config.scope)); - }; - - var updateLines$1 = function updateLines(fields, address, scope) { - var _toAddressLines3 = toAddressLines$1(numberOfLines$1(fields), address), - _toAddressLines4 = _slicedToArray(_toAddressLines3, 3), - line_1 = _toAddressLines4[0], - line_2 = _toAddressLines4[1], - line_3 = _toAddressLines4[2]; - - update$2(toElem$1(fields.line_1 || null, scope), line_1); - update$2(toElem$1(fields.line_2 || null, scope), line_2); - update$2(toElem$1(fields.line_3 || null, scope), line_3); - }; - - var searchNames$1 = function searchNames(names, scope) { - var result = {}; - var key; - - for (key in names) { - if (!names.hasOwnProperty(key)) continue; - var name = names[key]; - var named = toElem$1("[name=\"".concat(name, "\"]"), scope); - - if (named) { - result[key] = named; - continue; - } - - var ariaNamed = toElem$1("[aria-name=\"".concat(name, "\"]"), scope); - if (ariaNamed) result[key] = ariaNamed; - } - - return result; - }; - var searchLabels$1 = function searchLabels(labels, scope) { - var result = {}; - if (labels === undefined) return labels; - var key; - - for (key in labels) { - if (!labels.hasOwnProperty(key)) continue; - var name = labels[key]; - if (!name) continue; - var first = contains$1(scope, "label", name); - var label = toElem$1(first, scope); - if (!label) continue; - var forEl = label.getAttribute("for"); - - if (forEl) { - var byId = scope.querySelector("#".concat(cssEscape$1(forEl))); - - if (byId) { - result[key] = byId; - continue; - } - } - - var inner = label.querySelector("input"); - if (inner) result[key] = inner; - } - - return result; - }; - var populateAddress$1 = function populateAddress(options) { - var config = options.config; - - var address = _objectSpread$e({}, options.address); - - var scope = config.scope, - titleizePostTown = config.titleizePostTown, - populateOrganisation = config.populateOrganisation, - populateCounty = config.populateCounty; - var fields = getFields$2(options); - if (config.removeOrganisation) removeOrganisation$1(address); - if (titleizePostTown) address.post_town = capitalisePostTown_1(address.post_town); - updateLines$1(fields, address, scope); - delete address.line_1; - delete address.line_2; - delete address.line_3; - updateCountry$1(toElem$1(fields.country || null, scope), address); - delete address.country; - if (populateOrganisation === false) delete address.organisation_name; - if (populateCounty === false) delete address.county; - var e; - - for (e in fields) { - if (notInAddress$1(address, e)) continue; - - if (fields.hasOwnProperty(e)) { - var value = fields[e]; - if (!value) continue; - update$2(toElem$1(value, scope), extract$1(address, e)); - } - } - }; - var removeOrganisation$1 = function removeOrganisation(address) { - if (address.organisation_name.length === 0) return address; - if (address.line_2.length === 0 && address.line_3.length === 0) return address; - - if (address.line_1 === address.organisation_name) { - address.line_1 = address.line_2; - address.line_2 = address.line_3; - address.line_3 = ""; - } - - return address; - }; - - var keyCodeMapping$1 = { - 13: "Enter", - 38: "ArrowUp", - 40: "ArrowDown", - 36: "Home", - 35: "End", - 27: "Escape", - 8: "Backspace" - }; - var supportedKeys$1 = ["Enter", "ArrowUp", "ArrowDown", "Home", "End", "Escape", "Backspace"]; - - var supported$1 = function supported(k) { - return supportedKeys$1.indexOf(k) !== -1; - }; - - var toKey$1 = function toKey(event) { - if (event.keyCode) return keyCodeMapping$1[event.keyCode] || null; - return supported$1(event.key) ? event.key : null; - }; - - function _typeof(obj) { - "@babel/helpers - typeof"; - - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof = function _typeof(obj) { - return typeof obj; - }; - } else { - _typeof = function _typeof(obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }; - } - - return _typeof(obj); - } - - var isObject$7 = function isObject(value) { - var type = _typeof(value); - - return !!value && (type == "object" || type == "function"); - }; - var debounce$1 = function debounce(func, wait, options) { - var lastArgs, lastThis, maxWait, result, timerId, lastCallTime; - var lastInvokeTime = 0; - var leading = false; - var maxing = false; - var trailing = true; - - if (typeof func !== "function") { - throw new TypeError("Expected a function"); - } - - wait = +wait || 0; - - if (isObject$7(options)) { - leading = !!options.leading; - maxing = "maxWait" in options; - maxWait = maxing ? Math.max(+options.maxWait || 0, wait) : maxWait; - trailing = "trailing" in options ? !!options.trailing : trailing; - } - - function invokeFunc(time) { - var args = lastArgs; - var thisArg = lastThis; - lastArgs = lastThis = undefined; - lastInvokeTime = time; - result = func.apply(thisArg, args); - return result; - } - - function leadingEdge(time) { - lastInvokeTime = time; - timerId = setTimeout(timerExpired, wait); - return leading ? invokeFunc(time) : result; - } - - function remainingWait(time) { - var timeSinceLastCall = time - lastCallTime; - var timeSinceLastInvoke = time - lastInvokeTime; - var timeWaiting = wait - timeSinceLastCall; - return maxing ? Math.min(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting; - } - - function shouldInvoke(time) { - var timeSinceLastCall = time - lastCallTime; - var timeSinceLastInvoke = time - lastInvokeTime; - return lastCallTime === undefined || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait; - } - - function timerExpired() { - var time = Date.now(); - - if (shouldInvoke(time)) { - return trailingEdge(time); - } - - timerId = setTimeout(timerExpired, remainingWait(time)); - } - - function trailingEdge(time) { - timerId = undefined; - - if (trailing && lastArgs) { - return invokeFunc(time); - } - - lastArgs = lastThis = undefined; - return result; - } - - function cancel() { - if (timerId !== undefined) { - clearTimeout(timerId); - } - - lastInvokeTime = 0; - lastArgs = lastCallTime = lastThis = timerId = undefined; - } - - function pending() { - return timerId !== undefined; - } - - function debounced() { - var time = Date.now(); - var isInvoking = shouldInvoke(time); - - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - lastArgs = args; - lastThis = this; - lastCallTime = time; - - if (isInvoking) { - if (timerId === undefined) { - return leadingEdge(lastCallTime); - } - - if (maxing) { - timerId = setTimeout(timerExpired, wait); - return invokeFunc(lastCallTime); - } - } - - if (timerId === undefined) { - timerId = setTimeout(timerExpired, wait); - } - - return result; - } - - debounced.cancel = cancel; - debounced.pending = pending; - return debounced; - }; - - var watchTimer = function watchTimer(_ref) { - var bind = _ref.bind, - _ref$interval = _ref.interval, - interval = _ref$interval === void 0 ? 1000 : _ref$interval; - var timer = null; - - var start = function start() { - timer = window.setInterval(function () { - try { - bind(); - } catch (e) { - stop(); - } - }, interval); - return timer; - }; - - var stop = function stop() { - if (timer === null) return; - window.clearInterval(timer); - timer = null; - }; - - return { - start: start, - stop: stop - }; - }; - var watchMutation = function watchMutation(_ref2) { - var bind = _ref2.bind, - _ref2$interval = _ref2.interval, - interval = _ref2$interval === void 0 ? 1000 : _ref2$interval, - _ref2$target = _ref2.target, - target = _ref2$target === void 0 ? window.document : _ref2$target, - _ref2$observerConfig = _ref2.observerConfig, - observerConfig = _ref2$observerConfig === void 0 ? { - subtree: true, - childList: true, - attributes: true - } : _ref2$observerConfig; - var observer = new MutationObserver(debounce$1(function () { - try { - bind(); - } catch (e) { - stop(); - } - }, interval)); - - var start = function start() { - observer.observe(target, observerConfig); - return null; - }; - - var stop = function stop() { - return observer.disconnect(); - }; - - return { - start: start, - stop: stop - }; - }; - var watchChange = function watchChange(options) { - if (!window) return watchTimer(options); - if (!window.MutationObserver) return watchTimer(options); - if (options.mutationObserver) return watchMutation(options); - return watchTimer(options); - }; - - function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { - try { - var info = gen[key](arg); - var value = info.value; - } catch (error) { - reject(error); - return; - } - - if (info.done) { - resolve(value); - } else { - Promise.resolve(value).then(_next, _throw); - } - } - - function _asyncToGenerator(fn) { - return function () { - var self = this, - args = arguments; - return new Promise(function (resolve, reject) { - var gen = fn.apply(self, args); - - function _next(value) { - asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); - } - - function _throw(err) { - asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); - } - - _next(undefined); - }); - }; - } - - /** - * Copyright (c) 2014-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. - */ - var Op = Object.prototype; - var hasOwn = Op.hasOwnProperty; - var undefined$1; // More compressible than void 0. - - var $Symbol = typeof Symbol === "function" ? Symbol : {}; - var iteratorSymbol = $Symbol.iterator || "@@iterator"; - var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; - var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; - - function wrap(innerFn, outerFn, self, tryLocsList) { - // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. - var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; - var generator = Object.create(protoGenerator.prototype); - var context = new Context(tryLocsList || []); // The ._invoke method unifies the implementations of the .next, - // .throw, and .return methods. - - generator._invoke = makeInvokeMethod(innerFn, self, context); - return generator; - } // Try/catch helper to minimize deoptimizations. Returns a completion - // record like context.tryEntries[i].completion. This interface could - // have been (and was previously) designed to take a closure to be - // invoked without arguments, but in all the cases we care about we - // already have an existing method we want to call, so there's no need - // to create a new function object. We can even get away with assuming - // the method takes exactly one argument, since that happens to be true - // in every case, so we don't have to touch the arguments object. The - // only additional allocation required is the completion record, which - // has a stable shape and so hopefully should be cheap to allocate. - - - function tryCatch(fn, obj, arg) { - try { - return { - type: "normal", - arg: fn.call(obj, arg) - }; - } catch (err) { - return { - type: "throw", - arg: err - }; - } - } - - var GenStateSuspendedStart = "suspendedStart"; - var GenStateSuspendedYield = "suspendedYield"; - var GenStateExecuting = "executing"; - var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as - // breaking out of the dispatch switch statement. - - var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and - // .constructor.prototype properties for functions that return Generator - // objects. For full spec compliance, you may wish to configure your - // minifier not to mangle the names of these two functions. - - function Generator() {} - - function GeneratorFunction() {} - - function GeneratorFunctionPrototype() {} // This is a polyfill for %IteratorPrototype% for environments that - // don't natively support it. - - - var IteratorPrototype = {}; - - IteratorPrototype[iteratorSymbol] = function () { - return this; - }; - - var getProto = Object.getPrototypeOf; - var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); - - if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { - // This environment has a native %IteratorPrototype%; use it instead - // of the polyfill. - IteratorPrototype = NativeIteratorPrototype; - } - - var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); - GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; - GeneratorFunctionPrototype.constructor = GeneratorFunction; - GeneratorFunctionPrototype[toStringTagSymbol] = GeneratorFunction.displayName = "GeneratorFunction"; // Helper for defining the .next, .throw, and .return methods of the - // Iterator interface in terms of a single ._invoke method. - - function defineIteratorMethods(prototype) { - ["next", "throw", "return"].forEach(function (method) { - prototype[method] = function (arg) { - return this._invoke(method, arg); - }; - }); - } - - function isGeneratorFunction(genFun) { - var ctor = typeof genFun === "function" && genFun.constructor; - return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can - // do is to check its .name property. - (ctor.displayName || ctor.name) === "GeneratorFunction" : false; - } - - function mark(genFun) { - if (Object.setPrototypeOf) { - Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); - } else { - genFun.__proto__ = GeneratorFunctionPrototype; - - if (!(toStringTagSymbol in genFun)) { - genFun[toStringTagSymbol] = "GeneratorFunction"; - } - } - - genFun.prototype = Object.create(Gp); - return genFun; - } - // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test - // `hasOwn.call(value, "__await")` to determine if the yielded value is - // meant to be awaited. - - function awrap(arg) { - return { - __await: arg - }; - } - - function AsyncIterator(generator, PromiseImpl) { - function invoke(method, arg, resolve, reject) { - var record = tryCatch(generator[method], generator, arg); - - if (record.type === "throw") { - reject(record.arg); - } else { - var result = record.arg; - var value = result.value; - - if (value && _typeof(value) === "object" && hasOwn.call(value, "__await")) { - return PromiseImpl.resolve(value.__await).then(function (value) { - invoke("next", value, resolve, reject); - }, function (err) { - invoke("throw", err, resolve, reject); - }); - } - - return PromiseImpl.resolve(value).then(function (unwrapped) { - // When a yielded Promise is resolved, its final value becomes - // the .value of the Promise<{value,done}> result for the - // current iteration. - result.value = unwrapped; - resolve(result); - }, function (error) { - // If a rejected Promise was yielded, throw the rejection back - // into the async generator function so it can be handled there. - return invoke("throw", error, resolve, reject); - }); - } - } - - var previousPromise; - - function enqueue(method, arg) { - function callInvokeWithMethodAndArg() { - return new PromiseImpl(function (resolve, reject) { - invoke(method, arg, resolve, reject); - }); - } - - return previousPromise = // If enqueue has been called before, then we want to wait until - // all previous Promises have been resolved before calling invoke, - // so that results are always delivered in the correct order. If - // enqueue has not been called before, then it is important to - // call invoke immediately, without waiting on a callback to fire, - // so that the async generator function has the opportunity to do - // any necessary setup in a predictable way. This predictability - // is why the Promise constructor synchronously invokes its - // executor callback, and why async functions synchronously - // execute code before the first await. Since we implement simple - // async functions in terms of async generators, it is especially - // important to get this right, even though it requires care. - previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later - // invocations of the iterator. - callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); - } // Define the unified helper method that is used to implement .next, - // .throw, and .return (see defineIteratorMethods). - - - this._invoke = enqueue; - } - - defineIteratorMethods(AsyncIterator.prototype); - - AsyncIterator.prototype[asyncIteratorSymbol] = function () { - return this; - }; // Note that simple async functions are implemented on top of - // AsyncIterator objects; they just return a Promise for the value of - // the final result produced by the iterator. - - - function async(innerFn, outerFn, self, tryLocsList, PromiseImpl) { - if (PromiseImpl === void 0) PromiseImpl = Promise; - var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); - return isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator. - : iter.next().then(function (result) { - return result.done ? result.value : iter.next(); - }); - } - - function makeInvokeMethod(innerFn, self, context) { - var state = GenStateSuspendedStart; - return function invoke(method, arg) { - if (state === GenStateExecuting) { - throw new Error("Generator is already running"); - } - - if (state === GenStateCompleted) { - if (method === "throw") { - throw arg; - } // Be forgiving, per 25.3.3.3.3 of the spec: - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume - - - return doneResult(); - } - - context.method = method; - context.arg = arg; - - while (true) { - var delegate = context.delegate; - - if (delegate) { - var delegateResult = maybeInvokeDelegate(delegate, context); - - if (delegateResult) { - if (delegateResult === ContinueSentinel) continue; - return delegateResult; - } - } - - if (context.method === "next") { - // Setting context._sent for legacy support of Babel's - // function.sent implementation. - context.sent = context._sent = context.arg; - } else if (context.method === "throw") { - if (state === GenStateSuspendedStart) { - state = GenStateCompleted; - throw context.arg; - } - - context.dispatchException(context.arg); - } else if (context.method === "return") { - context.abrupt("return", context.arg); - } - - state = GenStateExecuting; - var record = tryCatch(innerFn, self, context); - - if (record.type === "normal") { - // If an exception is thrown from innerFn, we leave state === - // GenStateExecuting and loop back for another invocation. - state = context.done ? GenStateCompleted : GenStateSuspendedYield; - - if (record.arg === ContinueSentinel) { - continue; - } - - return { - value: record.arg, - done: context.done - }; - } else if (record.type === "throw") { - state = GenStateCompleted; // Dispatch the exception by looping back around to the - // context.dispatchException(context.arg) call above. - - context.method = "throw"; - context.arg = record.arg; - } - } - }; - } // Call delegate.iterator[context.method](context.arg) and handle the - // result, either by returning a { value, done } result from the - // delegate iterator, or by modifying context.method and context.arg, - // setting context.delegate to null, and returning the ContinueSentinel. - - - function maybeInvokeDelegate(delegate, context) { - var method = delegate.iterator[context.method]; - - if (method === undefined$1) { - // A .throw or .return when the delegate iterator has no .throw - // method always terminates the yield* loop. - context.delegate = null; - - if (context.method === "throw") { - // Note: ["return"] must be used for ES3 parsing compatibility. - if (delegate.iterator["return"]) { - // If the delegate iterator has a return method, give it a - // chance to clean up. - context.method = "return"; - context.arg = undefined$1; - maybeInvokeDelegate(delegate, context); - - if (context.method === "throw") { - // If maybeInvokeDelegate(context) changed context.method from - // "return" to "throw", let that override the TypeError below. - return ContinueSentinel; - } - } - - context.method = "throw"; - context.arg = new TypeError("The iterator does not provide a 'throw' method"); - } - - return ContinueSentinel; - } - - var record = tryCatch(method, delegate.iterator, context.arg); - - if (record.type === "throw") { - context.method = "throw"; - context.arg = record.arg; - context.delegate = null; - return ContinueSentinel; - } - - var info = record.arg; - - if (!info) { - context.method = "throw"; - context.arg = new TypeError("iterator result is not an object"); - context.delegate = null; - return ContinueSentinel; - } - - if (info.done) { - // Assign the result of the finished delegate to the temporary - // variable specified by delegate.resultName (see delegateYield). - context[delegate.resultName] = info.value; // Resume execution at the desired location (see delegateYield). - - context.next = delegate.nextLoc; // If context.method was "throw" but the delegate handled the - // exception, let the outer generator proceed normally. If - // context.method was "next", forget context.arg since it has been - // "consumed" by the delegate iterator. If context.method was - // "return", allow the original .return call to continue in the - // outer generator. - - if (context.method !== "return") { - context.method = "next"; - context.arg = undefined$1; - } - } else { - // Re-yield the result returned by the delegate method. - return info; - } // The delegate iterator is finished, so forget it and continue with - // the outer generator. - - - context.delegate = null; - return ContinueSentinel; - } // Define Generator.prototype.{next,throw,return} in terms of the - // unified ._invoke helper method. - - - defineIteratorMethods(Gp); - Gp[toStringTagSymbol] = "Generator"; // A Generator should always return itself as the iterator object when the - // @@iterator function is called on it. Some browsers' implementations of the - // iterator prototype chain incorrectly implement this, causing the Generator - // object to not be returned from this call. This ensures that doesn't happen. - // See https://github.com/facebook/regenerator/issues/274 for more details. - - Gp[iteratorSymbol] = function () { - return this; - }; - - Gp.toString = function () { - return "[object Generator]"; - }; - - function pushTryEntry(locs) { - var entry = { - tryLoc: locs[0] - }; - - if (1 in locs) { - entry.catchLoc = locs[1]; - } - - if (2 in locs) { - entry.finallyLoc = locs[2]; - entry.afterLoc = locs[3]; - } - - this.tryEntries.push(entry); - } - - function resetTryEntry(entry) { - var record = entry.completion || {}; - record.type = "normal"; - delete record.arg; - entry.completion = record; - } - - function Context(tryLocsList) { - // The root entry object (effectively a try statement without a catch - // or a finally block) gives us a place to store values thrown from - // locations where there is no enclosing try statement. - this.tryEntries = [{ - tryLoc: "root" - }]; - tryLocsList.forEach(pushTryEntry, this); - this.reset(true); - } - - function keys(object) { - var keys = []; - - for (var key in object) { - keys.push(key); - } - - keys.reverse(); // Rather than returning an object with a next method, we keep - // things simple and return the next function itself. - - return function next() { - while (keys.length) { - var key = keys.pop(); - - if (key in object) { - next.value = key; - next.done = false; - return next; - } - } // To avoid creating an additional object, we just hang the .value - // and .done properties off the next function object itself. This - // also ensures that the minifier will not anonymize the function. - - - next.done = true; - return next; - }; - } - - function values(iterable) { - if (iterable) { - var iteratorMethod = iterable[iteratorSymbol]; - - if (iteratorMethod) { - return iteratorMethod.call(iterable); - } - - if (typeof iterable.next === "function") { - return iterable; - } - - if (!isNaN(iterable.length)) { - var i = -1, - next = function next() { - while (++i < iterable.length) { - if (hasOwn.call(iterable, i)) { - next.value = iterable[i]; - next.done = false; - return next; - } - } - - next.value = undefined$1; - next.done = true; - return next; - }; - - return next.next = next; - } - } // Return an iterator with no values. - - - return { - next: doneResult - }; - } - - function doneResult() { - return { - value: undefined$1, - done: true - }; - } - - Context.prototype = { - constructor: Context, - reset: function reset(skipTempReset) { - this.prev = 0; - this.next = 0; // Resetting context._sent for legacy support of Babel's - // function.sent implementation. - - this.sent = this._sent = undefined$1; - this.done = false; - this.delegate = null; - this.method = "next"; - this.arg = undefined$1; - this.tryEntries.forEach(resetTryEntry); - - if (!skipTempReset) { - for (var name in this) { - // Not sure about the optimal order of these conditions: - if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) { - this[name] = undefined$1; - } - } - } - }, - stop: function stop() { - this.done = true; - var rootEntry = this.tryEntries[0]; - var rootRecord = rootEntry.completion; - - if (rootRecord.type === "throw") { - throw rootRecord.arg; - } - - return this.rval; - }, - dispatchException: function dispatchException(exception) { - if (this.done) { - throw exception; - } - - var context = this; - - function handle(loc, caught) { - record.type = "throw"; - record.arg = exception; - context.next = loc; - - if (caught) { - // If the dispatched exception was caught by a catch block, - // then let that catch block handle the exception normally. - context.method = "next"; - context.arg = undefined$1; - } - - return !!caught; - } - - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - var record = entry.completion; - - if (entry.tryLoc === "root") { - // Exception thrown outside of any try block that could handle - // it, so set the completion value of the entire function to - // throw the exception. - return handle("end"); - } - - if (entry.tryLoc <= this.prev) { - var hasCatch = hasOwn.call(entry, "catchLoc"); - var hasFinally = hasOwn.call(entry, "finallyLoc"); - - if (hasCatch && hasFinally) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } else if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - } else if (hasCatch) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } - } else if (hasFinally) { - if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - } else { - throw new Error("try statement without catch or finally"); - } - } - } - }, - abrupt: function abrupt(type, arg) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - - if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { - var finallyEntry = entry; - break; - } - } - - if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { - // Ignore the finally entry if control is not jumping to a - // location outside the try/catch block. - finallyEntry = null; - } - - var record = finallyEntry ? finallyEntry.completion : {}; - record.type = type; - record.arg = arg; - - if (finallyEntry) { - this.method = "next"; - this.next = finallyEntry.finallyLoc; - return ContinueSentinel; - } - - return this.complete(record); - }, - complete: function complete(record, afterLoc) { - if (record.type === "throw") { - throw record.arg; - } - - if (record.type === "break" || record.type === "continue") { - this.next = record.arg; - } else if (record.type === "return") { - this.rval = this.arg = record.arg; - this.method = "return"; - this.next = "end"; - } else if (record.type === "normal" && afterLoc) { - this.next = afterLoc; - } - - return ContinueSentinel; - }, - finish: function finish(finallyLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - - if (entry.finallyLoc === finallyLoc) { - this.complete(entry.completion, entry.afterLoc); - resetTryEntry(entry); - return ContinueSentinel; - } - } - }, - "catch": function _catch(tryLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - - if (entry.tryLoc === tryLoc) { - var record = entry.completion; - - if (record.type === "throw") { - var thrown = record.arg; - resetTryEntry(entry); - } - - return thrown; - } - } // The context.catch method must only be called with a location - // argument that corresponds to a known catch block. - - - throw new Error("illegal catch attempt"); - }, - delegateYield: function delegateYield(iterable, resultName, nextLoc) { - this.delegate = { - iterator: values(iterable), - resultName: resultName, - nextLoc: nextLoc - }; - - if (this.method === "next") { - // Deliberately forget the last sent value so that we don't - // accidentally pass it on to the delegate. - this.arg = undefined$1; - } - - return ContinueSentinel; - } - }; // Export a default namespace that plays well with Rollup - - var _regeneratorRuntime = { - wrap: wrap, - isGeneratorFunction: isGeneratorFunction, - AsyncIterator: AsyncIterator, - mark: mark, - awrap: awrap, - async: async, - keys: keys, - values: values - }; - - function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } - } - - function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); - } - } - - function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) _defineProperties(Constructor.prototype, protoProps); - if (staticProps) _defineProperties(Constructor, staticProps); - return Constructor; - } - - function isObject$6(value) { - var type = _typeof(value); - - return value != null && (type == 'object' || type == 'function'); - } - - var isObject_1 = isObject$6; - - var freeGlobal$1 = _typeof(commonjsGlobal) == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; - var _freeGlobal = freeGlobal$1; - - var freeGlobal = _freeGlobal; - /** Detect free variable `self`. */ - - var freeSelf = (typeof self === "undefined" ? "undefined" : _typeof(self)) == 'object' && self && self.Object === Object && self; - /** Used as a reference to the global object. */ - - var root$2 = freeGlobal || freeSelf || Function('return this')(); - var _root = root$2; - - var root$1 = _root; - /** - * Gets the timestamp of the number of milliseconds that have elapsed since - * the Unix epoch (1 January 1970 00:00:00 UTC). - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Date - * @returns {number} Returns the timestamp. - * @example - * - * _.defer(function(stamp) { - * console.log(_.now() - stamp); - * }, _.now()); - * // => Logs the number of milliseconds it took for the deferred invocation. - */ - - var now$1 = function now() { - return root$1.Date.now(); - }; - - var now_1 = now$1; - - /** Used to match a single whitespace character. */ - var reWhitespace = /\s/; - /** - * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace - * character of `string`. - * - * @private - * @param {string} string The string to inspect. - * @returns {number} Returns the index of the last non-whitespace character. - */ - - function trimmedEndIndex$1(string) { - var index = string.length; - - while (index-- && reWhitespace.test(string.charAt(index))) {} - - return index; - } - - var _trimmedEndIndex = trimmedEndIndex$1; - - var trimmedEndIndex = _trimmedEndIndex; - /** Used to match leading whitespace. */ - - var reTrimStart = /^\s+/; - /** - * The base implementation of `_.trim`. - * - * @private - * @param {string} string The string to trim. - * @returns {string} Returns the trimmed string. - */ - - function baseTrim$1(string) { - return string ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '') : string; - } - - var _baseTrim = baseTrim$1; - - var root = _root; - /** Built-in value references. */ - - var _Symbol2 = root.Symbol; - var _Symbol$2 = _Symbol2; - - var _Symbol$1 = _Symbol$2; - /** Used for built-in method references. */ - - var objectProto$1 = Object.prototype; - /** Used to check objects for own properties. */ - - var hasOwnProperty = objectProto$1.hasOwnProperty; - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - - var nativeObjectToString$1 = objectProto$1.toString; - /** Built-in value references. */ - - var symToStringTag$1 = _Symbol$1 ? _Symbol$1.toStringTag : undefined; - /** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. - */ - - function getRawTag$1(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag$1), - tag = value[symToStringTag$1]; - - try { - value[symToStringTag$1] = undefined; - var unmasked = true; - } catch (e) {} - - var result = nativeObjectToString$1.call(value); - - if (unmasked) { - if (isOwn) { - value[symToStringTag$1] = tag; - } else { - delete value[symToStringTag$1]; - } - } - - return result; - } - - var _getRawTag = getRawTag$1; - - /** Used for built-in method references. */ - var objectProto = Object.prototype; - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - - var nativeObjectToString = objectProto.toString; - /** - * Converts `value` to a string using `Object.prototype.toString`. - * - * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - */ - - function objectToString$1(value) { - return nativeObjectToString.call(value); - } - - var _objectToString = objectToString$1; - - var _Symbol = _Symbol$2, - getRawTag = _getRawTag, - objectToString = _objectToString; - /** `Object#toString` result references. */ - - var nullTag = '[object Null]', - undefinedTag = '[object Undefined]'; - /** Built-in value references. */ - - var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined; - /** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - - function baseGetTag$1(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; - } - - return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value); - } - - var _baseGetTag = baseGetTag$1; - - function isObjectLike$1(value) { - return value != null && _typeof(value) == 'object'; - } - - var isObjectLike_1 = isObjectLike$1; - - var baseGetTag = _baseGetTag, - isObjectLike = isObjectLike_1; - /** `Object#toString` result references. */ - - var symbolTag = '[object Symbol]'; - /** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ - - function isSymbol$1(value) { - return _typeof(value) == 'symbol' || isObjectLike(value) && baseGetTag(value) == symbolTag; - } - - var isSymbol_1 = isSymbol$1; - - var baseTrim = _baseTrim, - isObject$5 = isObject_1, - isSymbol = isSymbol_1; - /** Used as references for various `Number` constants. */ - - var NAN = 0 / 0; - /** Used to detect bad signed hexadecimal string values. */ - - var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - /** Used to detect binary string values. */ - - var reIsBinary = /^0b[01]+$/i; - /** Used to detect octal string values. */ - - var reIsOctal = /^0o[0-7]+$/i; - /** Built-in method references without a dependency on `root`. */ - - var freeParseInt = parseInt; - /** - * Converts `value` to a number. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. - * @example - * - * _.toNumber(3.2); - * // => 3.2 - * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toNumber(Infinity); - * // => Infinity - * - * _.toNumber('3.2'); - * // => 3.2 - */ - - function toNumber$1(value) { - if (typeof value == 'number') { - return value; - } - - if (isSymbol(value)) { - return NAN; - } - - if (isObject$5(value)) { - var other = typeof value.valueOf == 'function' ? value.valueOf() : value; - value = isObject$5(other) ? other + '' : other; - } - - if (typeof value != 'string') { - return value === 0 ? value : +value; - } - - value = baseTrim(value); - var isBinary = reIsBinary.test(value); - return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value; - } - - var toNumber_1 = toNumber$1; - - var isObject$4 = isObject_1, - now = now_1, - toNumber = toNumber_1; - /** Error message constants. */ - - var FUNC_ERROR_TEXT = 'Expected a function'; - /* Built-in method references for those with the same name as other `lodash` methods. */ - - var nativeMax = Math.max, - nativeMin = Math.min; - /** - * Creates a debounced function that delays invoking `func` until after `wait` - * milliseconds have elapsed since the last time the debounced function was - * invoked. The debounced function comes with a `cancel` method to cancel - * delayed `func` invocations and a `flush` method to immediately invoke them. - * Provide `options` to indicate whether `func` should be invoked on the - * leading and/or trailing edge of the `wait` timeout. The `func` is invoked - * with the last arguments provided to the debounced function. Subsequent - * calls to the debounced function return the result of the last `func` - * invocation. - * - * **Note:** If `leading` and `trailing` options are `true`, `func` is - * invoked on the trailing edge of the timeout only if the debounced function - * is invoked more than once during the `wait` timeout. - * - * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred - * until to the next tick, similar to `setTimeout` with a timeout of `0`. - * - * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) - * for details over the differences between `_.debounce` and `_.throttle`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to debounce. - * @param {number} [wait=0] The number of milliseconds to delay. - * @param {Object} [options={}] The options object. - * @param {boolean} [options.leading=false] - * Specify invoking on the leading edge of the timeout. - * @param {number} [options.maxWait] - * The maximum time `func` is allowed to be delayed before it's invoked. - * @param {boolean} [options.trailing=true] - * Specify invoking on the trailing edge of the timeout. - * @returns {Function} Returns the new debounced function. - * @example - * - * // Avoid costly calculations while the window size is in flux. - * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); - * - * // Invoke `sendMail` when clicked, debouncing subsequent calls. - * jQuery(element).on('click', _.debounce(sendMail, 300, { - * 'leading': true, - * 'trailing': false - * })); - * - * // Ensure `batchLog` is invoked once after 1 second of debounced calls. - * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); - * var source = new EventSource('/stream'); - * jQuery(source).on('message', debounced); - * - * // Cancel the trailing debounced invocation. - * jQuery(window).on('popstate', debounced.cancel); - */ - - function debounce(func, wait, options) { - var lastArgs, - lastThis, - maxWait, - result, - timerId, - lastCallTime, - lastInvokeTime = 0, - leading = false, - maxing = false, - trailing = true; - - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - - wait = toNumber(wait) || 0; - - if (isObject$4(options)) { - leading = !!options.leading; - maxing = 'maxWait' in options; - maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; - trailing = 'trailing' in options ? !!options.trailing : trailing; - } - - function invokeFunc(time) { - var args = lastArgs, - thisArg = lastThis; - lastArgs = lastThis = undefined; - lastInvokeTime = time; - result = func.apply(thisArg, args); - return result; - } - - function leadingEdge(time) { - // Reset any `maxWait` timer. - lastInvokeTime = time; // Start the timer for the trailing edge. - - timerId = setTimeout(timerExpired, wait); // Invoke the leading edge. - - return leading ? invokeFunc(time) : result; - } - - function remainingWait(time) { - var timeSinceLastCall = time - lastCallTime, - timeSinceLastInvoke = time - lastInvokeTime, - timeWaiting = wait - timeSinceLastCall; - return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting; - } - - function shouldInvoke(time) { - var timeSinceLastCall = time - lastCallTime, - timeSinceLastInvoke = time - lastInvokeTime; // Either this is the first call, activity has stopped and we're at the - // trailing edge, the system time has gone backwards and we're treating - // it as the trailing edge, or we've hit the `maxWait` limit. - - return lastCallTime === undefined || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait; - } - - function timerExpired() { - var time = now(); - - if (shouldInvoke(time)) { - return trailingEdge(time); - } // Restart the timer. - - - timerId = setTimeout(timerExpired, remainingWait(time)); - } - - function trailingEdge(time) { - timerId = undefined; // Only invoke if we have `lastArgs` which means `func` has been - // debounced at least once. - - if (trailing && lastArgs) { - return invokeFunc(time); - } - - lastArgs = lastThis = undefined; - return result; - } - - function cancel() { - if (timerId !== undefined) { - clearTimeout(timerId); - } - - lastInvokeTime = 0; - lastArgs = lastCallTime = lastThis = timerId = undefined; - } - - function flush() { - return timerId === undefined ? result : trailingEdge(now()); - } - - function debounced() { - var time = now(), - isInvoking = shouldInvoke(time); - lastArgs = arguments; - lastThis = this; - lastCallTime = time; - - if (isInvoking) { - if (timerId === undefined) { - return leadingEdge(lastCallTime); - } - - if (maxing) { - // Handle invocations in a tight loop. - clearTimeout(timerId); - timerId = setTimeout(timerExpired, wait); - return invokeFunc(lastCallTime); - } - } - - if (timerId === undefined) { - timerId = setTimeout(timerExpired, wait); - } - - return result; - } - - debounced.cancel = cancel; - debounced.flush = flush; - return debounced; - } - - var debounce_1 = debounce; - - /** - * @hidden - */ - - var reset = "border:0px;padding:0px;"; - /** - * @hidden - */ - - var hidden = "clip:rect(0px,0px,0px,0px);height:1px;margin-bottom:-1px;margin-right:-1px;overflow:hidden;position:absolute;white-space:nowrap;width:1px"; - /** - * @hidden - */ - - var update$1 = function update(e, id) { - e.id = id; - e.setAttribute("role", "status"); - e.setAttribute("aria-live", "polite"); - e.setAttribute("aria-atomic", "true"); - return e; - }; - /** - * Generates a screen reader compatible live area for announcements - * - * @hidden - */ - - - var announcer = function announcer(_ref) { - var document = _ref.document, - idA = _ref.idA, - idB = _ref.idB; - var container = document.createElement("div"); - container.setAttribute("style", reset + hidden); - var a = update$1(document.createElement("div"), idA); - var b = update$1(document.createElement("div"), idB); - container.appendChild(a); - container.appendChild(b); - var A = true; - var announce = debounce_1(function (message) { - var announcer = A ? a : b; - var backup = A ? b : a; - A = !A; - announcer.textContent = message; - backup.textContent = ""; - }, 1500, {}); - return { - container: container, - announce: announce - }; - }; - - var defaultContexts = { - GBR: { - name: "United Kingdom", - icon: "πŸ‡¬πŸ‡§" - }, - USA: { - name: "United States", - icon: "πŸ‡ΊπŸ‡Έ" - } - }; - var toContextList = function toContextList(contexts, restrictCountries) { - var result = []; - var codes = Object.keys(contexts); - - var _loop = function _loop() { - var code = _codes[_i]; - if (restrictCountries.length > 0 && !restrictCountries.some(function (e) { - return e === code; - })) return "continue"; - var _contexts$code = contexts[code], - name = _contexts$code.name, - icon = _contexts$code.icon; - result.push({ - code: code, - name: name, - icon: icon - }); - }; - - for (var _i = 0, _codes = codes; _i < _codes.length; _i++) { - var _ret = _loop(); - - if (_ret === "continue") continue; - } - - result.sort(function (b, a) { - return b.name.localeCompare(a.name); - }); - return result; - }; - - function ownKeys$d(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - - function _objectSpread$d(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$d(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$d(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - - /** - * @module Client - * - * @description HTTP API Client - */ - - /** - * Default configuration - */ - var defaults$d = { - tls: true, - api_key: "", - baseUrl: "api.ideal-postcodes.co.uk", - version: "v1", - strictAuthorisation: false, - timeout: 10000, - header: { - Accept: "application/json", - "Content-Type": "application/json" - }, - tags: [], - agent: {} - }; - /** - * Client Class - */ - - var Client$3 = /*#__PURE__*/function () { - function Client(config) { - _classCallCheck(this, Client); - - this.config = _objectSpread$d(_objectSpread$d({}, defaults$d), config); - this.config.header = _objectSpread$d(_objectSpread$d({}, defaults$d.header), config.header && config.header); - } - /** - * Return base URL for API requests - */ - - - _createClass(Client, [{ - key: "url", - value: function url() { - var _this$config = this.config, - baseUrl = _this$config.baseUrl, - version = _this$config.version; - return "".concat(this.protocol(), "://").concat(baseUrl, "/").concat(version); - } - }, { - key: "protocol", - value: function protocol() { - return this.config.tls ? "https" : "http"; - } - }]); - - return Client; - }(); - - function ownKeys$c(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - - function _objectSpread$c(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$c(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$c(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - - /** - * @module Utils - */ - - /** - * toQuery - * - * Shallow copies object while omitting undefined attributes - */ - var toStringMap$1 = function toStringMap(optional) { - if (optional === undefined) return {}; - return Object.keys(optional).reduce(function (result, key) { - var value = optional[key]; - var reduce = reduceStringMap$1(value); - if (reduce.length > 0) result[key] = reduce; - return result; - }, {}); - }; - - var isString$4 = function isString(i) { - return typeof i === "string"; - }; - - var isArray$3 = function isArray(i) { - return Array.isArray(i); - }; - - var reduceStringMap$1 = function reduceStringMap(value) { - var result = []; - - if (isArray$3(value)) { - value.forEach(function (val) { - if (isNumber$3(val)) result.push(val.toString()); - if (isString$4(val)) result.push(val); - }); - return result.join(","); - } - - if (isNumber$3(value)) return value.toString(); - if (isString$4(value)) return value; - return ""; - }; - - var isNumber$3 = function isNumber(n) { - return typeof n === "number"; - }; - /** - * toTimeout - * - * Returns timeout value from request object. Delegates to default client - * timeout if not specified - */ - - - var toTimeout$1 = function toTimeout(_ref, client) { - var timeout = _ref.timeout; - if (isNumber$3(timeout)) return timeout; - return client.config.timeout; - }; - /** - * toHeader - * - * Extracts HTTP Header object from request and client default headers - * - * Precendence is given to request specific headers - */ - - var toHeader$3 = function toHeader(_ref2, client) { - var _ref2$header = _ref2.header, - header = _ref2$header === void 0 ? {} : _ref2$header; - return _objectSpread$c(_objectSpread$c({}, client.config.header), toStringMap$1(header)); - }; - - function _assertThisInitialized(self) { - if (self === void 0) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - } - - return self; - } - - function _setPrototypeOf(o, p) { - _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { - o.__proto__ = p; - return o; - }; - - return _setPrototypeOf(o, p); - } - - function _inherits(subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError("Super expression must either be null or a function"); - } - - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - writable: true, - configurable: true - } - }); - if (superClass) _setPrototypeOf(subClass, superClass); - } - - function _possibleConstructorReturn(self, call) { - if (call && (_typeof(call) === "object" || typeof call === "function")) { - return call; - } else if (call !== void 0) { - throw new TypeError("Derived constructors may only return object or undefined"); - } - - return _assertThisInitialized(self); - } - - function _getPrototypeOf(o) { - _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { - return o.__proto__ || Object.getPrototypeOf(o); - }; - return _getPrototypeOf(o); - } - - function _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; - } - - function _isNativeReflectConstruct$4() { - if (typeof Reflect === "undefined" || !Reflect.construct) return false; - if (Reflect.construct.sham) return false; - if (typeof Proxy === "function") return true; - - try { - Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); - return true; - } catch (e) { - return false; - } - } - - function _construct(Parent, args, Class) { - if (_isNativeReflectConstruct$4()) { - _construct = Reflect.construct; - } else { - _construct = function _construct(Parent, args, Class) { - var a = [null]; - a.push.apply(a, args); - var Constructor = Function.bind.apply(Parent, a); - var instance = new Constructor(); - if (Class) _setPrototypeOf(instance, Class.prototype); - return instance; - }; - } - - return _construct.apply(null, arguments); - } - - function _wrapNativeSuper(Class) { - var _cache = typeof Map === "function" ? new Map() : undefined; - - _wrapNativeSuper = function _wrapNativeSuper(Class) { - if (Class === null || !_isNativeFunction(Class)) return Class; - - if (typeof Class !== "function") { - throw new TypeError("Super expression must either be null or a function"); - } - - if (typeof _cache !== "undefined") { - if (_cache.has(Class)) return _cache.get(Class); - - _cache.set(Class, Wrapper); - } - - function Wrapper() { - return _construct(Class, arguments, _getPrototypeOf(this).constructor); - } - - Wrapper.prototype = Object.create(Class.prototype, { - constructor: { - value: Wrapper, - enumerable: false, - writable: true, - configurable: true - } - }); - return _setPrototypeOf(Wrapper, Class); - }; - - return _wrapNativeSuper(Class); - } - - function _createSuper$3(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$3(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } - - function _isNativeReflectConstruct$3() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } - - /** - * @module Errors - * - * @description Exports error classes which may be returned by this client - */ - // Take note of https://github.com/Microsoft/TypeScript/issues/13965 - - /** - * IdealPostcodesError - * - * Base error class for all API responses that return an error. This class - * is used where a JSON body is not provided or invalid - * E.g. 503 rate limit response, JSON parse failure response - */ - var IdealPostcodesError$3 = /*#__PURE__*/function (_Error) { - _inherits(IdealPostcodesError, _Error); - - var _super = _createSuper$3(IdealPostcodesError); - - /** - * Instantiate IdealPostcodesError - */ - function IdealPostcodesError(options) { - var _this; - - _classCallCheck(this, IdealPostcodesError); - - var trueProto = (this instanceof IdealPostcodesError ? this.constructor : void 0).prototype; - _this = _super.call(this); - _this.__proto__ = trueProto; - var message = options.message, - httpStatus = options.httpStatus, - _options$metadata = options.metadata, - metadata = _options$metadata === void 0 ? {} : _options$metadata; - _this.message = message; - _this.name = "Ideal Postcodes Error"; - _this.httpStatus = httpStatus; - _this.metadata = metadata; - - if (Error.captureStackTrace) { - Error.captureStackTrace(_assertThisInitialized(_this), IdealPostcodesError); - } - - return _this; - } - - return IdealPostcodesError; - }( /*#__PURE__*/_wrapNativeSuper(Error)); - /** - * IdpcApiError - * - * Base error class for API responses with a JSON body. Typically a subclass - * will be used to capture the error category (e.g. 400, 401, 500, etc) - */ - - var IdpcApiError$1 = /*#__PURE__*/function (_IdealPostcodesError) { - _inherits(IdpcApiError, _IdealPostcodesError); - - var _super2 = _createSuper$3(IdpcApiError); - - /** - * Returns an API error instance - */ - function IdpcApiError(httpResponse) { - var _this2; - - _classCallCheck(this, IdpcApiError); - - _this2 = _super2.call(this, { - httpStatus: httpResponse.httpStatus, - message: httpResponse.body.message - }); - _this2.response = httpResponse; - return _this2; - } - - return IdpcApiError; - }(IdealPostcodesError$3); - /** - * IdpcBadRequestError - * - * Captures API responses that return a 400 (Bad Request Error) response - * - * Examples include: - * - Invalid syntax submitted - * - Invalid date range submitted - * - Invalid tag submitted - */ - - var IdpcBadRequestError$1 = /*#__PURE__*/function (_IdpcApiError) { - _inherits(IdpcBadRequestError, _IdpcApiError); - - var _super3 = _createSuper$3(IdpcBadRequestError); - - function IdpcBadRequestError() { - _classCallCheck(this, IdpcBadRequestError); - - return _super3.apply(this, arguments); - } - - return IdpcBadRequestError; - }(IdpcApiError$1); - /** - * IdpcUnauthorisedError - * - * Captures API responses that return a 401 (Unauthorised) response - * - * Examples include: - * - Invalid api_key - * - Invalid user_token - * - Invalid licensee - */ - - var IdpcUnauthorisedError$1 = /*#__PURE__*/function (_IdpcApiError2) { - _inherits(IdpcUnauthorisedError, _IdpcApiError2); - - var _super4 = _createSuper$3(IdpcUnauthorisedError); - - function IdpcUnauthorisedError() { - _classCallCheck(this, IdpcUnauthorisedError); - - return _super4.apply(this, arguments); - } - - return IdpcUnauthorisedError; - }(IdpcApiError$1); - /** - * IpdcInvalidKeyError - * - * Invalid API Key presented for request - */ - - var IdpcInvalidKeyError$1 = /*#__PURE__*/function (_IdpcUnauthorisedErro) { - _inherits(IdpcInvalidKeyError, _IdpcUnauthorisedErro); - - var _super5 = _createSuper$3(IdpcInvalidKeyError); - - function IdpcInvalidKeyError() { - _classCallCheck(this, IdpcInvalidKeyError); - - return _super5.apply(this, arguments); - } - - return IdpcInvalidKeyError; - }(IdpcUnauthorisedError$1); - /** - * IdpcRequestFailedError - * - * Captures API responses that return a 402 (Request Failed) response - * - * Examples include: - * - Key balance depleted - * - Daily key limit reached - */ - - var IdpcRequestFailedError$1 = /*#__PURE__*/function (_IdpcApiError3) { - _inherits(IdpcRequestFailedError, _IdpcApiError3); - - var _super6 = _createSuper$3(IdpcRequestFailedError); - - function IdpcRequestFailedError() { - _classCallCheck(this, IdpcRequestFailedError); - - return _super6.apply(this, arguments); - } - - return IdpcRequestFailedError; - }(IdpcApiError$1); - /** - * IdpcBalanceDepleted - * - * Balance on key has been depleted - */ - - var IdpcBalanceDepletedError$1 = /*#__PURE__*/function (_IdpcRequestFailedErr) { - _inherits(IdpcBalanceDepletedError, _IdpcRequestFailedErr); - - var _super7 = _createSuper$3(IdpcBalanceDepletedError); - - function IdpcBalanceDepletedError() { - _classCallCheck(this, IdpcBalanceDepletedError); - - return _super7.apply(this, arguments); - } - - return IdpcBalanceDepletedError; - }(IdpcRequestFailedError$1); - /** - * IdpcLimitReachedError - * - * Limit reached. One of your lookup limits has been breached for today. This - * could either be your total daily limit on your key or the individual IP - * limit. You can either wait for for the limit to reset (after a day) or - * manually disable or increase your limit. - */ - - var IdpcLimitReachedError$1 = /*#__PURE__*/function (_IdpcRequestFailedErr2) { - _inherits(IdpcLimitReachedError, _IdpcRequestFailedErr2); - - var _super8 = _createSuper$3(IdpcLimitReachedError); - - function IdpcLimitReachedError() { - _classCallCheck(this, IdpcLimitReachedError); - - return _super8.apply(this, arguments); - } - - return IdpcLimitReachedError; - }(IdpcRequestFailedError$1); - /** - * IdpcResourceNotFoundError - * - * Captures API responses that return a 404 (Resource Not Found) response - * - * Examples include: - * - Postcode not found - * - UDPRN not found - * - Key not found - */ - - var IdpcResourceNotFoundError$1 = /*#__PURE__*/function (_IdpcApiError4) { - _inherits(IdpcResourceNotFoundError, _IdpcApiError4); - - var _super9 = _createSuper$3(IdpcResourceNotFoundError); - - function IdpcResourceNotFoundError() { - _classCallCheck(this, IdpcResourceNotFoundError); - - return _super9.apply(this, arguments); - } - - return IdpcResourceNotFoundError; - }(IdpcApiError$1); - /** - * IdpcPostcodeNotFoundError - * - * Requested postcode does not exist - */ - - var IdpcPostcodeNotFoundError$1 = /*#__PURE__*/function (_IdpcResourceNotFound) { - _inherits(IdpcPostcodeNotFoundError, _IdpcResourceNotFound); - - var _super10 = _createSuper$3(IdpcPostcodeNotFoundError); - - function IdpcPostcodeNotFoundError() { - _classCallCheck(this, IdpcPostcodeNotFoundError); - - return _super10.apply(this, arguments); - } - - return IdpcPostcodeNotFoundError; - }(IdpcResourceNotFoundError$1); - /** - * IdpcKeyNotFoundError - * - * Requested API Key does not exist - */ - - var IdpcKeyNotFoundError$1 = /*#__PURE__*/function (_IdpcResourceNotFound2) { - _inherits(IdpcKeyNotFoundError, _IdpcResourceNotFound2); - - var _super11 = _createSuper$3(IdpcKeyNotFoundError); - - function IdpcKeyNotFoundError() { - _classCallCheck(this, IdpcKeyNotFoundError); - - return _super11.apply(this, arguments); - } - - return IdpcKeyNotFoundError; - }(IdpcResourceNotFoundError$1); - /** - * IdpcUdprnNotFoundError - * - * Requested UDPRN does not exist - */ - - var IdpcUdprnNotFoundError$1 = /*#__PURE__*/function (_IdpcResourceNotFound3) { - _inherits(IdpcUdprnNotFoundError, _IdpcResourceNotFound3); - - var _super12 = _createSuper$3(IdpcUdprnNotFoundError); - - function IdpcUdprnNotFoundError() { - _classCallCheck(this, IdpcUdprnNotFoundError); - - return _super12.apply(this, arguments); - } - - return IdpcUdprnNotFoundError; - }(IdpcResourceNotFoundError$1); - /** - * IdpcUmprnNotFoundError - * - * Requested UMPRN does not exist - */ - - var IdpcUmprnNotFoundError$1 = /*#__PURE__*/function (_IdpcResourceNotFound4) { - _inherits(IdpcUmprnNotFoundError, _IdpcResourceNotFound4); - - var _super13 = _createSuper$3(IdpcUmprnNotFoundError); - - function IdpcUmprnNotFoundError() { - _classCallCheck(this, IdpcUmprnNotFoundError); - - return _super13.apply(this, arguments); - } - - return IdpcUmprnNotFoundError; - }(IdpcResourceNotFoundError$1); - /** - * IdpcServerError - * - * Captures API responses that return a 500 (Server Error) response - */ - - var IdpcServerError$1 = /*#__PURE__*/function (_IdpcApiError5) { - _inherits(IdpcServerError, _IdpcApiError5); - - var _super14 = _createSuper$3(IdpcServerError); - - function IdpcServerError() { - _classCallCheck(this, IdpcServerError); - - return _super14.apply(this, arguments); - } - - return IdpcServerError; - }(IdpcApiError$1); // 200 Responses - - var OK$1 = 200; // 300 Responses - - var REDIRECT$1 = 300; // 400 Responses - - var BAD_REQUEST$1 = 400; // 401 Responses - - var UNAUTHORISED$1 = 401; - var INVALID_KEY$1 = 4010; // 402 Responses - - var PAYMENT_REQUIRED$1 = 402; - var BALANCE_DEPLETED$1 = 4020; - var LIMIT_REACHED$1 = 4021; // 404 Responses - - var NOT_FOUND$1 = 404; - var POSTCODE_NOT_FOUND$1 = 4040; - var KEY_NOT_FOUND$1 = 4042; - var UDPRN_NOT_FOUND$1 = 4044; - var UMPRN_NOT_FOUND$1 = 4046; // 500 Responses - - var SERVER_ERROR$1 = 500; - - var isSuccess$1 = function isSuccess(code) { - if (code < OK$1) return false; - if (code >= REDIRECT$1) return false; - return true; - }; - - var isObject$3 = function isObject(o) { - if (o === null) return false; - if (_typeof(o) !== "object") return false; - return true; - }; - - var isErrorResponse$1 = function isErrorResponse(body) { - if (!isObject$3(body)) return false; - if (typeof body.message !== "string") return false; - if (typeof body.code !== "number") return false; - return true; - }; - /** - * parse - * - * Parses API responses and returns an error for non 2xx responses - * - * Upon detecting an error an instance of IdealPostcodesError is returned - */ - - - var parse$1 = function parse(response) { - var httpStatus = response.httpStatus, - body = response.body; - if (isSuccess$1(httpStatus)) return; - - if (isErrorResponse$1(body)) { - // Test for specific API errors of interest - var code = body.code; - if (code === INVALID_KEY$1) return new IdpcInvalidKeyError$1(response); - if (code === POSTCODE_NOT_FOUND$1) return new IdpcPostcodeNotFoundError$1(response); - if (code === KEY_NOT_FOUND$1) return new IdpcKeyNotFoundError$1(response); - if (code === UDPRN_NOT_FOUND$1) return new IdpcUdprnNotFoundError$1(response); - if (code === UMPRN_NOT_FOUND$1) return new IdpcUmprnNotFoundError$1(response); - if (code === BALANCE_DEPLETED$1) return new IdpcBalanceDepletedError$1(response); - if (code === LIMIT_REACHED$1) return new IdpcLimitReachedError$1(response); // If no API errors of interest detected, fall back to http status code - - if (httpStatus === NOT_FOUND$1) return new IdpcResourceNotFoundError$1(response); - if (httpStatus === BAD_REQUEST$1) return new IdpcBadRequestError$1(response); - if (httpStatus === PAYMENT_REQUIRED$1) return new IdpcRequestFailedError$1(response); - if (httpStatus === UNAUTHORISED$1) return new IdpcUnauthorisedError$1(response); - if (httpStatus === SERVER_ERROR$1) return new IdpcServerError$1(response); - } // Generate generic error (backstop) - - - return new IdealPostcodesError$3({ - httpStatus: httpStatus, - message: JSON.stringify(body) - }); - }; - - var toRetrieveUrl$1 = function toRetrieveUrl(options, id) { - return [options.client.url(), options.resource, encodeURIComponent(id), options.action].filter(function (e) { - return e !== undefined; - }).join("/"); - }; - - var retrieveMethod$1 = function retrieveMethod(options) { - var client = options.client; - return function (id, request) { - return client.config.agent.http({ - method: "GET", - url: toRetrieveUrl$1(options, id), - query: toStringMap$1(request.query), - header: toHeader$3(request, client), - timeout: toTimeout$1(request, client) - }).then(function (response) { - var error = parse$1(response); - if (error) throw error; - return response; - }); - }; - }; - var listMethod$1 = function listMethod(options) { - var client = options.client, - resource = options.resource; - return function (request) { - return client.config.agent.http({ - method: "GET", - url: "".concat(client.url(), "/").concat(resource), - query: toStringMap$1(request.query), - header: toHeader$3(request, client), - timeout: toTimeout$1(request, client) - }).then(function (response) { - var error = parse$1(response); - if (error) throw error; - return response; - }); - }; - }; - - var resource$4 = "keys"; - var retrieve$2 = function retrieve(client, apiKey, request) { - return retrieveMethod$1({ - resource: resource$4, - client: client - })(apiKey, request); - }; - - /** - * @module Helper Methods - */ - /** - * Check Key Availability - * - * Checks if a key can bey used - * - * [API Documentation for /keys]()https://ideal-postcodes.co.uk/documentation/keys#key) - */ - - var checkKeyUsability$1 = function checkKeyUsability(options) { - var client = options.client, - timeout = options.timeout; - var api_key = options.api_key || options.client.config.api_key; - var licensee = options.licensee; - var query; - - if (licensee === undefined) { - query = {}; - } else { - query = { - licensee: licensee - }; - } - - var queryOptions = { - query: query, - header: {} - }; - if (timeout !== undefined) queryOptions.timeout = timeout; - return retrieve$2(client, api_key, queryOptions).then(function (response) { - return response.body.result; - }); // Assert that we're retrieving public key information as no user_token provided - }; - - var resource$3 = "autocomplete/addresses"; - var list$1 = function list(client, request) { - return listMethod$1({ - resource: resource$3, - client: client - })(request); - }; // Resolves address to the GBR format - - var gbr = function gbr(client, id, request) { - return retrieveMethod$1({ - resource: resource$3, - client: client, - action: "gbr" - })(id, request); - }; - - var axios$5 = {exports: {}}; - - var bind$9 = function bind(fn, thisArg) { - return function wrap() { - var args = new Array(arguments.length); - - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } - - return fn.apply(thisArg, args); - }; - }; - - var bind$8 = bind$9; // utils is a library of generic helper functions non-specific to axios - - var toString$1 = Object.prototype.toString; - /** - * Determine if a value is an Array - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an Array, otherwise false - */ - - function isArray$2(val) { - return toString$1.call(val) === '[object Array]'; - } - /** - * Determine if a value is undefined - * - * @param {Object} val The value to test - * @returns {boolean} True if the value is undefined, otherwise false - */ - - - function isUndefined$1(val) { - return typeof val === 'undefined'; - } - /** - * Determine if a value is a Buffer - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Buffer, otherwise false - */ - - - function isBuffer$1(val) { - return val !== null && !isUndefined$1(val) && val.constructor !== null && !isUndefined$1(val.constructor) && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); - } - /** - * Determine if a value is an ArrayBuffer - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an ArrayBuffer, otherwise false - */ - - - function isArrayBuffer$1(val) { - return toString$1.call(val) === '[object ArrayBuffer]'; - } - /** - * Determine if a value is a FormData - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an FormData, otherwise false - */ - - - function isFormData$1(val) { - return typeof FormData !== 'undefined' && val instanceof FormData; - } - /** - * Determine if a value is a view on an ArrayBuffer - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false - */ - - - function isArrayBufferView$1(val) { - var result; - - if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) { - result = ArrayBuffer.isView(val); - } else { - result = val && val.buffer && val.buffer instanceof ArrayBuffer; - } - - return result; - } - /** - * Determine if a value is a String - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a String, otherwise false - */ - - - function isString$3(val) { - return typeof val === 'string'; - } - /** - * Determine if a value is a Number - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Number, otherwise false - */ - - - function isNumber$2(val) { - return typeof val === 'number'; - } - /** - * Determine if a value is an Object - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an Object, otherwise false - */ - - - function isObject$2(val) { - return val !== null && _typeof(val) === 'object'; - } - /** - * Determine if a value is a plain Object - * - * @param {Object} val The value to test - * @return {boolean} True if value is a plain Object, otherwise false - */ - - - function isPlainObject$1(val) { - if (toString$1.call(val) !== '[object Object]') { - return false; - } - - var prototype = Object.getPrototypeOf(val); - return prototype === null || prototype === Object.prototype; - } - /** - * Determine if a value is a Date - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Date, otherwise false - */ - - - function isDate$1(val) { - return toString$1.call(val) === '[object Date]'; - } - /** - * Determine if a value is a File - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a File, otherwise false - */ - - - function isFile$1(val) { - return toString$1.call(val) === '[object File]'; - } - /** - * Determine if a value is a Blob - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Blob, otherwise false - */ - - - function isBlob$1(val) { - return toString$1.call(val) === '[object Blob]'; - } - /** - * Determine if a value is a Function - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Function, otherwise false - */ - - - function isFunction$1(val) { - return toString$1.call(val) === '[object Function]'; - } - /** - * Determine if a value is a Stream - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Stream, otherwise false - */ - - - function isStream$1(val) { - return isObject$2(val) && isFunction$1(val.pipe); - } - /** - * Determine if a value is a URLSearchParams object - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a URLSearchParams object, otherwise false - */ - - - function isURLSearchParams$1(val) { - return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; - } - /** - * Trim excess whitespace off the beginning and end of a string - * - * @param {String} str The String to trim - * @returns {String} The String freed of excess whitespace - */ - - - function trim$1(str) { - return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, ''); - } - /** - * Determine if we're running in a standard browser environment - * - * This allows axios to run in a web worker, and react-native. - * Both environments support XMLHttpRequest, but not fully standard globals. - * - * web workers: - * typeof window -> undefined - * typeof document -> undefined - * - * react-native: - * navigator.product -> 'ReactNative' - * nativescript - * navigator.product -> 'NativeScript' or 'NS' - */ - - - function isStandardBrowserEnv$1() { - if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || navigator.product === 'NativeScript' || navigator.product === 'NS')) { - return false; - } - - return typeof window !== 'undefined' && typeof document !== 'undefined'; - } - /** - * Iterate over an Array or an Object invoking a function for each item. - * - * If `obj` is an Array callback will be called passing - * the value, index, and complete array for each item. - * - * If 'obj' is an Object callback will be called passing - * the value, key, and complete object for each property. - * - * @param {Object|Array} obj The object to iterate - * @param {Function} fn The callback to invoke for each item - */ - - - function forEach$1(obj, fn) { - // Don't bother if no value provided - if (obj === null || typeof obj === 'undefined') { - return; - } // Force an array if not already something iterable - - - if (_typeof(obj) !== 'object') { - /*eslint no-param-reassign:0*/ - obj = [obj]; - } - - if (isArray$2(obj)) { - // Iterate over array values - for (var i = 0, l = obj.length; i < l; i++) { - fn.call(null, obj[i], i, obj); - } - } else { - // Iterate over object keys - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - fn.call(null, obj[key], key, obj); - } - } - } - } - /** - * Accepts varargs expecting each argument to be an object, then - * immutably merges the properties of each object and returns result. - * - * When multiple objects contain the same key the later object in - * the arguments list will take precedence. - * - * Example: - * - * ```js - * var result = merge({foo: 123}, {foo: 456}); - * console.log(result.foo); // outputs 456 - * ``` - * - * @param {Object} obj1 Object to merge - * @returns {Object} Result of all merge properties - */ - - - function merge$1() { - var result = {}; - - function assignValue(val, key) { - if (isPlainObject$1(result[key]) && isPlainObject$1(val)) { - result[key] = merge$1(result[key], val); - } else if (isPlainObject$1(val)) { - result[key] = merge$1({}, val); - } else if (isArray$2(val)) { - result[key] = val.slice(); - } else { - result[key] = val; - } - } - - for (var i = 0, l = arguments.length; i < l; i++) { - forEach$1(arguments[i], assignValue); - } - - return result; - } - /** - * Extends object a by mutably adding to it the properties of object b. - * - * @param {Object} a The object to be extended - * @param {Object} b The object to copy properties from - * @param {Object} thisArg The object to bind function to - * @return {Object} The resulting value of object a - */ - - - function extend$1(a, b, thisArg) { - forEach$1(b, function assignValue(val, key) { - if (thisArg && typeof val === 'function') { - a[key] = bind$8(val, thisArg); - } else { - a[key] = val; - } - }); - return a; - } - /** - * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) - * - * @param {string} content with BOM - * @return {string} content value without BOM - */ - - - function stripBOM$1(content) { - if (content.charCodeAt(0) === 0xFEFF) { - content = content.slice(1); - } - - return content; - } - - var utils$r = { - isArray: isArray$2, - isArrayBuffer: isArrayBuffer$1, - isBuffer: isBuffer$1, - isFormData: isFormData$1, - isArrayBufferView: isArrayBufferView$1, - isString: isString$3, - isNumber: isNumber$2, - isObject: isObject$2, - isPlainObject: isPlainObject$1, - isUndefined: isUndefined$1, - isDate: isDate$1, - isFile: isFile$1, - isBlob: isBlob$1, - isFunction: isFunction$1, - isStream: isStream$1, - isURLSearchParams: isURLSearchParams$1, - isStandardBrowserEnv: isStandardBrowserEnv$1, - forEach: forEach$1, - merge: merge$1, - extend: extend$1, - trim: trim$1, - stripBOM: stripBOM$1 - }; - - var utils$q = utils$r; - - function encode$1(val) { - return encodeURIComponent(val).replace(/%3A/gi, ':').replace(/%24/g, '$').replace(/%2C/gi, ',').replace(/%20/g, '+').replace(/%5B/gi, '[').replace(/%5D/gi, ']'); - } - /** - * Build a URL by appending params to the end - * - * @param {string} url The base of the url (e.g., http://www.google.com) - * @param {object} [params] The params to be appended - * @returns {string} The formatted url - */ - - - var buildURL$5 = function buildURL(url, params, paramsSerializer) { - /*eslint no-param-reassign:0*/ - if (!params) { - return url; - } - - var serializedParams; - - if (paramsSerializer) { - serializedParams = paramsSerializer(params); - } else if (utils$q.isURLSearchParams(params)) { - serializedParams = params.toString(); - } else { - var parts = []; - utils$q.forEach(params, function serialize(val, key) { - if (val === null || typeof val === 'undefined') { - return; - } - - if (utils$q.isArray(val)) { - key = key + '[]'; - } else { - val = [val]; - } - - utils$q.forEach(val, function parseValue(v) { - if (utils$q.isDate(v)) { - v = v.toISOString(); - } else if (utils$q.isObject(v)) { - v = JSON.stringify(v); - } - - parts.push(encode$1(key) + '=' + encode$1(v)); - }); - }); - serializedParams = parts.join('&'); - } - - if (serializedParams) { - var hashmarkIndex = url.indexOf('#'); - - if (hashmarkIndex !== -1) { - url = url.slice(0, hashmarkIndex); - } - - url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; - } - - return url; - }; - - var utils$p = utils$r; - - function InterceptorManager$3() { - this.handlers = []; - } - /** - * Add a new interceptor to the stack - * - * @param {Function} fulfilled The function to handle `then` for a `Promise` - * @param {Function} rejected The function to handle `reject` for a `Promise` - * - * @return {Number} An ID used to remove interceptor later - */ - - - InterceptorManager$3.prototype.use = function use(fulfilled, rejected, options) { - this.handlers.push({ - fulfilled: fulfilled, - rejected: rejected, - synchronous: options ? options.synchronous : false, - runWhen: options ? options.runWhen : null - }); - return this.handlers.length - 1; - }; - /** - * Remove an interceptor from the stack - * - * @param {Number} id The ID that was returned by `use` - */ - - - InterceptorManager$3.prototype.eject = function eject(id) { - if (this.handlers[id]) { - this.handlers[id] = null; - } - }; - /** - * Iterate over all the registered interceptors - * - * This method is particularly useful for skipping over any - * interceptors that may have become `null` calling `eject`. - * - * @param {Function} fn The function to call for each interceptor - */ - - - InterceptorManager$3.prototype.forEach = function forEach(fn) { - utils$p.forEach(this.handlers, function forEachHandler(h) { - if (h !== null) { - fn(h); - } - }); - }; - - var InterceptorManager_1$1 = InterceptorManager$3; - - var utils$o = utils$r; - - var normalizeHeaderName$3 = function normalizeHeaderName(headers, normalizedName) { - utils$o.forEach(headers, function processHeader(value, name) { - if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { - headers[normalizedName] = value; - delete headers[name]; - } - }); - }; - - /** - * Update an Error with the specified config, error code, and response. - * - * @param {Error} error The error to update. - * @param {Object} config The config. - * @param {string} [code] The error code (for example, 'ECONNABORTED'). - * @param {Object} [request] The request. - * @param {Object} [response] The response. - * @returns {Error} The error. - */ - - - var enhanceError$5 = function enhanceError(error, config, code, request, response) { - error.config = config; - - if (code) { - error.code = code; - } - - error.request = request; - error.response = response; - error.isAxiosError = true; - - error.toJSON = function toJSON() { - return { - // Standard - message: this.message, - name: this.name, - // Microsoft - description: this.description, - number: this.number, - // Mozilla - fileName: this.fileName, - lineNumber: this.lineNumber, - columnNumber: this.columnNumber, - stack: this.stack, - // Axios - config: this.config, - code: this.code, - status: this.response && this.response.status ? this.response.status : null - }; - }; - - return error; - }; - - var enhanceError$4 = enhanceError$5; - /** - * Create an Error with the specified message, config, error code, request and response. - * - * @param {string} message The error message. - * @param {Object} config The config. - * @param {string} [code] The error code (for example, 'ECONNABORTED'). - * @param {Object} [request] The request. - * @param {Object} [response] The response. - * @returns {Error} The created error. - */ - - var createError$5 = function createError(message, config, code, request, response) { - var error = new Error(message); - return enhanceError$4(error, config, code, request, response); - }; - - var createError$4 = createError$5; - /** - * Resolve or reject a Promise based on response status. - * - * @param {Function} resolve A function that resolves the promise. - * @param {Function} reject A function that rejects the promise. - * @param {object} response The response. - */ - - var settle$3 = function settle(resolve, reject, response) { - var validateStatus = response.config.validateStatus; - - if (!response.status || !validateStatus || validateStatus(response.status)) { - resolve(response); - } else { - reject(createError$4('Request failed with status code ' + response.status, response.config, null, response.request, response)); - } - }; - - var utils$n = utils$r; - var cookies$3 = utils$n.isStandardBrowserEnv() ? // Standard browser envs support document.cookie - function standardBrowserEnv() { - return { - write: function write(name, value, expires, path, domain, secure) { - var cookie = []; - cookie.push(name + '=' + encodeURIComponent(value)); - - if (utils$n.isNumber(expires)) { - cookie.push('expires=' + new Date(expires).toGMTString()); - } - - if (utils$n.isString(path)) { - cookie.push('path=' + path); - } - - if (utils$n.isString(domain)) { - cookie.push('domain=' + domain); - } - - if (secure === true) { - cookie.push('secure'); - } - - document.cookie = cookie.join('; '); - }, - read: function read(name) { - var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); - return match ? decodeURIComponent(match[3]) : null; - }, - remove: function remove(name) { - this.write(name, '', Date.now() - 86400000); - } - }; - }() : // Non standard browser env (web workers, react-native) lack needed support. - function nonStandardBrowserEnv() { - return { - write: function write() {}, - read: function read() { - return null; - }, - remove: function remove() {} - }; - }(); - - /** - * Determines whether the specified URL is absolute - * - * @param {string} url The URL to test - * @returns {boolean} True if the specified URL is absolute, otherwise false - */ - - - var isAbsoluteURL$3 = function isAbsoluteURL(url) { - // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). - // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed - // by any combination of letters, digits, plus, period, or hyphen. - return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); - }; - - /** - * Creates a new URL by combining the specified URLs - * - * @param {string} baseURL The base URL - * @param {string} relativeURL The relative URL - * @returns {string} The combined URL - */ - - - var combineURLs$3 = function combineURLs(baseURL, relativeURL) { - return relativeURL ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') : baseURL; - }; - - var isAbsoluteURL$2 = isAbsoluteURL$3; - var combineURLs$2 = combineURLs$3; - /** - * Creates a new URL by combining the baseURL with the requestedURL, - * only when the requestedURL is not already an absolute URL. - * If the requestURL is absolute, this function returns the requestedURL untouched. - * - * @param {string} baseURL The base URL - * @param {string} requestedURL Absolute or relative URL to combine - * @returns {string} The combined full path - */ - - var buildFullPath$3 = function buildFullPath(baseURL, requestedURL) { - if (baseURL && !isAbsoluteURL$2(requestedURL)) { - return combineURLs$2(baseURL, requestedURL); - } - - return requestedURL; - }; - - var utils$m = utils$r; // Headers whose duplicates are ignored by node - // c.f. https://nodejs.org/api/http.html#http_message_headers - - var ignoreDuplicateOf$1 = ['age', 'authorization', 'content-length', 'content-type', 'etag', 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', 'last-modified', 'location', 'max-forwards', 'proxy-authorization', 'referer', 'retry-after', 'user-agent']; - /** - * Parse headers into an object - * - * ``` - * Date: Wed, 27 Aug 2014 08:58:49 GMT - * Content-Type: application/json - * Connection: keep-alive - * Transfer-Encoding: chunked - * ``` - * - * @param {String} headers Headers needing to be parsed - * @returns {Object} Headers parsed into an object - */ - - var parseHeaders$3 = function parseHeaders(headers) { - var parsed = {}; - var key; - var val; - var i; - - if (!headers) { - return parsed; - } - - utils$m.forEach(headers.split('\n'), function parser(line) { - i = line.indexOf(':'); - key = utils$m.trim(line.substr(0, i)).toLowerCase(); - val = utils$m.trim(line.substr(i + 1)); - - if (key) { - if (parsed[key] && ignoreDuplicateOf$1.indexOf(key) >= 0) { - return; - } - - if (key === 'set-cookie') { - parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); - } else { - parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; - } - } - }); - return parsed; - }; - - var utils$l = utils$r; - var isURLSameOrigin$3 = utils$l.isStandardBrowserEnv() ? // Standard browser envs have full support of the APIs needed to test - // whether the request URL is of the same origin as current location. - function standardBrowserEnv() { - var msie = /(msie|trident)/i.test(navigator.userAgent); - var urlParsingNode = document.createElement('a'); - var originURL; - /** - * Parse a URL to discover it's components - * - * @param {String} url The URL to be parsed - * @returns {Object} - */ - - function resolveURL(url) { - var href = url; - - if (msie) { - // IE needs attribute set twice to normalize properties - urlParsingNode.setAttribute('href', href); - href = urlParsingNode.href; - } - - urlParsingNode.setAttribute('href', href); // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils - - return { - href: urlParsingNode.href, - protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', - host: urlParsingNode.host, - search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', - hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', - hostname: urlParsingNode.hostname, - port: urlParsingNode.port, - pathname: urlParsingNode.pathname.charAt(0) === '/' ? urlParsingNode.pathname : '/' + urlParsingNode.pathname - }; - } - - originURL = resolveURL(window.location.href); - /** - * Determine if a URL shares the same origin as the current location - * - * @param {String} requestURL The URL to test - * @returns {boolean} True if URL shares the same origin, otherwise false - */ - - return function isURLSameOrigin(requestURL) { - var parsed = utils$l.isString(requestURL) ? resolveURL(requestURL) : requestURL; - return parsed.protocol === originURL.protocol && parsed.host === originURL.host; - }; - }() : // Non standard browser envs (web workers, react-native) lack needed support. - function nonStandardBrowserEnv() { - return function isURLSameOrigin() { - return true; - }; - }(); - - /** - * A `Cancel` is an object that is thrown when an operation is canceled. - * - * @class - * @param {string=} message The message. - */ - - - function Cancel$7(message) { - this.message = message; - } - - Cancel$7.prototype.toString = function toString() { - return 'Cancel' + (this.message ? ': ' + this.message : ''); - }; - - Cancel$7.prototype.__CANCEL__ = true; - var Cancel_1$1 = Cancel$7; - - var utils$k = utils$r; - var settle$2 = settle$3; - var cookies$2 = cookies$3; - var buildURL$4 = buildURL$5; - var buildFullPath$2 = buildFullPath$3; - var parseHeaders$2 = parseHeaders$3; - var isURLSameOrigin$2 = isURLSameOrigin$3; - var createError$3 = createError$5; - var defaults$c = defaults_1$1; - var Cancel$6 = Cancel_1$1; - - var xhr$1 = function xhrAdapter(config) { - return new Promise(function dispatchXhrRequest(resolve, reject) { - var requestData = config.data; - var requestHeaders = config.headers; - var responseType = config.responseType; - var onCanceled; - - function done() { - if (config.cancelToken) { - config.cancelToken.unsubscribe(onCanceled); - } - - if (config.signal) { - config.signal.removeEventListener('abort', onCanceled); - } - } - - if (utils$k.isFormData(requestData)) { - delete requestHeaders['Content-Type']; // Let the browser set it - } - - var request = new XMLHttpRequest(); // HTTP basic authentication - - if (config.auth) { - var username = config.auth.username || ''; - var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; - requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); - } - - var fullPath = buildFullPath$2(config.baseURL, config.url); - request.open(config.method.toUpperCase(), buildURL$4(fullPath, config.params, config.paramsSerializer), true); // Set the request timeout in MS - - request.timeout = config.timeout; - - function onloadend() { - if (!request) { - return; - } // Prepare the response - - - var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders$2(request.getAllResponseHeaders()) : null; - var responseData = !responseType || responseType === 'text' || responseType === 'json' ? request.responseText : request.response; - var response = { - data: responseData, - status: request.status, - statusText: request.statusText, - headers: responseHeaders, - config: config, - request: request - }; - settle$2(function _resolve(value) { - resolve(value); - done(); - }, function _reject(err) { - reject(err); - done(); - }, response); // Clean up request - - request = null; - } - - if ('onloadend' in request) { - // Use onloadend if available - request.onloadend = onloadend; - } else { - // Listen for ready state to emulate onloadend - request.onreadystatechange = function handleLoad() { - if (!request || request.readyState !== 4) { - return; - } // The request errored out and we didn't get a response, this will be - // handled by onerror instead - // With one exception: request that using file: protocol, most browsers - // will return status as 0 even though it's a successful request - - - if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { - return; - } // readystate handler is calling before onerror or ontimeout handlers, - // so we should call onloadend on the next 'tick' - - - setTimeout(onloadend); - }; - } // Handle browser request cancellation (as opposed to a manual cancellation) - - - request.onabort = function handleAbort() { - if (!request) { - return; - } - - reject(createError$3('Request aborted', config, 'ECONNABORTED', request)); // Clean up request - - request = null; - }; // Handle low level network errors - - - request.onerror = function handleError() { - // Real errors are hidden from us by the browser - // onerror should only fire if it's a network error - reject(createError$3('Network Error', config, null, request)); // Clean up request - - request = null; - }; // Handle timeout - - - request.ontimeout = function handleTimeout() { - var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded'; - var transitional = config.transitional || defaults$c.transitional; - - if (config.timeoutErrorMessage) { - timeoutErrorMessage = config.timeoutErrorMessage; - } - - reject(createError$3(timeoutErrorMessage, config, transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED', request)); // Clean up request - - request = null; - }; // Add xsrf header - // This is only done if running in a standard browser environment. - // Specifically not if we're in a web worker, or react-native. - - - if (utils$k.isStandardBrowserEnv()) { - // Add xsrf header - var xsrfValue = (config.withCredentials || isURLSameOrigin$2(fullPath)) && config.xsrfCookieName ? cookies$2.read(config.xsrfCookieName) : undefined; - - if (xsrfValue) { - requestHeaders[config.xsrfHeaderName] = xsrfValue; - } - } // Add headers to the request - - - if ('setRequestHeader' in request) { - utils$k.forEach(requestHeaders, function setRequestHeader(val, key) { - if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { - // Remove Content-Type if data is undefined - delete requestHeaders[key]; - } else { - // Otherwise add header to the request - request.setRequestHeader(key, val); - } - }); - } // Add withCredentials to request if needed - - - if (!utils$k.isUndefined(config.withCredentials)) { - request.withCredentials = !!config.withCredentials; - } // Add responseType to request if needed - - - if (responseType && responseType !== 'json') { - request.responseType = config.responseType; - } // Handle progress if needed - - - if (typeof config.onDownloadProgress === 'function') { - request.addEventListener('progress', config.onDownloadProgress); - } // Not all browsers support upload events - - - if (typeof config.onUploadProgress === 'function' && request.upload) { - request.upload.addEventListener('progress', config.onUploadProgress); - } - - if (config.cancelToken || config.signal) { - // Handle cancellation - // eslint-disable-next-line func-names - onCanceled = function onCanceled(cancel) { - if (!request) { - return; - } - - reject(!cancel || cancel && cancel.type ? new Cancel$6('canceled') : cancel); - request.abort(); - request = null; - }; - - config.cancelToken && config.cancelToken.subscribe(onCanceled); - - if (config.signal) { - config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled); - } - } - - if (!requestData) { - requestData = null; - } // Send the request - - - request.send(requestData); - }); - }; - - var utils$j = utils$r; - var normalizeHeaderName$2 = normalizeHeaderName$3; - var enhanceError$3 = enhanceError$5; - var DEFAULT_CONTENT_TYPE$1 = { - 'Content-Type': 'application/x-www-form-urlencoded' - }; - - function setContentTypeIfUnset$1(headers, value) { - if (!utils$j.isUndefined(headers) && utils$j.isUndefined(headers['Content-Type'])) { - headers['Content-Type'] = value; - } - } - - function getDefaultAdapter$1() { - var adapter; - - if (typeof XMLHttpRequest !== 'undefined') { - // For browsers use XHR adapter - adapter = xhr$1; - } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { - // For node use HTTP adapter - adapter = xhr$1; - } - - return adapter; - } - - function stringifySafely$1(rawValue, parser, encoder) { - if (utils$j.isString(rawValue)) { - try { - (parser || JSON.parse)(rawValue); - return utils$j.trim(rawValue); - } catch (e) { - if (e.name !== 'SyntaxError') { - throw e; - } - } - } - - return (encoder || JSON.stringify)(rawValue); - } - - var defaults$b = { - transitional: { - silentJSONParsing: true, - forcedJSONParsing: true, - clarifyTimeoutError: false - }, - adapter: getDefaultAdapter$1(), - transformRequest: [function transformRequest(data, headers) { - normalizeHeaderName$2(headers, 'Accept'); - normalizeHeaderName$2(headers, 'Content-Type'); - - if (utils$j.isFormData(data) || utils$j.isArrayBuffer(data) || utils$j.isBuffer(data) || utils$j.isStream(data) || utils$j.isFile(data) || utils$j.isBlob(data)) { - return data; - } - - if (utils$j.isArrayBufferView(data)) { - return data.buffer; - } - - if (utils$j.isURLSearchParams(data)) { - setContentTypeIfUnset$1(headers, 'application/x-www-form-urlencoded;charset=utf-8'); - return data.toString(); - } - - if (utils$j.isObject(data) || headers && headers['Content-Type'] === 'application/json') { - setContentTypeIfUnset$1(headers, 'application/json'); - return stringifySafely$1(data); - } - - return data; - }], - transformResponse: [function transformResponse(data) { - var transitional = this.transitional || defaults$b.transitional; - var silentJSONParsing = transitional && transitional.silentJSONParsing; - var forcedJSONParsing = transitional && transitional.forcedJSONParsing; - var strictJSONParsing = !silentJSONParsing && this.responseType === 'json'; - - if (strictJSONParsing || forcedJSONParsing && utils$j.isString(data) && data.length) { - try { - return JSON.parse(data); - } catch (e) { - if (strictJSONParsing) { - if (e.name === 'SyntaxError') { - throw enhanceError$3(e, this, 'E_JSON_PARSE'); - } - - throw e; - } - } - } - - return data; - }], - - /** - * A timeout in milliseconds to abort a request. If set to 0 (default) a - * timeout is not created. - */ - timeout: 0, - xsrfCookieName: 'XSRF-TOKEN', - xsrfHeaderName: 'X-XSRF-TOKEN', - maxContentLength: -1, - maxBodyLength: -1, - validateStatus: function validateStatus(status) { - return status >= 200 && status < 300; - }, - headers: { - common: { - 'Accept': 'application/json, text/plain, */*' - } - } - }; - utils$j.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { - defaults$b.headers[method] = {}; - }); - utils$j.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { - defaults$b.headers[method] = utils$j.merge(DEFAULT_CONTENT_TYPE$1); - }); - var defaults_1$1 = defaults$b; - - var utils$i = utils$r; - var defaults$a = defaults_1$1; - /** - * Transform the data for a request or a response - * - * @param {Object|String} data The data to be transformed - * @param {Array} headers The headers for the request or response - * @param {Array|Function} fns A single function or Array of functions - * @returns {*} The resulting transformed data - */ - - var transformData$3 = function transformData(data, headers, fns) { - var context = this || defaults$a; - /*eslint no-param-reassign:0*/ - - utils$i.forEach(fns, function transform(fn) { - data = fn.call(context, data, headers); - }); - return data; - }; - - var isCancel$3 = function isCancel(value) { - return !!(value && value.__CANCEL__); - }; - - var utils$h = utils$r; - var transformData$2 = transformData$3; - var isCancel$2 = isCancel$3; - var defaults$9 = defaults_1$1; - var Cancel$5 = Cancel_1$1; - /** - * Throws a `Cancel` if cancellation has been requested. - */ - - function throwIfCancellationRequested$1(config) { - if (config.cancelToken) { - config.cancelToken.throwIfRequested(); - } - - if (config.signal && config.signal.aborted) { - throw new Cancel$5('canceled'); - } - } - /** - * Dispatch a request to the server using the configured adapter. - * - * @param {object} config The config that is to be used for the request - * @returns {Promise} The Promise to be fulfilled - */ - - - var dispatchRequest$3 = function dispatchRequest(config) { - throwIfCancellationRequested$1(config); // Ensure headers exist - - config.headers = config.headers || {}; // Transform request data - - config.data = transformData$2.call(config, config.data, config.headers, config.transformRequest); // Flatten headers - - config.headers = utils$h.merge(config.headers.common || {}, config.headers[config.method] || {}, config.headers); - utils$h.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], function cleanHeaderConfig(method) { - delete config.headers[method]; - }); - var adapter = config.adapter || defaults$9.adapter; - return adapter(config).then(function onAdapterResolution(response) { - throwIfCancellationRequested$1(config); // Transform response data - - response.data = transformData$2.call(config, response.data, response.headers, config.transformResponse); - return response; - }, function onAdapterRejection(reason) { - if (!isCancel$2(reason)) { - throwIfCancellationRequested$1(config); // Transform response data - - if (reason && reason.response) { - reason.response.data = transformData$2.call(config, reason.response.data, reason.response.headers, config.transformResponse); - } - } - - return Promise.reject(reason); - }); - }; - - var utils$g = utils$r; - /** - * Config-specific merge-function which creates a new config-object - * by merging two configuration objects together. - * - * @param {Object} config1 - * @param {Object} config2 - * @returns {Object} New object resulting from merging config2 to config1 - */ - - var mergeConfig$5 = function mergeConfig(config1, config2) { - // eslint-disable-next-line no-param-reassign - config2 = config2 || {}; - var config = {}; - - function getMergedValue(target, source) { - if (utils$g.isPlainObject(target) && utils$g.isPlainObject(source)) { - return utils$g.merge(target, source); - } else if (utils$g.isPlainObject(source)) { - return utils$g.merge({}, source); - } else if (utils$g.isArray(source)) { - return source.slice(); - } - - return source; - } // eslint-disable-next-line consistent-return - - - function mergeDeepProperties(prop) { - if (!utils$g.isUndefined(config2[prop])) { - return getMergedValue(config1[prop], config2[prop]); - } else if (!utils$g.isUndefined(config1[prop])) { - return getMergedValue(undefined, config1[prop]); - } - } // eslint-disable-next-line consistent-return - - - function valueFromConfig2(prop) { - if (!utils$g.isUndefined(config2[prop])) { - return getMergedValue(undefined, config2[prop]); - } - } // eslint-disable-next-line consistent-return - - - function defaultToConfig2(prop) { - if (!utils$g.isUndefined(config2[prop])) { - return getMergedValue(undefined, config2[prop]); - } else if (!utils$g.isUndefined(config1[prop])) { - return getMergedValue(undefined, config1[prop]); - } - } // eslint-disable-next-line consistent-return - - - function mergeDirectKeys(prop) { - if (prop in config2) { - return getMergedValue(config1[prop], config2[prop]); - } else if (prop in config1) { - return getMergedValue(undefined, config1[prop]); - } - } - - var mergeMap = { - 'url': valueFromConfig2, - 'method': valueFromConfig2, - 'data': valueFromConfig2, - 'baseURL': defaultToConfig2, - 'transformRequest': defaultToConfig2, - 'transformResponse': defaultToConfig2, - 'paramsSerializer': defaultToConfig2, - 'timeout': defaultToConfig2, - 'timeoutMessage': defaultToConfig2, - 'withCredentials': defaultToConfig2, - 'adapter': defaultToConfig2, - 'responseType': defaultToConfig2, - 'xsrfCookieName': defaultToConfig2, - 'xsrfHeaderName': defaultToConfig2, - 'onUploadProgress': defaultToConfig2, - 'onDownloadProgress': defaultToConfig2, - 'decompress': defaultToConfig2, - 'maxContentLength': defaultToConfig2, - 'maxBodyLength': defaultToConfig2, - 'transport': defaultToConfig2, - 'httpAgent': defaultToConfig2, - 'httpsAgent': defaultToConfig2, - 'cancelToken': defaultToConfig2, - 'socketPath': defaultToConfig2, - 'responseEncoding': defaultToConfig2, - 'validateStatus': mergeDirectKeys - }; - utils$g.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) { - var merge = mergeMap[prop] || mergeDeepProperties; - var configValue = merge(prop); - utils$g.isUndefined(configValue) && merge !== mergeDirectKeys || (config[prop] = configValue); - }); - return config; - }; - - var data$1 = { - "version": "0.24.0" - }; - - var VERSION$1 = data$1.version; - var validators$3 = {}; // eslint-disable-next-line func-names - - ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function (type, i) { - validators$3[type] = function validator(thing) { - return _typeof(thing) === type || 'a' + (i < 1 ? 'n ' : ' ') + type; - }; - }); - var deprecatedWarnings$1 = {}; - /** - * Transitional option validator - * @param {function|boolean?} validator - set to false if the transitional option has been removed - * @param {string?} version - deprecated version / removed since version - * @param {string?} message - some message with additional info - * @returns {function} - */ - - validators$3.transitional = function transitional(validator, version, message) { - function formatMessage(opt, desc) { - return '[Axios v' + VERSION$1 + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); - } // eslint-disable-next-line func-names - - - return function (value, opt, opts) { - if (validator === false) { - throw new Error(formatMessage(opt, ' has been removed' + (version ? ' in ' + version : ''))); - } - - if (version && !deprecatedWarnings$1[opt]) { - deprecatedWarnings$1[opt] = true; // eslint-disable-next-line no-console - - console.warn(formatMessage(opt, ' has been deprecated since v' + version + ' and will be removed in the near future')); - } - - return validator ? validator(value, opt, opts) : true; - }; - }; - /** - * Assert object's properties type - * @param {object} options - * @param {object} schema - * @param {boolean?} allowUnknown - */ - - - function assertOptions$1(options, schema, allowUnknown) { - if (_typeof(options) !== 'object') { - throw new TypeError('options must be an object'); - } - - var keys = Object.keys(options); - var i = keys.length; - - while (i-- > 0) { - var opt = keys[i]; - var validator = schema[opt]; - - if (validator) { - var value = options[opt]; - var result = value === undefined || validator(value, opt, options); - - if (result !== true) { - throw new TypeError('option ' + opt + ' must be ' + result); - } - - continue; - } - - if (allowUnknown !== true) { - throw Error('Unknown option ' + opt); - } - } - } - - var validator$3 = { - assertOptions: assertOptions$1, - validators: validators$3 - }; - - var utils$f = utils$r; - var buildURL$3 = buildURL$5; - var InterceptorManager$2 = InterceptorManager_1$1; - var dispatchRequest$2 = dispatchRequest$3; - var mergeConfig$4 = mergeConfig$5; - var validator$2 = validator$3; - var validators$2 = validator$2.validators; - /** - * Create a new instance of Axios - * - * @param {Object} instanceConfig The default config for the instance - */ - - function Axios$3(instanceConfig) { - this.defaults = instanceConfig; - this.interceptors = { - request: new InterceptorManager$2(), - response: new InterceptorManager$2() - }; - } - /** - * Dispatch a request - * - * @param {Object} config The config specific for this request (merged with this.defaults) - */ - - - Axios$3.prototype.request = function request(config) { - /*eslint no-param-reassign:0*/ - // Allow for axios('example/url'[, config]) a la fetch API - if (typeof config === 'string') { - config = arguments[1] || {}; - config.url = arguments[0]; - } else { - config = config || {}; - } - - config = mergeConfig$4(this.defaults, config); // Set config.method - - if (config.method) { - config.method = config.method.toLowerCase(); - } else if (this.defaults.method) { - config.method = this.defaults.method.toLowerCase(); - } else { - config.method = 'get'; - } - - var transitional = config.transitional; - - if (transitional !== undefined) { - validator$2.assertOptions(transitional, { - silentJSONParsing: validators$2.transitional(validators$2.boolean), - forcedJSONParsing: validators$2.transitional(validators$2.boolean), - clarifyTimeoutError: validators$2.transitional(validators$2.boolean) - }, false); - } // filter out skipped interceptors - - - var requestInterceptorChain = []; - var synchronousRequestInterceptors = true; - this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { - if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { - return; - } - - synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; - requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); - }); - var responseInterceptorChain = []; - this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { - responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); - }); - var promise; - - if (!synchronousRequestInterceptors) { - var chain = [dispatchRequest$2, undefined]; - Array.prototype.unshift.apply(chain, requestInterceptorChain); - chain = chain.concat(responseInterceptorChain); - promise = Promise.resolve(config); - - while (chain.length) { - promise = promise.then(chain.shift(), chain.shift()); - } - - return promise; - } - - var newConfig = config; - - while (requestInterceptorChain.length) { - var onFulfilled = requestInterceptorChain.shift(); - var onRejected = requestInterceptorChain.shift(); - - try { - newConfig = onFulfilled(newConfig); - } catch (error) { - onRejected(error); - break; - } - } - - try { - promise = dispatchRequest$2(newConfig); - } catch (error) { - return Promise.reject(error); - } - - while (responseInterceptorChain.length) { - promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift()); - } - - return promise; - }; - - Axios$3.prototype.getUri = function getUri(config) { - config = mergeConfig$4(this.defaults, config); - return buildURL$3(config.url, config.params, config.paramsSerializer).replace(/^\?/, ''); - }; // Provide aliases for supported request methods - - - utils$f.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { - /*eslint func-names:0*/ - Axios$3.prototype[method] = function (url, config) { - return this.request(mergeConfig$4(config || {}, { - method: method, - url: url, - data: (config || {}).data - })); - }; - }); - utils$f.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { - /*eslint func-names:0*/ - Axios$3.prototype[method] = function (url, data, config) { - return this.request(mergeConfig$4(config || {}, { - method: method, - url: url, - data: data - })); - }; - }); - var Axios_1$1 = Axios$3; - - var Cancel$4 = Cancel_1$1; - /** - * A `CancelToken` is an object that can be used to request cancellation of an operation. - * - * @class - * @param {Function} executor The executor function. - */ - - function CancelToken$1(executor) { - if (typeof executor !== 'function') { - throw new TypeError('executor must be a function.'); - } - - var resolvePromise; - this.promise = new Promise(function promiseExecutor(resolve) { - resolvePromise = resolve; - }); - var token = this; // eslint-disable-next-line func-names - - this.promise.then(function (cancel) { - if (!token._listeners) return; - var i; - var l = token._listeners.length; - - for (i = 0; i < l; i++) { - token._listeners[i](cancel); - } - - token._listeners = null; - }); // eslint-disable-next-line func-names - - this.promise.then = function (onfulfilled) { - var _resolve; // eslint-disable-next-line func-names - - - var promise = new Promise(function (resolve) { - token.subscribe(resolve); - _resolve = resolve; - }).then(onfulfilled); - - promise.cancel = function reject() { - token.unsubscribe(_resolve); - }; - - return promise; - }; - - executor(function cancel(message) { - if (token.reason) { - // Cancellation has already been requested - return; - } - - token.reason = new Cancel$4(message); - resolvePromise(token.reason); - }); - } - /** - * Throws a `Cancel` if cancellation has been requested. - */ - - - CancelToken$1.prototype.throwIfRequested = function throwIfRequested() { - if (this.reason) { - throw this.reason; - } - }; - /** - * Subscribe to the cancel signal - */ - - - CancelToken$1.prototype.subscribe = function subscribe(listener) { - if (this.reason) { - listener(this.reason); - return; - } - - if (this._listeners) { - this._listeners.push(listener); - } else { - this._listeners = [listener]; - } - }; - /** - * Unsubscribe from the cancel signal - */ - - - CancelToken$1.prototype.unsubscribe = function unsubscribe(listener) { - if (!this._listeners) { - return; - } - - var index = this._listeners.indexOf(listener); - - if (index !== -1) { - this._listeners.splice(index, 1); - } - }; - /** - * Returns an object that contains a new `CancelToken` and a function that, when called, - * cancels the `CancelToken`. - */ - - - CancelToken$1.source = function source() { - var cancel; - var token = new CancelToken$1(function executor(c) { - cancel = c; - }); - return { - token: token, - cancel: cancel - }; - }; - - var CancelToken_1$1 = CancelToken$1; - - /** - * Syntactic sugar for invoking a function and expanding an array for arguments. - * - * Common use case would be to use `Function.prototype.apply`. - * - * ```js - * function f(x, y, z) {} - * var args = [1, 2, 3]; - * f.apply(null, args); - * ``` - * - * With `spread` this example can be re-written. - * - * ```js - * spread(function(x, y, z) {})([1, 2, 3]); - * ``` - * - * @param {Function} callback - * @returns {Function} - */ - - - var spread$1 = function spread(callback) { - return function wrap(arr) { - return callback.apply(null, arr); - }; - }; - - /** - * Determines whether the payload is an error thrown by Axios - * - * @param {*} payload The value to test - * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false - */ - - - var isAxiosError$1 = function isAxiosError(payload) { - return _typeof(payload) === 'object' && payload.isAxiosError === true; - }; - - var utils$e = utils$r; - var bind$7 = bind$9; - var Axios$2 = Axios_1$1; - var mergeConfig$3 = mergeConfig$5; - var defaults$8 = defaults_1$1; - /** - * Create an instance of Axios - * - * @param {Object} defaultConfig The default config for the instance - * @return {Axios} A new instance of Axios - */ - - function createInstance$1(defaultConfig) { - var context = new Axios$2(defaultConfig); - var instance = bind$7(Axios$2.prototype.request, context); // Copy axios.prototype to instance - - utils$e.extend(instance, Axios$2.prototype, context); // Copy context to instance - - utils$e.extend(instance, context); // Factory for creating new instances - - instance.create = function create(instanceConfig) { - return createInstance$1(mergeConfig$3(defaultConfig, instanceConfig)); - }; - - return instance; - } // Create the default instance to be exported - - - var axios$4 = createInstance$1(defaults$8); // Expose Axios class to allow class inheritance - - axios$4.Axios = Axios$2; // Expose Cancel & CancelToken - - axios$4.Cancel = Cancel_1$1; - axios$4.CancelToken = CancelToken_1$1; - axios$4.isCancel = isCancel$3; - axios$4.VERSION = data$1.version; // Expose all/spread - - axios$4.all = function all(promises) { - return Promise.all(promises); - }; - - axios$4.spread = spread$1; // Expose isAxiosError - - axios$4.isAxiosError = isAxiosError$1; - axios$5.exports = axios$4; // Allow use of default import syntax in TypeScript - - axios$5.exports.default = axios$4; - - var axios$3 = axios$5.exports; - - var IdealPostcodesError$2 = IdealPostcodesError$3; - /** - * Converts a Got header object to one that can be used by the client - * - * @hidden - */ - - var toHeader$2 = function toHeader(gotHeaders) { - return Object.keys(gotHeaders).reduce(function (headers, key) { - var val = gotHeaders[key]; - - if (typeof val === "string") { - headers[key] = val; - } else if (Array.isArray(val)) { - headers[key] = val.join(","); - } - - return headers; - }, {}); - }; - /** - * Adapts got responses to a format consumable by core-interface - * - * @hidden - */ - - var toHttpResponse$1 = function toHttpResponse(httpRequest, response) { - return { - httpRequest: httpRequest, - body: response.data, - httpStatus: response.status || 0, - header: toHeader$2(response.headers), - metadata: { - response: response - } - }; - }; - /** - * Catch non-response errors (e.g. network failure, DNS failure, timeout) - * wrap in our Error class and return - * - * @hidden - */ - - - var handleError$1 = function handleError(error) { - var idpcError = new IdealPostcodesError$2({ - message: "[".concat(error.name, "] ").concat(error.message), - httpStatus: 0, - metadata: { - axios: error - } - }); - return Promise.reject(idpcError); - }; // Don't throw errors for any HTTP status code - // Allow core-interface to absorb these and emit own errors - - - var validateStatus$1 = function validateStatus() { - return true; - }; - /** - * Agent - * - * @hidden - */ - - - var Agent$1 = /*#__PURE__*/function () { - function Agent() { - _classCallCheck(this, Agent); - - this.Axios = axios$3.create({ - validateStatus: validateStatus$1 - }); - } - - _createClass(Agent, [{ - key: "requestWithBody", - value: function requestWithBody(httpRequest) { - var body = httpRequest.body, - method = httpRequest.method, - timeout = httpRequest.timeout, - url = httpRequest.url, - header = httpRequest.header, - query = httpRequest.query; - return this.Axios.request({ - url: url, - method: method, - headers: header, - params: query, - data: body, - timeout: timeout - }).then(function (response) { - return toHttpResponse$1(httpRequest, response); - }).catch(handleError$1); - } - }, { - key: "request", - value: function request(httpRequest) { - var method = httpRequest.method, - timeout = httpRequest.timeout, - url = httpRequest.url, - header = httpRequest.header, - query = httpRequest.query; - return this.Axios.request({ - url: url, - method: method, - headers: header, - params: query, - timeout: timeout - }).then(function (response) { - return toHttpResponse$1(httpRequest, response); - }).catch(handleError$1); - } - }, { - key: "http", - value: function http(httpRequest) { - if (httpRequest.body !== undefined) return this.requestWithBody(httpRequest); - return this.request(httpRequest); - } - }]); - - return Agent; - }(); - - function ownKeys$b(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - - function _objectSpread$b(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$b(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$b(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - - function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } - - function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } - var Client$2 = /*#__PURE__*/function (_CoreInterface) { - _inherits(Client, _CoreInterface); - - var _super = _createSuper$2(Client); - - /** - * Client constructor extends CoreInterface - */ - function Client(config) { - _classCallCheck(this, Client); - - var agent = new Agent$1(); - return _super.call(this, _objectSpread$b({ - agent: agent - }, config)); - } - - return Client; - }(Client$3); - - function ownKeys$a(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - - function _objectSpread$a(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$a(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$a(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - /** - * @hidden - */ - - var ApiCache = /*#__PURE__*/function () { - function ApiCache(client) { - _classCallCheck(this, ApiCache); - - this.prefix = "!"; - this.client = client; - this.cache = {}; - } - - _createClass(ApiCache, [{ - key: "key", - value: function key(query) { - return "".concat(this.prefix).concat(query.toLowerCase()); - } - }, { - key: "retrieve", - value: function retrieve(query) { - return this.cache[this.key(query)]; - } - }, { - key: "store", - value: function store(query, data) { - this.cache[this.key(query)] = data; - return data; - } - }, { - key: "clear", - value: function clear() { - this.cache = {}; - } - /** - * Retrieve a list of address suggestions given a query - * - * Write and read from cache if previously requested - */ - - }, { - key: "query", - value: function query(_query) { - var _this = this; - - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var cachedValue = this.retrieve(_query); - if (cachedValue) return Promise.resolve(cachedValue); - var p = list$1(this.client, { - query: _objectSpread$a({ - query: _query, - api_key: this.client.config.api_key - }, options) - }).then(function (response) { - var suggestions = response.body.result.hits; - - _this.store(_query, suggestions); - - return suggestions; - }); - this.store(_query, p); - return p; - } - }, { - key: "resolve", - value: function resolve(suggestion) { - return gbr(this.client, suggestion.id, { - query: { - api_key: this.client.config.api_key - } - }).then(function (response) { - return response.body.result; - }); - } - }]); - - return ApiCache; - }(); - - var isString$2 = function isString(input) { - return typeof input === "string"; - }; - - var hasWindow = function hasWindow() { - return typeof window !== "undefined"; - }; - var toArray = function toArray(nodeList) { - return Array.prototype.slice.call(nodeList); - }; - var loaded = function loaded(elem) { - var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "idpc"; - return elem.getAttribute(prefix) === "true"; - }; - var markLoaded = function markLoaded(elem) { - var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "idpc"; - return elem.setAttribute(prefix, "true"); - }; - - var isTrue$2 = function isTrue() { - return true; - }; - - var getParent = function getParent(node, entity) { - var test = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : isTrue$2; - var parent = node; - var tagName = entity.toUpperCase(); - - while (parent.tagName !== "HTML") { - if (parent.tagName === tagName && test(parent)) return parent; - if (parent.parentNode === null) return null; - parent = parent.parentNode; - } - - return null; - }; - var toHtmlElem = function toHtmlElem(parent, selector) { - return selector ? parent.querySelector(selector) : null; - }; - var toElem = function toElem(elem, context) { - if (isString$2(elem)) return context.querySelector(elem); - return elem; - }; - - var d$1 = function d() { - return window.document; - }; - - var getScope$1 = function getScope(scope) { - if (isString$2(scope)) return d$1().querySelector(scope); - if (scope === null) return d$1(); - return scope; - }; - var getDocument = function getDocument(scope) { - if (scope instanceof Document) return scope; - if (scope.ownerDocument) return scope.ownerDocument; - return d$1(); - }; - var setStyle = function setStyle(element, style) { - var currentRules = element.getAttribute("style"); - Object.keys(style).forEach(function (key) { - return element.style[key] = style[key]; - }); - return currentRules; - }; - var restoreStyle = function restoreStyle(element, style) { - element.setAttribute("style", style || ""); - }; - var hide = function hide(e) { - e.style.display = "none"; - return e; - }; - var show = function show(e) { - e.style.display = ""; - return e; - }; - var remove = function remove(elem) { - if (elem === null || elem.parentNode === null) return; - elem.parentNode.removeChild(elem); - }; - var contains = function contains(scope, selector, text) { - var elements = scope.querySelectorAll(selector); - - for (var i = 0; i < elements.length; i++) { - var e = elements[i]; - var content = e.innerText; - if (content && content.trim() === text) return e; - } - - return null; - }; - - var generateTimer = function generateTimer(_ref) { - var pageTest = _ref.pageTest, - bind = _ref.bind, - _ref$interval = _ref.interval, - interval = _ref$interval === void 0 ? 1000 : _ref$interval; - var timer = null; - - var start = function start(config) { - if (!pageTest()) return null; - timer = window.setInterval(function () { - try { - bind(config); - } catch (e) { - stop(); - console.log(e); - } - }, interval); - return timer; - }; - - var stop = function stop() { - if (timer === null) return; - window.clearInterval(timer); - timer = null; - }; - - return { - start: start, - stop: stop - }; - }; - var cssEscape = function cssEscape(value) { - value = String(value); - var length = value.length; - var index = -1; - var codeUnit; - var result = ""; - var firstCodeUnit = value.charCodeAt(0); - - while (++index < length) { - codeUnit = value.charCodeAt(index); - - if (codeUnit == 0x0000) { - result += "\uFFFD"; - continue; - } - - if (codeUnit >= 0x0001 && codeUnit <= 0x001f || codeUnit == 0x007f || index == 0 && codeUnit >= 0x0030 && codeUnit <= 0x0039 || index == 1 && codeUnit >= 0x0030 && codeUnit <= 0x0039 && firstCodeUnit == 0x002d) { - result += "\\" + codeUnit.toString(16) + " "; - continue; - } - - if (index == 0 && length == 1 && codeUnit == 0x002d) { - result += "\\" + value.charAt(index); - continue; - } - - if (codeUnit >= 0x0080 || codeUnit == 0x002d || codeUnit == 0x005f || codeUnit >= 0x0030 && codeUnit <= 0x0039 || codeUnit >= 0x0041 && codeUnit <= 0x005a || codeUnit >= 0x0061 && codeUnit <= 0x007a) { - result += value.charAt(index); - continue; - } - - result += "\\" + value.charAt(index); - } - - return result; - }; - - var loadStyle = function loadStyle(href, document) { - var link = document.createElement("link"); - link.type = "text/css"; - link.rel = "stylesheet"; - link.href = href; - return link; - }; - var injectStyle = function injectStyle(css, document) { - var style = document.createElement("style"); - style.type = "text/css"; - style.appendChild(document.createTextNode(css)); - document.head.appendChild(style); - return style; - }; - - var newEvent = function newEvent(_ref) { - var event = _ref.event, - _ref$bubbles = _ref.bubbles, - bubbles = _ref$bubbles === void 0 ? true : _ref$bubbles, - _ref$cancelable = _ref.cancelable, - cancelable = _ref$cancelable === void 0 ? true : _ref$cancelable; - if (typeof window.Event === "function") return new window.Event(event, { - bubbles: bubbles, - cancelable: cancelable - }); - var e = document.createEvent("Event"); - e.initEvent(event, bubbles, cancelable); - return e; - }; - var trigger = function trigger(e, event) { - return e.dispatchEvent(newEvent({ - event: event - })); - }; - - var isSelect = function isSelect(e) { - if (e === null) return false; - return e instanceof HTMLSelectElement; - }; - var isInput = function isInput(e) { - if (e === null) return false; - return e instanceof HTMLInputElement; - }; - var isTextarea = function isTextarea(e) { - if (e === null) return false; - return e instanceof HTMLTextAreaElement; - }; - var update = function update(input, value) { - var skipTrigger = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - if (!input) return; - if (!isInput(input) && !isTextarea(input)) return; - change({ - e: input, - value: value, - skipTrigger: skipTrigger - }); - }; - var hasValue = function hasValue(select, value) { - if (value === null) return false; - return select.querySelector("[value=\"".concat(value, "\"]")) !== null; - }; - - var updateSelect = function updateSelect(_ref) { - var e = _ref.e, - value = _ref.value, - skipTrigger = _ref.skipTrigger; - if (value === null) return; - if (!isSelect(e)) return; - setValue(e, value); - if (!skipTrigger) trigger(e, "select"); - trigger(e, "change"); - }; - - var setValue = function setValue(e, value) { - var descriptor = Object.getOwnPropertyDescriptor(e.constructor.prototype, "value"); - if (descriptor === undefined) return; - if (descriptor.set === undefined) return; - var setter = descriptor.set; - setter.call(e, value); - }; - - var updateInput = function updateInput(_ref2) { - var e = _ref2.e, - value = _ref2.value, - skipTrigger = _ref2.skipTrigger; - if (value === null) return; - if (!isInput(e) && !isTextarea(e)) return; - setValue(e, value); - if (!skipTrigger) trigger(e, "input"); - trigger(e, "change"); - }; - - var change = function change(options) { - if (options.value === null) return; - updateSelect(options); - updateInput(options); - }; - - var toCiIso = function toCiIso(address) { - if (/^GY/.test(address.postcode)) return "GG"; - if (/^JE/.test(address.postcode)) return "JE"; - return null; - }; - var UK = "United Kingdom"; - var IOM = "Isle of Man"; - var EN = "England"; - var SC = "Scotland"; - var WA = "Wales"; - var NI = "Northern Ireland"; - var CI = "Channel Islands"; - var toIso = function toIso(address) { - var country = address.country; - if (country === EN) return "GB"; - if (country === SC) return "GB"; - if (country === WA) return "GB"; - if (country === NI) return "GB"; - if (country === IOM) return "IM"; - if (country === CI) return toCiIso(address); - return null; - }; - var toCountry = function toCountry(address) { - var country = address.country; - if (country === EN) return UK; - if (country === SC) return UK; - if (country === WA) return UK; - if (country === NI) return UK; - if (country === IOM) return IOM; - - if (country === CI) { - var iso = toCiIso(address); - if (iso === "GG") return "Guernsey"; - if (iso === "JE") return "Jersey"; - } - - return null; - }; - var updateCountry = function updateCountry(select, address) { - if (!select) return; - - if (isSelect(select)) { - var iso = toIso(address); - if (hasValue(select, iso)) change({ - e: select, - value: iso - }); - var bcc = toCountry(address); - if (hasValue(select, bcc)) change({ - e: select, - value: bcc - }); - } - - if (isInput(select)) { - var _bcc = toCountry(address); - - change({ - e: select, - value: _bcc - }); - } - }; - - var g = {}; - - if (hasWindow()) { - if (window.idpcGlobal) { - g = window.idpcGlobal; - } else { - window.idpcGlobal = g; - } - } - - var idpcState = function idpcState() { - return g; - }; - - var idGen = function idGen() { - var prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "idpc_"; - return function () { - var g = idpcState(); - if (!g.idGen) g.idGen = {}; - if (g.idGen[prefix] === undefined) g.idGen[prefix] = 0; - g.idGen[prefix] += 1; - return "".concat(prefix).concat(g.idGen[prefix]); - }; - }; - - function ownKeys$9(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - - function _objectSpread$9(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$9(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$9(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - var numberOfLines = function numberOfLines(targets) { - var line_2 = targets.line_2, - line_3 = targets.line_3; - if (!line_2) return 1; - if (!line_3) return 2; - return 3; - }; - var join = function join(list) { - return list.filter(function (e) { - if (isString$2(e)) return !!e.trim(); - return !!e; - }).join(", "); - }; - var toAddressLines = function toAddressLines(n, address) { - var line_1 = address.line_1, - line_2 = address.line_2, - line_3 = address.line_3; - if (n === 3) return [line_1, line_2, line_3]; - if (n === 2) return [line_1, join([line_2, line_3]), ""]; - return [join([line_1, line_2, line_3]), "", ""]; - }; - var extract = function extract(a, attr) { - var result = a[attr]; - if (typeof result === "number") return result.toString(); - if (result === undefined) return ""; - return result; - }; - var notInAddress = function notInAddress(o, attr) { - return o[attr] === undefined; - }; - var getFields$1 = function getFields(o) { - return _objectSpread$9(_objectSpread$9(_objectSpread$9({}, o.outputFields), searchNames(o.names || {}, o.config.scope)), searchLabels(o.labels || {}, o.config.scope)); - }; - - var updateLines = function updateLines(fields, address, scope) { - var _toAddressLines3 = toAddressLines(numberOfLines(fields), address), - _toAddressLines4 = _slicedToArray(_toAddressLines3, 3), - line_1 = _toAddressLines4[0], - line_2 = _toAddressLines4[1], - line_3 = _toAddressLines4[2]; - - update(toElem(fields.line_1 || null, scope), line_1); - update(toElem(fields.line_2 || null, scope), line_2); - update(toElem(fields.line_3 || null, scope), line_3); - }; - - var searchNames = function searchNames(names, scope) { - var result = {}; - var key; - - for (key in names) { - if (!names.hasOwnProperty(key)) continue; - var name = names[key]; - var named = toElem("[name=\"".concat(name, "\"]"), scope); - - if (named) { - result[key] = named; - continue; - } - - var ariaNamed = toElem("[aria-name=\"".concat(name, "\"]"), scope); - if (ariaNamed) result[key] = ariaNamed; - } - - return result; - }; - var searchLabels = function searchLabels(labels, scope) { - var result = {}; - if (labels === undefined) return labels; - var key; - - for (key in labels) { - if (!labels.hasOwnProperty(key)) continue; - var name = labels[key]; - if (!name) continue; - var first = contains(scope, "label", name); - var label = toElem(first, scope); - if (!label) continue; - var forEl = label.getAttribute("for"); - - if (forEl) { - var byId = scope.querySelector("#".concat(cssEscape(forEl))); - - if (byId) { - result[key] = byId; - continue; - } - } - - var inner = label.querySelector("input"); - if (inner) result[key] = inner; - } - - return result; - }; - var populateAddress = function populateAddress(options) { - var config = options.config; - - var address = _objectSpread$9({}, options.address); - - var scope = config.scope, - titleizePostTown = config.titleizePostTown, - populateOrganisation = config.populateOrganisation, - populateCounty = config.populateCounty; - var fields = getFields$1(options); - if (config.removeOrganisation) removeOrganisation(address); - if (titleizePostTown) address.post_town = capitalisePostTown_1(address.post_town); - updateLines(fields, address, scope); - delete address.line_1; - delete address.line_2; - delete address.line_3; - updateCountry(toElem(fields.country || null, scope), address); - delete address.country; - if (populateOrganisation === false) delete address.organisation_name; - if (populateCounty === false) delete address.county; - var e; - - for (e in fields) { - if (notInAddress(address, e)) continue; - - if (fields.hasOwnProperty(e)) { - var value = fields[e]; - if (!value) continue; - update(toElem(value, scope), extract(address, e)); - } - } - }; - var removeOrganisation = function removeOrganisation(address) { - if (address.organisation_name.length === 0) return address; - if (address.line_2.length === 0 && address.line_3.length === 0) return address; - - if (address.line_1 === address.organisation_name) { - address.line_1 = address.line_2; - address.line_2 = address.line_3; - address.line_3 = ""; - } - - return address; - }; - - var keyCodeMapping = { - 13: "Enter", - 38: "ArrowUp", - 40: "ArrowDown", - 36: "Home", - 35: "End", - 27: "Escape", - 8: "Backspace" - }; - var supportedKeys = ["Enter", "ArrowUp", "ArrowDown", "Home", "End", "Escape", "Backspace"]; - - var supported = function supported(k) { - return supportedKeys.indexOf(k) !== -1; - }; - - var toKey = function toKey(event) { - if (event.keyCode) return keyCodeMapping[event.keyCode] || null; - return supported(event.key) ? event.key : null; - }; - - /** - * Default CSS - * - * @hidden - */ - - var d = ".idpc_af.hidden{display:none}div.idpc_autocomplete{position:relative;margin:0!important;padding:0;border:0;color:#28282b;text-rendering:optimizeLegibility;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}div.idpc_autocomplete>input{display:block}div.idpc_af{position:absolute;left:0;z-index:2000;min-width:100%;box-sizing:border-box;border-radius:3px;background:#fff;border:1px solid rgba(0,0,0,.3);box-shadow:.05em .2em .6em rgba(0,0,0,.2);text-shadow:none;padding:0;margin-top:2px}div.idpc_af>ul{list-style:none;padding:0;max-height:250px;overflow-y:scroll;margin:0!important}div.idpc_af>ul>li{position:relative;padding:.2em .5em;cursor:pointer;margin:0!important}div.idpc_toolbar{padding:.3em .5em;border-top:1px solid rgba(0,0,0,.3);text-align:right}div.idpc_af>ul>li:hover{background-color:#e5e4e2}div.idpc_af>ul>li.idpc_error{padding:.5em;text-align:center;cursor:default!important}div.idpc_af>ul>li.idpc_error:hover{background:#fff;cursor:default!important}div.idpc_af>ul>li[aria-selected=true]{background-color:#e5e4e2;z-index:3000}div.idpc_autocomplete>.idpc-unhide{font-size:.9em;text-decoration:underline;cursor:pointer}div.idpc_af>div>span{padding:.2em .5em;border-radius:3px;cursor:pointer;font-size:110%}span.idpc_icon{font-size:1.2em;line-height:1em;vertical-align:middle}div.idpc_toolbar>span span.idpc_country{margin-right:.3em;max-width:0;font-size:.9em;-webkit-transition:max-width .5s ease-out;transition:max-width .5s ease-out;display:inline-block;vertical-align:middle;white-space:nowrap;overflow:hidden}div.idpc_autocomplete>div>div>span:hover span.idpc_country{max-width:7em}div.idpc_autocomplete>div>div>span:hover{background-color:#e5e4e2;-webkit-transition:background-color .5s ease;-ms-transition:background-color .5s ease;transition:background-color .5s ease}"; - /** - * Injects CSS style into DOM - * - * Idempotent - * - * @hidden - */ - - var addStyle = function addStyle(c) { - var style = c.options.injectStyle; - if (!style) return; - var g = idpcState(); - if (!g.afstyle) g.afstyle = {}; - - if (isString$2(style) && !g.afstyle[style]) { - g.afstyle[style] = true; - var link = loadStyle(style, c.document); - c.document.head.appendChild(link); - return link; - } - - if (style === true && !g.afstyle[""]) { - g.afstyle[""] = true; - return injectStyle(d, c.document); - } - - return; - }; - /** - * Returns a negative offset which can be used to correctly align input box - * @hidden - */ - - var computeOffset = function computeOffset(c) { - var offset; - var input = c.input; - if (c.options.alignToInput === false) return {}; - - try { - var w = c.options.document.defaultView; - if (!w) return {}; - offset = w.getComputedStyle(input).marginBottom; - } catch (_) { - return {}; - } - - if (!offset) return {}; - var nOffset = parseInt(offset.replace("px", ""), 10); - if (isNaN(nOffset)) return {}; - if (nOffset === 0) return {}; - var negativeOffset = nOffset * -1 + c.options.offset; - return { - marginTop: negativeOffset + "px" - }; - }; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - function t(t, n) { - var e = "function" == typeof Symbol && t[Symbol.iterator]; - if (!e) return t; - var r, - o, - i = e.call(t), - a = []; - - try { - for (; (void 0 === n || n-- > 0) && !(r = i.next()).done;) { - a.push(r.value); - } - } catch (t) { - o = { - error: t - }; - } finally { - try { - r && !r.done && (e = i.return) && e.call(i); - } finally { - if (o) throw o.error; - } - } - - return a; - } - - var n; - !function (t) { - t[t.NotStarted = 0] = "NotStarted", t[t.Running = 1] = "Running", t[t.Stopped = 2] = "Stopped"; - }(n || (n = {})); - var e = { - type: "xstate.init" - }; - - function r(t) { - return void 0 === t ? [] : [].concat(t); - } - - function i(t, n) { - return "string" == typeof (t = "string" == typeof t && n && n[t] ? n[t] : t) ? { - type: t - } : "function" == typeof t ? { - type: t.name, - exec: t - } : t; - } - - function a(t) { - return function (n) { - return t === n; - }; - } - - function u(t) { - return "string" == typeof t ? { - type: t - } : t; - } - - function c(t, n) { - return { - value: t, - context: n, - actions: [], - changed: !1, - matches: a(t) - }; - } - - function f(t, n, e) { - var r = n, - o = !1; - return [t.filter(function (t) { - if ("xstate.assign" === t.type) { - o = !0; - var n = Object.assign({}, r); - return "function" == typeof t.assignment ? n = t.assignment(r, e) : Object.keys(t.assignment).forEach(function (o) { - n[o] = "function" == typeof t.assignment[o] ? t.assignment[o](r, e) : t.assignment[o]; - }), r = n, !1; - } - - return !0; - }), r, o]; - } - - function s(n, o) { - void 0 === o && (o = {}); - var s = t(f(r(n.states[n.initial].entry).map(function (t) { - return i(t, o.actions); - }), n.context, e), 2), - l = s[0], - v = s[1], - y = { - config: n, - _options: o, - initialState: { - value: n.initial, - actions: l, - context: v, - matches: a(n.initial) - }, - transition: function transition(e, o) { - var s, - l, - v = "string" == typeof e ? { - value: e, - context: n.context - } : e, - p = v.value, - g = v.context, - d = u(o), - x = n.states[p]; - - if (x.on) { - var m = r(x.on[d.type]); - - try { - for (var h = function (t) { - var n = "function" == typeof Symbol && Symbol.iterator, - e = n && t[n], - r = 0; - if (e) return e.call(t); - if (t && "number" == typeof t.length) return { - next: function next() { - return t && r >= t.length && (t = void 0), { - value: t && t[r++], - done: !t - }; - } - }; - throw new TypeError(n ? "Object is not iterable." : "Symbol.iterator is not defined."); - }(m), b = h.next(); !b.done; b = h.next()) { - var S = b.value; - if (void 0 === S) return c(p, g); - - var w = "string" == typeof S ? { - target: S - } : S, - j = w.target, - E = w.actions, - R = void 0 === E ? [] : E, - N = w.cond, - O = void 0 === N ? function () { - return !0; - } : N, - _ = void 0 === j, - k = null != j ? j : p, - T = n.states[k]; - - if (O(g, d)) { - var q = t(f((_ ? r(R) : [].concat(x.exit, R, T.entry).filter(function (t) { - return t; - })).map(function (t) { - return i(t, y._options.actions); - }), g, d), 3), - z = q[0], - A = q[1], - B = q[2], - C = null != j ? j : p; - return { - value: C, - context: A, - actions: z, - changed: j !== p || z.length > 0 || B, - matches: a(C) - }; - } - } - } catch (t) { - s = { - error: t - }; - } finally { - try { - b && !b.done && (l = h.return) && l.call(h); - } finally { - if (s) throw s.error; - } - } - } - - return c(p, g); - } - }; - return y; - } - - var l = function l(t, n) { - return t.actions.forEach(function (e) { - var r = e.exec; - return r && r(t.context, n); - }); - }; - - function v(t) { - var r = t.initialState, - o = n.NotStarted, - i = new Set(), - c = { - _machine: t, - send: function send(e) { - o === n.Running && (r = t.transition(r, e), l(r, u(e)), i.forEach(function (t) { - return t(r); - })); - }, - subscribe: function subscribe(t) { - return i.add(t), t(r), { - unsubscribe: function unsubscribe() { - return i.delete(t); - } - }; - }, - start: function start(i) { - if (i) { - var u = "object" == _typeof(i) ? i : { - context: t.config.context, - value: i - }; - r = { - value: u.value, - actions: [], - context: u.context, - matches: a(u.value) - }; - } - - return o = n.Running, l(r, e), c; - }, - stop: function stop() { - return o = n.Stopped, i.clear(), c; - }, - - get state() { - return r; - }, - - get status() { - return o; - } - - }; - return c; - } - - function ownKeys$8(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - - function _objectSpread$8(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$8(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$8(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - /** - * @hidden - */ - - var INPUT = { - INPUT: { - actions: "input" - } - }; - /** - * @hidden - */ - - var CLOSE = { - CLOSE: "closed" - }; - /** - * @hidden - */ - - var SUGGEST = { - SUGGEST: { - target: "suggesting", - actions: ["updateSuggestions"] - } - }; - /** - * @hidden - */ - - var NOTIFY = { - NOTIFY: { - target: "notifying", - actions: ["updateMessage"] - } - }; - /** - * @hidden - */ - - var NEXT = { - NEXT: { - actions: ["next", "gotoCurrent"] - } - }; - /** - * @hidden - */ - - var PREVIOUS = { - PREVIOUS: { - actions: ["previous", "gotoCurrent"] - } - }; - /** - * @hidden - */ - - var RESET = { - RESET: { - actions: ["resetCurrent", "gotoCurrent"] - } - }; - /** - * @hidden - */ - - var CHANGE_COUNTRY = { - CHANGE_COUNTRY: { - target: "suggesting_country" - } - }; - /** - * Creates a finite state machine that drives Address Finder UI - * @hidden - */ - - var create = function create(_ref) { - var c = _ref.c; - var machine = s({ - initial: "closed", - states: { - closed: { - entry: ["close"], - exit: ["open"], - on: { - AWAKE: [{ - target: "suggesting", - cond: function cond() { - return c.suggestions.length > 0; - } - }, { - target: "notifying" - }] - } - }, - notifying: { - entry: ["renderNotice"], - exit: ["clearAnnouncement"], - on: _objectSpread$8(_objectSpread$8(_objectSpread$8(_objectSpread$8(_objectSpread$8({}, CLOSE), SUGGEST), NOTIFY), INPUT), CHANGE_COUNTRY) - }, - suggesting_country: { - entry: ["renderContexts", "gotoCurrent", "expand", "addCountryHint"], - exit: ["resetCurrent", "gotoCurrent", "contract", "clearHint"], - on: _objectSpread$8(_objectSpread$8(_objectSpread$8(_objectSpread$8(_objectSpread$8(_objectSpread$8({}, CLOSE), NOTIFY), NEXT), PREVIOUS), RESET), {}, { - INPUT: { - actions: ["countryInput"] - }, - SELECT_COUNTRY: { - target: "notifying", - actions: ["selectCountry"] - } - }) - }, - suggesting: { - entry: ["renderSuggestions", "gotoCurrent", "expand", "addHint"], - exit: ["resetCurrent", "gotoCurrent", "contract", "clearHint"], - on: _objectSpread$8(_objectSpread$8(_objectSpread$8(_objectSpread$8(_objectSpread$8(_objectSpread$8(_objectSpread$8(_objectSpread$8(_objectSpread$8({}, CLOSE), SUGGEST), NOTIFY), INPUT), CHANGE_COUNTRY), NEXT), PREVIOUS), RESET), {}, { - SELECT_ADDRESS: { - target: "closed", - actions: ["selectAddress"] - } - }) - } - } - }, { - actions: { - addHint: function addHint() { - c.setPlaceholder(c.options.msgPlaceholder); - }, - addCountryHint: function addCountryHint() { - c.setPlaceholder(c.options.msgPlaceholderCountry); - }, - clearHint: function clearHint() { - c.unsetPlaceholder(); - }, - - /** - * Updates current li in list to active descendant - */ - gotoCurrent: function gotoCurrent() { - c.goToCurrent(); - }, - - /** - * Unhighlights a suggestion - */ - resetCurrent: function resetCurrent() { - c.current = -1; - }, - - /** - * Triggers onInput callback - */ - input: function input(_, e) { - if (e.type !== "INPUT") return; - c.retrieveSuggestions(e.event); - }, - - /** - * Narrows country search box - */ - countryInput: function countryInput() {}, - - /** - * Clears ARIA announcement fields - */ - clearAnnouncement: function clearAnnouncement() { - c.announce(""); - }, - - /** - * Renders suggestion within list - */ - renderContexts: function renderContexts(_, e) { - if (e.type !== "CHANGE_COUNTRY") return; - c.renderContexts(); - }, - - /** - * Renders suggestion within list - */ - renderSuggestions: function renderSuggestions(_, e) { - if (e.type !== "SUGGEST") return; - c.renderSuggestions(); - }, - - /** - * Update suggestions - */ - updateSuggestions: function updateSuggestions(_, e) { - if (e.type !== "SUGGEST") return; - c.updateSuggestions(e.suggestions); - }, - - /** - * Hides list and runs callback - */ - close: function close(_, e) { - if (e.type === "CLOSE") return c.close(e.reason); - c.close(); - }, - - /** - * Makes list visible and run callback - */ - open: function open() { - c.open(); - }, - - /** - * Marks aria component as expanded - */ - expand: function expand() { - c.ariaExpand(); - }, - - /** - * Marks aria component as closed - */ - contract: function contract() { - c.ariaContract(); - }, - - /** - * Assigns notification message - */ - updateMessage: function updateMessage(_, e) { - if (e.type !== "NOTIFY") return; - c.notification = e.notification; - }, - - /** - * Renders message container and current message - */ - renderNotice: function renderNotice() { - c.renderNotice(); - }, - - /** - * Selects next element in list. Wraps to top if at bottom - */ - next: function next() { - c.next(); - }, - - /** - * Selects previous element in list. Wraps to bottom if at top - */ - previous: function previous() { - c.previous(); - }, - - /** - * Triggers select on current context or clicked element - */ - selectCountry: function selectCountry(_, e) { - if (e.type !== "SELECT_COUNTRY") return; - var co = e.contextDetails; - if (!co) return; - c.applyContext(co); - c.notification = "Country switched to ".concat(co.name, " ").concat(co.icon); - }, - - /** - * Triggers select on current suggestion or clicked element - */ - selectAddress: function selectAddress(_, e) { - if (e.type !== "SELECT_ADDRESS") return; - var s = e.suggestion; - if (!s) return; - c.applySuggestion(s); - } - } - }); - return v(machine); - }; - - function ownKeys$7(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - - function _objectSpread$7(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$7(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$7(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - /** - * @hidden - */ - - var NOOP$3 = function NOOP() {}; - /** - * Default options assigned to controller instances - */ - - var defaults$7 = { - // DOM - outputScope: null, - // Client - apiKey: "", - checkKey: true, - // WAI-ARIA compliance settings - aria: "1.0", - // Behaviour - titleizePostTown: true, - outputFields: {}, - names: {}, - labels: {}, - removeOrganisation: false, - injectStyle: true, - inputField: "", - autocomplete: "none", - populateCounty: true, - populateOrganisation: true, - queryOptions: {}, - alignToInput: true, - offset: 2, - hideToolbar: false, - // Country - defaultCountry: "GBR", - restrictCountries: [], - contexts: defaultContexts, - // Messages - msgFallback: "Please enter your address manually", - msgInitial: "Start typing to find address", - msgNoMatch: "No matches found", - msgList: "Select your address", - msgCountryToggle: "Change Country", - // Placeholder Messages - msgPlaceholder: "Type the first line or postal code of your address", - msgPlaceholderCountry: "Select your country", - // View classes - messageClass: "idpc_error", - containerClass: "idpc_autocomplete", - mainClass: "idpc_af", - listClass: "idpc_ul", - toolbarClass: "idpc_toolbar", - countryToggleClass: "idpc_country", - // Syles - mainStyle: {}, - inputStyle: {}, - listStyle: {}, - liStyle: {}, - containerStyle: {}, - // Hide / unhide - unhide: null, - unhideClass: "idpc-unhide", - msgUnhide: "Enter address manually", - hide: [], - // Callbacks - onOpen: NOOP$3, - onSelect: NOOP$3, - onBlur: NOOP$3, - onClose: NOOP$3, - onFocus: NOOP$3, - onInput: NOOP$3, - onLoaded: NOOP$3, - onSearchError: NOOP$3, - onSuggestionError: NOOP$3, - onMounted: NOOP$3, - onRemove: NOOP$3, - onSuggestionsRetrieved: NOOP$3, - onAddressSelected: NOOP$3, - onAddressRetrieved: NOOP$3, - onAddressPopulated: NOOP$3, - onFailedCheck: NOOP$3, - onMouseDown: NOOP$3, - onKeyDown: NOOP$3, - onUnhide: NOOP$3, - onCountrySelected: NOOP$3 - }; - /** - * # Controller - * - * The Autocomplete Controller class acts as the public class which you may - * wield to enable address autocomplete on your HTML address forms - * - * When instantiated, the controller will serve as a bridge beteen the - * address suggestion view presented on the DOM and the Ideal - * Postcodes Address resolution HTTP APIs - * - * The role of the controller is to bind to events produced by the user - * interface and take appropriate action including querying the API, - * modifying other aspects of the DOM. - */ - - var Controller$1 = /*#__PURE__*/function () { - function Controller(options) { - var _this = this; - - _classCallCheck(this, Controller); - - this.options = _objectSpread$7(_objectSpread$7(_objectSpread$7({}, { - scope: window.document, - document: window.document - }), defaults$7), options); // Default inputField to line_1 if `inputField` not specified - - if (!options.inputField) this.options.inputField = this.options.outputFields.line_1 || ""; // To overcome config overload - idpcConfig global config object already - // defines autocomplete (boolean) - //@ts-ignore - - if (this.options.autocomplete === true) this.options.autocomplete = defaults$7.autocomplete; // Scope the operations of this controller to a document or DOM subtree - - this.scope = getScope$1(this.options.scope); // Assign a parent Document for elem creation - - this.document = getDocument(this.scope); // Assign a document or DOM subtree to scope outputs. Defaults to controller scope - - this.outputScope = findOrCreate(this.scope, this.options.outputScope, function () { - return _this.scope; - }); // Initialise state - - this.context = this.options.defaultCountry; - this.notification = this.options.msgInitial; - this.current = -1; - this.suggestions = []; - this.contextSuggestions = toContextList(this.options.contexts, this.options.restrictCountries); - this.client = new Client$2(_objectSpread$7(_objectSpread$7({}, this.options), {}, { - api_key: this.options.apiKey - })); - this.cache = new ApiCache(this.client); - this.retrieveSuggestions = debounce_1(function (event) { - _this.options.onInput.call(_this, event); - - var query = _this.query(); - - if (query.trim().length === 0) { - _this.setMessage(_this.options.msgInitial); - - return Promise.resolve(_this); - } - - return _this.cache.query(query, _objectSpread$7(_objectSpread$7({}, _this.options.queryOptions), {}, { - context: _this.context - })).then(function (suggestions) { - _this.options.onSuggestionsRetrieved.call(_this, suggestions); - - return _this.setSuggestions(suggestions, query); - }).catch(function (error) { - if (_this.query() === query) _this.setMessage(_this.options.msgFallback); - - _this.options.onSuggestionError.call(_this, error); - - return _this; - }); - }, 100, { - leading: true, - trailing: true, - maxWait: 100 - }); - this.ids = idGen("idpcaf"); // Configure container - - this.container = this.options.document.createElement("div"); - this.container.className = this.options.containerClass; - this.container.id = this.ids(); - this.container.setAttribute("aria-haspopup", "listbox"); // Create message element - - this.message = this.options.document.createElement("li"); - this.message.textContent = this.options.msgInitial; - this.message.className = this.options.messageClass; // Create button to toggle country selection - - this.countryToggle = this.options.document.createElement("span"); - this.countryToggle.className = this.options.countryToggleClass; - this.countryToggle.addEventListener("mousedown", _onCountryToggle(this)); - this.countryIcon = this.options.document.createElement("span"); - this.countryIcon.className = "idpc_icon"; - this.countryIcon.innerText = this.currentContext().icon; - this.countryMessage = this.options.document.createElement("span"); - this.countryMessage.innerText = "Select Country"; - this.countryMessage.className = "idpc_country"; - this.countryToggle.appendChild(this.countryMessage); - this.countryToggle.appendChild(this.countryIcon); // Create toolbar (for country selection) - - this.toolbar = this.options.document.createElement("div"); - this.toolbar.className = this.options.toolbarClass; - this.toolbar.appendChild(this.countryToggle); - if (this.options.hideToolbar) hide(this.toolbar); // Configure UL - - this.list = this.options.document.createElement("ul"); - this.list.className = this.options.listClass; - this.list.id = this.ids(); - this.list.setAttribute("aria-label", this.options.msgList); - this.list.setAttribute("role", "listbox"); - this.mainComponent = this.options.document.createElement("div"); - this.mainComponent.appendChild(this.list); - this.mainComponent.appendChild(this.toolbar); - this.mainComponent.className = this.options.mainClass; - hide(this.mainComponent); //configure unhide - - this.unhideEvent = this.unhideFields.bind(this); - this.unhide = this.createUnhide(); // Configure input - - var input; - - if (isString$2(this.options.inputField)) { - input = this.scope.querySelector(this.options.inputField); - } else { - input = this.options.inputField; - } - - if (!input) throw new Error("Address Finder: Unable to find valid input field"); - this.input = input; - this.input.setAttribute("autocomplete", this.options.autocomplete); - this.input.setAttribute("aria-autocomplete", "list"); - this.input.setAttribute("aria-controls", this.list.id); - this.input.setAttribute("aria-autocomplete", "list"); - this.input.setAttribute("aria-activedescendant", ""); - this.input.setAttribute("autocorrect", "off"); - this.input.setAttribute("autocapitalize", "off"); - this.input.setAttribute("spellcheck", "false"); - if (!this.input.id) this.input.id = this.ids(); // Apply additional accessibility improvments - - this.ariaAnchor().setAttribute("role", "combobox"); - this.ariaAnchor().setAttribute("aria-expanded", "false"); - this.ariaAnchor().setAttribute("aria-owns", this.list.id); - this.placeholderCache = this.input.placeholder; // Create listeners - - this.inputListener = _onInput(this); - this.blurListener = _onBlur(this); - this.focusListener = _onFocus(this); - this.keydownListener = _onKeyDown(this); - - var _announcer = announcer({ - idA: this.ids(), - idB: this.ids(), - document: this.options.document - }), - container = _announcer.container, - announce = _announcer.announce; - - this.announce = announce; - this.alerts = container; - this.inputStyle = setStyle(this.input, this.options.inputStyle); - setStyle(this.container, this.options.containerStyle); - setStyle(this.list, this.options.listStyle); // Apply an offset based off any margin - - var offset = computeOffset(this); - setStyle(this.mainComponent, _objectSpread$7(_objectSpread$7({}, offset), this.options.mainStyle)); - this.fsm = create({ - c: this - }); - this.init(); - } - /** - * Sets placeholder and caches previous result - * @hidden - */ - - - _createClass(Controller, [{ - key: "setPlaceholder", - value: function setPlaceholder(msg) { - this.input.placeholder = msg; - } - /** - * Unsets any placeholder value to original - * @hidden - */ - - }, { - key: "unsetPlaceholder", - value: function unsetPlaceholder() { - if (this.placeholderCache === undefined) return this.input.removeAttribute("placeholder"); - this.input.placeholder = this.placeholderCache; - } - /** - * Returns current highlighted context - * @hidden - */ - - }, { - key: "currentContext", - value: function currentContext() { - var c = this.options.contexts[this.context]; - return { - code: this.context, - name: c.name, - icon: c.icon - }; - } - /** - * Binds to DOM and begin DOM mutations - * @hidden - */ - - }, { - key: "load", - value: function load() { - this.attach(); - addStyle(this); - this.options.onLoaded.call(this); - } - /** - * Attaches Controller to the DOM. - * - * If `checkKey` is enabled, a key check will be performed prioer to binding. Use the `onLoaded` and `onFailedCheck` callbacks to define follow up behaviour if the key check succeeds or fails - */ - - }, { - key: "init", - value: function init() { - var _this2 = this; - - return new Promise(function (resolve) { - if (!_this2.options.checkKey) { - _this2.load(); - - resolve(); - return; - } - - checkKeyUsability$1({ - client: _this2.client, - api_key: _this2.options.apiKey - }).then(function (response) { - if (!response.available) throw new Error("Key currently not usable"); - - _this2.load(); - - resolve(); - }).catch(function (error) { - _this2.options.onFailedCheck.call(_this2, error); - - resolve(); - }); - }); - } - /** - * Render available country options - */ - - }, { - key: "renderContexts", - value: function renderContexts() { - var _this3 = this; - - this.list.innerHTML = ""; - this.contextSuggestions.forEach(function (contextDetails, i) { - var name = contextDetails.name; - - var li = _this3.options.document.createElement("li"); - - li.textContent = name; - li.setAttribute("aria-selected", "false"); - li.setAttribute("tabindex", "-1"); - li.setAttribute("aria-posinset", "".concat(i + 1)); - li.setAttribute("aria-setsize", _this3.contextSuggestions.length.toString()); - li.setAttribute("role", "option"); - setStyle(li, _this3.options.liStyle); - li.addEventListener("mousedown", function (e) { - e.preventDefault(); - - _this3.options.onMouseDown.call(_this3, e); - - _this3.fsm.send({ - type: "SELECT_COUNTRY", - contextDetails: contextDetails - }); - }); - li.id = "".concat(_this3.list.id, "_").concat(i); - - _this3.list.appendChild(li); - }); - this.announce("".concat(this.contextSuggestions.length, " countries available")); - } - /** - * Render current address suggestions - */ - - }, { - key: "renderSuggestions", - value: function renderSuggestions() { - var _this4 = this; - - this.list.innerHTML = ""; - var s = this.suggestions; - s.forEach(function (suggestion, i) { - var li = _this4.options.document.createElement("li"); - - li.textContent = suggestion.suggestion; - li.setAttribute("aria-selected", "false"); - li.setAttribute("tabindex", "-1"); - li.setAttribute("title", suggestion.suggestion); - li.setAttribute("aria-posinset", "".concat(i + 1)); - li.setAttribute("aria-setsize", s.length.toString()); - li.setAttribute("role", "option"); - setStyle(li, _this4.options.liStyle); - li.addEventListener("mousedown", function (e) { - e.preventDefault(); - - _this4.options.onMouseDown.call(_this4, e); - - _this4.fsm.send({ - type: "SELECT_ADDRESS", - suggestion: suggestion - }); - }); - li.id = "".concat(_this4.list.id, "_").concat(i); - - _this4.list.appendChild(li); - }); - this.announce("".concat(s.length, " addresses available")); - } - /** - * Updates current li in list to active descendant - */ - - }, { - key: "goToCurrent", - value: function goToCurrent() { - var lis = this.list.children; - this.input.setAttribute("aria-activedescendant", ""); - - for (var i = 0; i < lis.length; i += 1) { - if (i === this.current) { - this.input.setAttribute("aria-activedescendant", lis[i].id); - lis[i].setAttribute("aria-selected", "true"); - this.goto(i); - } else { - lis[i].setAttribute("aria-selected", "false"); - } - } - } - /** - * Marks aria component as opened - */ - - }, { - key: "ariaExpand", - value: function ariaExpand() { - this.ariaAnchor().setAttribute("aria-expanded", "true"); - } - /** - * Marks aria component as closed - */ - - }, { - key: "ariaContract", - value: function ariaContract() { - this.ariaAnchor().setAttribute("aria-expanded", "false"); - } - /** - * Resolves a suggestion to full address and apply results to form - */ - - }, { - key: "applySuggestion", - value: function applySuggestion(suggestion) { - var _this5 = this; - - this.options.onSelect.call(this, suggestion); - this.options.onAddressSelected.call(this, suggestion); - this.announce("The address ".concat(suggestion.suggestion, " has been applied to this form")); - return this.cache.resolve(suggestion).then(function (address) { - if (address === null) throw "Unable to retrieve address"; - - _this5.options.onAddressRetrieved.call(_this5, address); - - _this5.populateAddress(address); - - return _this5; - }).catch(function (error) { - _this5.open(); - - _this5.setMessage(_this5.options.msgFallback); - - _this5.options.onSearchError.call(_this5, error); - - return error; - }); - } - /** - * Writes a selected to the input fields specified in the controller config - */ - - }, { - key: "populateAddress", - value: function populateAddress$1(address) { - this.unhideFields(); - - populateAddress({ - address: address, - config: _objectSpread$7(_objectSpread$7({}, this.options), {}, { - scope: this.outputScope - }), - outputFields: this.options.outputFields, - names: this.options.names, - labels: this.options.labels - }); - - this.options.onAddressPopulated.call(this, address); - } - /** - * Applies new query options to search. This process clears the existing - * cache to prevent stale searches - */ - - }, { - key: "setQueryOptions", - value: function setQueryOptions(options) { - this.cache.clear(); - this.options.queryOptions = options; - } - /** - * Adds Address Finder to DOM - * - Wraps input with container - * - Appends suggestion list to container - * - Enables listeners - * - Starts FSM - */ - - }, { - key: "attach", - value: function attach() { - if (this.fsm.status === n.Running) return this; - this.input.addEventListener("input", this.inputListener); - this.input.addEventListener("blur", this.blurListener); - this.input.addEventListener("focus", this.focusListener); - this.input.addEventListener("keydown", this.keydownListener); - var parent = this.input.parentNode; - - if (parent) { - // Wrap input in a div and append suggestion list - parent.insertBefore(this.container, this.input); - this.container.appendChild(this.input); - this.container.appendChild(this.mainComponent); - this.container.appendChild(this.alerts); - if (this.options.hide.length > 0 && this.options.unhide == null) this.container.appendChild(this.unhide); - } - - this.fsm.start(); - this.options.onMounted.call(this); - this.hideFields(); - return this; - } - /** - * Removes Address Finder from DOM - * - Disable listeners - * - Removes sugestion list from container - * - Appends suggestion list to container - * - Enables listeners - * - Stops FSM - */ - - }, { - key: "detach", - value: function detach() { - if (this.fsm.status !== n.Running) return this; - this.input.removeEventListener("input", this.inputListener); - this.input.removeEventListener("blur", this.blurListener); - this.input.removeEventListener("focus", this.focusListener); - this.input.removeEventListener("keydown", this.keydownListener); - this.container.removeChild(this.mainComponent); - this.container.removeChild(this.alerts); - var parent = this.container.parentNode; - - if (parent) { - parent.insertBefore(this.input, this.container); - parent.removeChild(this.container); - } - - this.unmountUnhide(); - this.unhideFields(); - this.fsm.stop(); - restoreStyle(this.input, this.inputStyle); - this.options.onRemove.call(this); - this.unsetPlaceholder(); - return this; - } - /** - * Sets message as a list item, no or empty string removes any message - */ - - }, { - key: "setMessage", - value: function setMessage(notification) { - this.fsm.send({ - type: "NOTIFY", - notification: notification - }); - return this; - } - /** - * Returns HTML Element which recevies key aria attributes - * - * @hidden - */ - - }, { - key: "ariaAnchor", - value: function ariaAnchor() { - if (this.options.aria === "1.0") return this.input; - return this.container; - } - /** - * Returns current address query - */ - - }, { - key: "query", - value: function query() { - return this.input.value; - } - /** - * Set address finder suggestions - */ - - }, { - key: "setSuggestions", - value: function setSuggestions(suggestions, query) { - if (query !== this.query()) return this; - if (suggestions.length === 0) return this.setMessage(this.options.msgNoMatch); - this.fsm.send({ - type: "SUGGEST", - suggestions: suggestions - }); - return this; - } - /** - * Close address finder - */ - - }, { - key: "close", - value: function close() { - var reason = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "blur"; - hide(this.mainComponent); - if (reason === "esc") update(this.input, ""); - this.options.onClose.call(this, reason); - } - /** - * Updates suggestions and resets current selection - * @hidden - */ - - }, { - key: "updateSuggestions", - value: function updateSuggestions(s) { - this.suggestions = s; - this.current = -1; - } - /** - * Applies context to API cache - * @hidden - */ - - }, { - key: "applyContext", - value: function applyContext(details) { - var context = details.code; - this.context = context; - this.countryIcon.innerText = details.icon; - this.announce("Country switched to ".concat(details.name)); - } - /** - * Renders notification box - * @hidden - */ - - }, { - key: "renderNotice", - value: function renderNotice() { - this.list.innerHTML = ""; - this.input.setAttribute("aria-activedescendant", ""); - this.message.textContent = this.notification; - this.announce(this.notification); - this.list.appendChild(this.message); - } - /** - * Open address finder - * @hidden - */ - - }, { - key: "open", - value: function open() { - show(this.mainComponent); - this.options.onOpen.call(this); - } - /** - * Sets next suggestion as current - * @hidden - */ - - }, { - key: "next", - value: function next() { - if (this.current + 1 > this.list.children.length - 1) { - // Goes over edge of list and back to start - this.current = 0; - } else { - this.current += 1; - } - - return this; - } - /** - * Sets previous suggestion as current - * @hidden - */ - - }, { - key: "previous", - value: function previous() { - if (this.current - 1 < 0) { - this.current = this.list.children.length - 1; // Wrap to last elem - } else { - this.current += -1; - } - - return this; - } - /** - * Given a HTMLLiElement, scroll parent until it is in view - * @hidden - */ - - }, { - key: "scrollToView", - value: function scrollToView(li) { - var liOffset = li.offsetTop; - var ulScrollTop = this.list.scrollTop; - - if (liOffset < ulScrollTop) { - this.list.scrollTop = liOffset; - } - - var ulHeight = this.list.clientHeight; - var liHeight = li.clientHeight; - - if (liOffset + liHeight > ulScrollTop + ulHeight) { - this.list.scrollTop = liOffset - ulHeight + liHeight; - } - - return this; - } - /** - * Moves currently selected li into view - * @hidden - */ - - }, { - key: "goto", - value: function goto(i) { - var lis = this.list.children; - var suggestion = lis[i]; - - if (i > -1 && lis.length > 0) { - this.scrollToView(suggestion); - } else { - this.scrollToView(lis[0]); - } - - return this; - } - /** - * Returns true if address finder is open - */ - - }, { - key: "opened", - value: function opened() { - return !this.closed(); - } - /** - * Returs false if address finder is closed - */ - - }, { - key: "closed", - value: function closed() { - return this.fsm.state.matches("closed"); - } - /** - * Creates a clickable element that can trigger unhiding of fields - */ - - }, { - key: "createUnhide", - value: function createUnhide() { - var _this6 = this; - - var e = findOrCreate(this.scope, this.options.unhide, function () { - var e = _this6.options.document.createElement("p"); - - e.innerText = _this6.options.msgUnhide; - e.setAttribute("role", "button"); - e.setAttribute("tabindex", "0"); - if (_this6.options.unhideClass) e.className = _this6.options.unhideClass; - return e; - }); - e.addEventListener("click", this.unhideEvent); - return e; - } - /** - * Removes unhide elem from DOM - */ - - }, { - key: "unmountUnhide", - value: function unmountUnhide() { - this.unhide.removeEventListener("click", this.unhideEvent); - if (this.options.unhide == null && this.options.hide.length) remove(this.unhide); - } - }, { - key: "hiddenFields", - value: function hiddenFields() { - var _this7 = this; - - return this.options.hide.map(function (e) { - if (isString$2(e)) return toHtmlElem(_this7.options.scope, e); - return e; - }).filter(function (e) { - return e !== null; - }); - } - /** - * Hides fields marked for hiding - */ - - }, { - key: "hideFields", - value: function hideFields() { - this.hiddenFields().forEach(hide); - } - /** - * Unhides fields marked for hiding - */ - - }, { - key: "unhideFields", - value: function unhideFields() { - this.hiddenFields().forEach(show); - this.options.onUnhide.call(this); - } - }]); - - return Controller; - }(); - /** - * Event handler: Fires when focus moves away from input field - * @hidden - */ - - var _onBlur = function _onBlur(c) { - return function () { - c.options.onBlur.call(c); - c.fsm.send({ - type: "CLOSE", - reason: "blur" - }); - }; - }; - /** - * Event handler: Fires when input field is focused - * @hidden - */ - - - var _onFocus = function _onFocus(c) { - return function (_) { - c.options.onFocus.call(c); - c.fsm.send("AWAKE"); - }; - }; - /** - * Event handler: Fires when input is detected on input field - * @hidden - */ - - - var _onInput = function _onInput(c) { - return function (event) { - if (c.query().toLowerCase() === ":c") { - update(c.input, ""); - return c.fsm.send({ - type: "CHANGE_COUNTRY" - }); - } - - c.fsm.send({ - type: "INPUT", - event: event - }); - }; - }; - /** - * Event handler: Fires when country selection is clicked - * Triggers: - * - Country selection menu - * - * @hidden - */ - - - var _onCountryToggle = function _onCountryToggle(c) { - return function (e) { - e.preventDefault(); - c.fsm.send({ - type: "CHANGE_COUNTRY" - }); - }; - }; - /** - * Event handler: Fires on "keyDown" event of search field - * @hidden - */ - - - var _onKeyDown = function _onKeyDown(c) { - return function (event) { - // Dispatch events based on keys - var key = toKey(event); - if (key === "Enter") event.preventDefault(); - c.options.onKeyDown.call(c, event); - if (c.closed()) return c.fsm.send("AWAKE"); // When suggesting country - - if (c.fsm.state.matches("suggesting_country")) { - if (key === "Enter") { - var contextDetails = c.contextSuggestions[c.current]; - if (contextDetails) c.fsm.send({ - type: "SELECT_COUNTRY", - contextDetails: contextDetails - }); - } - - if (key === "Backspace") c.fsm.send({ - type: "INPUT", - event: event - }); - - if (key === "ArrowUp") { - event.preventDefault(); - c.fsm.send("PREVIOUS"); - } - - if (key === "ArrowDown") { - event.preventDefault(); - c.fsm.send("NEXT"); - } - } // When suggesting address - - - if (c.fsm.state.matches("suggesting")) { - if (key === "Enter") { - var suggestion = c.suggestions[c.current]; - if (suggestion) c.fsm.send({ - type: "SELECT_ADDRESS", - suggestion: suggestion - }); - } - - if (key === "Backspace") c.fsm.send({ - type: "INPUT", - event: event - }); - - if (key === "ArrowUp") { - event.preventDefault(); - c.fsm.send("PREVIOUS"); - } - - if (key === "ArrowDown") { - event.preventDefault(); - c.fsm.send("NEXT"); - } - } - - if (key === "Escape") c.fsm.send({ - type: "CLOSE", - reason: "esc" - }); - if (key === "Home") c.fsm.send({ - type: "RESET" - }); - if (key === "End") c.fsm.send({ - type: "RESET" - }); - }; - }; - /** - * Retrieve Element - * - If string, assumes is valid and returns first match within scope - * - If null, invokes the create method to return a default - * - If HTMLElement returns instance - * @hidden - */ - - var findOrCreate = function findOrCreate(scope, q, create) { - if (isString$2(q)) return scope.querySelector(q); - if (create && q === null) return create(); - return q; - }; - - /** - * Configure and launch an instance of the Address Finder - * - * This method will create and return a new AddressFinder instance. It will also add a global reference to the controller at `AddressFinder.controllers` - */ - - var setup$1 = function setup(config) { - var c = new Controller$1(config); - controllers$1.push(c); - return c; - }; - /** - * Configure and launch an instance of the Address Finder - * - * This is equivalent to invoking `setup` except inside a DOMContentLoaded event callback - */ - - var go = function go(config, d) { - return new Promise(function (resolve, _) { - (d || document).addEventListener("DOMContentLoaded", function (_) { - var c = setup$1(config); - return resolve(c); - }); - }).catch(function (_) { - return null; - }); - }; - /** - * Cache of Address Finder controllers - */ - - var controllers$1 = []; - - function ownKeys$6(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - - function _objectSpread$6(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$6(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$6(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - - var isTrue$1 = function isTrue() { - return true; - }; - - var getAnchors$1 = function getAnchors(config, marker) { - var scope = getScope$1(config.scope || null); - var matches = scope.querySelectorAll(config.anchor || config.inputField || (config.outputFields || {}).line_1); - return toArray(matches).filter(function (e) { - return !loaded(e, marker); - }); - }; - - var DEFAULT_INTERVAL = 1000; - - var formScope = function formScope(anchor) { - return getParent(anchor, "FORM"); - }; - /** - * Dynamically apply AddressFinder when relevant fields appear - * - Exits if page test is fails - * - Check if key usable - * - Creates a bind method - * - Retrives parent scope - * - Marks anchor if completed - * - Creates timer tools - */ - - - var watch$1 = function watch(config) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var client = new Client$2({ - api_key: config.apiKey - }); - var _options$pageTest = options.pageTest, - pageTest = _options$pageTest === void 0 ? isTrue$1 : _options$pageTest; - if (!pageTest()) return Promise.resolve(null); - return checkKeyUsability$1({ - client: client - }).then(function (key) { - if (!key.available) return null; - var _options$getScope = options.getScope, - getScope = _options$getScope === void 0 ? formScope : _options$getScope, - _options$interval = options.interval, - interval = _options$interval === void 0 ? DEFAULT_INTERVAL : _options$interval, - anchor = options.anchor, - _options$onBind = options.onBind, - onBind = _options$onBind === void 0 ? NOOP$3 : _options$onBind, - _options$onAnchorFoun = options.onAnchorFound, - onAnchorFound = _options$onAnchorFoun === void 0 ? NOOP$3 : _options$onAnchorFoun, - _options$onBindAttemp = options.onBindAttempt, - onBindAttempt = _options$onBindAttemp === void 0 ? NOOP$3 : _options$onBindAttemp, - _options$immediate = options.immediate, - immediate = _options$immediate === void 0 ? true : _options$immediate, - _options$marker = options.marker, - marker = _options$marker === void 0 ? "idpc" : _options$marker; - - var bind = function bind() { - onBindAttempt({ - config: config, - options: options - }); - getAnchors$1(_objectSpread$6({ - anchor: anchor - }, config), marker).forEach(function (anchor) { - var scope = getScope(anchor); - if (!scope) return; - - var newConfig = _objectSpread$6(_objectSpread$6({ - scope: scope - }, config), {}, { - checkKey: false - }); - - onAnchorFound({ - anchor: anchor, - scope: scope, - config: newConfig - }); - var c = setup$1(newConfig); - markLoaded(anchor, marker); - onBind(c); - }); - }; - - var _generateTimer = generateTimer({ - bind: bind, - pageTest: pageTest, - interval: interval - }), - start = _generateTimer.start, - stop = _generateTimer.stop; - - if (immediate) start(); - return { - start: start, - stop: stop, - bind: bind - }; - }).catch(function (e) { - // Swallow promise errors and raise via optionall onError callback - if (options.onError) options.onError(e); - return null; - }); - }; - - /** - * @module Address-Finder Exports - */ - /** - * Namespace that exports Address Finder methods and classes - */ - - var AddressFinder = { - setup: setup$1, - controllers: controllers$1, - Controller: Controller$1, - defaults: defaults$7, - watch: watch$1, - go: go - }; - - function ownKeys$5(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - - function _objectSpread$5(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$5(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$5(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - - /** - * @module Client - * - * @description HTTP API Client - */ - - /** - * Default configuration - */ - var defaults$6 = { - tls: true, - api_key: "", - baseUrl: "api.ideal-postcodes.co.uk", - version: "v1", - strictAuthorisation: false, - timeout: 10000, - header: { - Accept: "application/json", - "Content-Type": "application/json" - }, - tags: [], - agent: {} - }; - /** - * Client Class - */ - - var Client$1 = /*#__PURE__*/function () { - function Client(config) { - _classCallCheck(this, Client); - - this.config = _objectSpread$5(_objectSpread$5({}, defaults$6), config); - this.config.header = _objectSpread$5(_objectSpread$5({}, defaults$6.header), config.header && config.header); - } - /** - * Return base URL for API requests - */ - - - _createClass(Client, [{ - key: "url", - value: function url() { - var _this$config = this.config, - baseUrl = _this$config.baseUrl, - version = _this$config.version; - return "".concat(this.protocol(), "://").concat(baseUrl, "/").concat(version); - } - }, { - key: "protocol", - value: function protocol() { - return this.config.tls ? "https" : "http"; - } - }]); - - return Client; - }(); - - function ownKeys$4(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - - function _objectSpread$4(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$4(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$4(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - - /** - * @module Utils - */ - - /** - * toQuery - * - * Shallow copies object while omitting undefined attributes - */ - var toStringMap = function toStringMap(optional) { - if (optional === undefined) return {}; - return Object.keys(optional).reduce(function (result, key) { - var value = optional[key]; - var reduce = reduceStringMap(value); - if (reduce.length > 0) result[key] = reduce; - return result; - }, {}); - }; - - var isString$1 = function isString(i) { - return typeof i === "string"; - }; - - var isArray$1 = function isArray(i) { - return Array.isArray(i); - }; - - var reduceStringMap = function reduceStringMap(value) { - var result = []; - - if (isArray$1(value)) { - value.forEach(function (val) { - if (isNumber$1(val)) result.push(val.toString()); - if (isString$1(val)) result.push(val); - }); - return result.join(","); - } - - if (isNumber$1(value)) return value.toString(); - if (isString$1(value)) return value; - return ""; - }; - - var isNumber$1 = function isNumber(n) { - return typeof n === "number"; - }; - /** - * toTimeout - * - * Returns timeout value from request object. Delegates to default client - * timeout if not specified - */ - - - var toTimeout = function toTimeout(_ref, client) { - var timeout = _ref.timeout; - if (isNumber$1(timeout)) return timeout; - return client.config.timeout; - }; - /** - * toHeader - * - * Extracts HTTP Header object from request and client default headers - * - * Precendence is given to request specific headers - */ - - var toHeader$1 = function toHeader(_ref2, client) { - var _ref2$header = _ref2.header, - header = _ref2$header === void 0 ? {} : _ref2$header; - return _objectSpread$4(_objectSpread$4({}, client.config.header), toStringMap(header)); - }; - /** - * toAuthHeader - * - * Extracts credentials into authorization header format - */ - - var toAuthHeader = function toAuthHeader(client, options) { - var credentials = []; - var api_key = options.api_key || client.config.api_key; - credentials.push(["api_key", api_key]); - var licensee = options.licensee; - if (licensee !== undefined) credentials.push(["licensee", licensee]); - var user_token = options.user_token; - if (user_token !== undefined) credentials.push(["user_token", user_token]); - return "IDEALPOSTCODES ".concat(toCredentialString(credentials)); - }; - /** - * appendAuthorization - * - * Mutates a headers object to include Authorization header. Will insert if found: - * - api_key - * - licensee - * - user_token - */ - - var appendAuthorization = function appendAuthorization(_ref3) { - var header = _ref3.header, - options = _ref3.options, - client = _ref3.client; - header.Authorization = toAuthHeader(client, options); - return header; - }; - - var toCredentialString = function toCredentialString(credentials) { - return credentials.map(function (_ref4) { - var _ref5 = _slicedToArray(_ref4, 2), - key = _ref5[0], - value = _ref5[1]; - - return "".concat(key, "=\"").concat(value, "\""); - }).join(" "); - }; // Adds source IP to headers - - - var appendIp = function appendIp(_ref6) { - var header = _ref6.header, - options = _ref6.options; - var sourceIp = options.sourceIp; - if (sourceIp !== undefined) header["IDPC-Source-IP"] = sourceIp; - return header; - }; // Adds filters to query - - var appendFilter = function appendFilter(_ref7) { - var query = _ref7.query, - options = _ref7.options; - var filter = options.filter; - if (filter !== undefined) query.filter = filter.join(","); - return query; - }; // Adds tags to query - - var appendTags = function appendTags(_ref8) { - var client = _ref8.client, - query = _ref8.query, - options = _ref8.options; - var tags; - if (client.config.tags.length) tags = client.config.tags; - if (options.tags) tags = options.tags; - if (tags !== undefined) query.tags = tags.join(","); - return query; - }; // Adds pagination attributes to query - - var appendPage = function appendPage(_ref9) { - var query = _ref9.query, - options = _ref9.options; - var page = options.page, - limit = options.limit; - if (page !== undefined) query.page = page.toString(); - if (limit !== undefined) query.limit = limit.toString(); - return query; - }; - - function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } - - function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } - - /** - * @module Errors - * - * @description Exports error classes which may be returned by this client - */ - // Take note of https://github.com/Microsoft/TypeScript/issues/13965 - - /** - * IdealPostcodesError - * - * Base error class for all API responses that return an error. This class - * is used where a JSON body is not provided or invalid - * E.g. 503 rate limit response, JSON parse failure response - */ - var IdealPostcodesError$1 = /*#__PURE__*/function (_Error) { - _inherits(IdealPostcodesError, _Error); - - var _super = _createSuper$1(IdealPostcodesError); - - /** - * Instantiate IdealPostcodesError - */ - function IdealPostcodesError(options) { - var _this; - - _classCallCheck(this, IdealPostcodesError); - - var trueProto = (this instanceof IdealPostcodesError ? this.constructor : void 0).prototype; - _this = _super.call(this); - _this.__proto__ = trueProto; - var message = options.message, - httpStatus = options.httpStatus, - _options$metadata = options.metadata, - metadata = _options$metadata === void 0 ? {} : _options$metadata; - _this.message = message; - _this.name = "Ideal Postcodes Error"; - _this.httpStatus = httpStatus; - _this.metadata = metadata; - - if (Error.captureStackTrace) { - Error.captureStackTrace(_assertThisInitialized(_this), IdealPostcodesError); - } - - return _this; - } - - return IdealPostcodesError; - }( /*#__PURE__*/_wrapNativeSuper(Error)); - /** - * IdpcApiError - * - * Base error class for API responses with a JSON body. Typically a subclass - * will be used to capture the error category (e.g. 400, 401, 500, etc) - */ - - var IdpcApiError = /*#__PURE__*/function (_IdealPostcodesError) { - _inherits(IdpcApiError, _IdealPostcodesError); - - var _super2 = _createSuper$1(IdpcApiError); - - /** - * Returns an API error instance - */ - function IdpcApiError(httpResponse) { - var _this2; - - _classCallCheck(this, IdpcApiError); - - _this2 = _super2.call(this, { - httpStatus: httpResponse.httpStatus, - message: httpResponse.body.message - }); - _this2.response = httpResponse; - return _this2; - } - - return IdpcApiError; - }(IdealPostcodesError$1); - /** - * IdpcBadRequestError - * - * Captures API responses that return a 400 (Bad Request Error) response - * - * Examples include: - * - Invalid syntax submitted - * - Invalid date range submitted - * - Invalid tag submitted - */ - - var IdpcBadRequestError = /*#__PURE__*/function (_IdpcApiError) { - _inherits(IdpcBadRequestError, _IdpcApiError); - - var _super3 = _createSuper$1(IdpcBadRequestError); - - function IdpcBadRequestError() { - _classCallCheck(this, IdpcBadRequestError); - - return _super3.apply(this, arguments); - } - - return IdpcBadRequestError; - }(IdpcApiError); - /** - * IdpcUnauthorisedError - * - * Captures API responses that return a 401 (Unauthorised) response - * - * Examples include: - * - Invalid api_key - * - Invalid user_token - * - Invalid licensee - */ - - var IdpcUnauthorisedError = /*#__PURE__*/function (_IdpcApiError2) { - _inherits(IdpcUnauthorisedError, _IdpcApiError2); - - var _super4 = _createSuper$1(IdpcUnauthorisedError); - - function IdpcUnauthorisedError() { - _classCallCheck(this, IdpcUnauthorisedError); - - return _super4.apply(this, arguments); - } - - return IdpcUnauthorisedError; - }(IdpcApiError); - /** - * IpdcInvalidKeyError - * - * Invalid API Key presented for request - */ - - var IdpcInvalidKeyError = /*#__PURE__*/function (_IdpcUnauthorisedErro) { - _inherits(IdpcInvalidKeyError, _IdpcUnauthorisedErro); - - var _super5 = _createSuper$1(IdpcInvalidKeyError); - - function IdpcInvalidKeyError() { - _classCallCheck(this, IdpcInvalidKeyError); - - return _super5.apply(this, arguments); - } - - return IdpcInvalidKeyError; - }(IdpcUnauthorisedError); - /** - * IdpcRequestFailedError - * - * Captures API responses that return a 402 (Request Failed) response - * - * Examples include: - * - Key balance depleted - * - Daily key limit reached - */ - - var IdpcRequestFailedError = /*#__PURE__*/function (_IdpcApiError3) { - _inherits(IdpcRequestFailedError, _IdpcApiError3); - - var _super6 = _createSuper$1(IdpcRequestFailedError); - - function IdpcRequestFailedError() { - _classCallCheck(this, IdpcRequestFailedError); - - return _super6.apply(this, arguments); - } - - return IdpcRequestFailedError; - }(IdpcApiError); - /** - * IdpcBalanceDepleted - * - * Balance on key has been depleted - */ - - var IdpcBalanceDepletedError = /*#__PURE__*/function (_IdpcRequestFailedErr) { - _inherits(IdpcBalanceDepletedError, _IdpcRequestFailedErr); - - var _super7 = _createSuper$1(IdpcBalanceDepletedError); - - function IdpcBalanceDepletedError() { - _classCallCheck(this, IdpcBalanceDepletedError); - - return _super7.apply(this, arguments); - } - - return IdpcBalanceDepletedError; - }(IdpcRequestFailedError); - /** - * IdpcLimitReachedError - * - * Limit reached. One of your lookup limits has been breached for today. This - * could either be your total daily limit on your key or the individual IP - * limit. You can either wait for for the limit to reset (after a day) or - * manually disable or increase your limit. - */ - - var IdpcLimitReachedError = /*#__PURE__*/function (_IdpcRequestFailedErr2) { - _inherits(IdpcLimitReachedError, _IdpcRequestFailedErr2); - - var _super8 = _createSuper$1(IdpcLimitReachedError); - - function IdpcLimitReachedError() { - _classCallCheck(this, IdpcLimitReachedError); - - return _super8.apply(this, arguments); - } - - return IdpcLimitReachedError; - }(IdpcRequestFailedError); - /** - * IdpcResourceNotFoundError - * - * Captures API responses that return a 404 (Resource Not Found) response - * - * Examples include: - * - Postcode not found - * - UDPRN not found - * - Key not found - */ - - var IdpcResourceNotFoundError = /*#__PURE__*/function (_IdpcApiError4) { - _inherits(IdpcResourceNotFoundError, _IdpcApiError4); - - var _super9 = _createSuper$1(IdpcResourceNotFoundError); - - function IdpcResourceNotFoundError() { - _classCallCheck(this, IdpcResourceNotFoundError); - - return _super9.apply(this, arguments); - } - - return IdpcResourceNotFoundError; - }(IdpcApiError); - /** - * IdpcPostcodeNotFoundError - * - * Requested postcode does not exist - */ - - var IdpcPostcodeNotFoundError = /*#__PURE__*/function (_IdpcResourceNotFound) { - _inherits(IdpcPostcodeNotFoundError, _IdpcResourceNotFound); - - var _super10 = _createSuper$1(IdpcPostcodeNotFoundError); - - function IdpcPostcodeNotFoundError() { - _classCallCheck(this, IdpcPostcodeNotFoundError); - - return _super10.apply(this, arguments); - } - - return IdpcPostcodeNotFoundError; - }(IdpcResourceNotFoundError); - /** - * IdpcKeyNotFoundError - * - * Requested API Key does not exist - */ - - var IdpcKeyNotFoundError = /*#__PURE__*/function (_IdpcResourceNotFound2) { - _inherits(IdpcKeyNotFoundError, _IdpcResourceNotFound2); - - var _super11 = _createSuper$1(IdpcKeyNotFoundError); - - function IdpcKeyNotFoundError() { - _classCallCheck(this, IdpcKeyNotFoundError); - - return _super11.apply(this, arguments); - } - - return IdpcKeyNotFoundError; - }(IdpcResourceNotFoundError); - /** - * IdpcUdprnNotFoundError - * - * Requested UDPRN does not exist - */ - - var IdpcUdprnNotFoundError = /*#__PURE__*/function (_IdpcResourceNotFound3) { - _inherits(IdpcUdprnNotFoundError, _IdpcResourceNotFound3); - - var _super12 = _createSuper$1(IdpcUdprnNotFoundError); - - function IdpcUdprnNotFoundError() { - _classCallCheck(this, IdpcUdprnNotFoundError); - - return _super12.apply(this, arguments); - } - - return IdpcUdprnNotFoundError; - }(IdpcResourceNotFoundError); - /** - * IdpcUmprnNotFoundError - * - * Requested UMPRN does not exist - */ - - var IdpcUmprnNotFoundError = /*#__PURE__*/function (_IdpcResourceNotFound4) { - _inherits(IdpcUmprnNotFoundError, _IdpcResourceNotFound4); - - var _super13 = _createSuper$1(IdpcUmprnNotFoundError); - - function IdpcUmprnNotFoundError() { - _classCallCheck(this, IdpcUmprnNotFoundError); - - return _super13.apply(this, arguments); - } - - return IdpcUmprnNotFoundError; - }(IdpcResourceNotFoundError); - /** - * IdpcServerError - * - * Captures API responses that return a 500 (Server Error) response - */ - - var IdpcServerError = /*#__PURE__*/function (_IdpcApiError5) { - _inherits(IdpcServerError, _IdpcApiError5); - - var _super14 = _createSuper$1(IdpcServerError); - - function IdpcServerError() { - _classCallCheck(this, IdpcServerError); - - return _super14.apply(this, arguments); - } - - return IdpcServerError; - }(IdpcApiError); // 200 Responses - - var OK = 200; // 300 Responses - - var REDIRECT = 300; // 400 Responses - - var BAD_REQUEST = 400; // 401 Responses - - var UNAUTHORISED = 401; - var INVALID_KEY = 4010; // 402 Responses - - var PAYMENT_REQUIRED = 402; - var BALANCE_DEPLETED = 4020; - var LIMIT_REACHED = 4021; // 404 Responses - - var NOT_FOUND = 404; - var POSTCODE_NOT_FOUND = 4040; - var KEY_NOT_FOUND = 4042; - var UDPRN_NOT_FOUND = 4044; - var UMPRN_NOT_FOUND = 4046; // 500 Responses - - var SERVER_ERROR = 500; - - var isSuccess = function isSuccess(code) { - if (code < OK) return false; - if (code >= REDIRECT) return false; - return true; - }; - - var isObject$1 = function isObject(o) { - if (o === null) return false; - if (_typeof(o) !== "object") return false; - return true; - }; - - var isErrorResponse = function isErrorResponse(body) { - if (!isObject$1(body)) return false; - if (typeof body.message !== "string") return false; - if (typeof body.code !== "number") return false; - return true; - }; - /** - * parse - * - * Parses API responses and returns an error for non 2xx responses - * - * Upon detecting an error an instance of IdealPostcodesError is returned - */ - - - var parse = function parse(response) { - var httpStatus = response.httpStatus, - body = response.body; - if (isSuccess(httpStatus)) return; - - if (isErrorResponse(body)) { - // Test for specific API errors of interest - var code = body.code; - if (code === INVALID_KEY) return new IdpcInvalidKeyError(response); - if (code === POSTCODE_NOT_FOUND) return new IdpcPostcodeNotFoundError(response); - if (code === KEY_NOT_FOUND) return new IdpcKeyNotFoundError(response); - if (code === UDPRN_NOT_FOUND) return new IdpcUdprnNotFoundError(response); - if (code === UMPRN_NOT_FOUND) return new IdpcUmprnNotFoundError(response); - if (code === BALANCE_DEPLETED) return new IdpcBalanceDepletedError(response); - if (code === LIMIT_REACHED) return new IdpcLimitReachedError(response); // If no API errors of interest detected, fall back to http status code - - if (httpStatus === NOT_FOUND) return new IdpcResourceNotFoundError(response); - if (httpStatus === BAD_REQUEST) return new IdpcBadRequestError(response); - if (httpStatus === PAYMENT_REQUIRED) return new IdpcRequestFailedError(response); - if (httpStatus === UNAUTHORISED) return new IdpcUnauthorisedError(response); - if (httpStatus === SERVER_ERROR) return new IdpcServerError(response); - } // Generate generic error (backstop) - - - return new IdealPostcodesError$1({ - httpStatus: httpStatus, - message: JSON.stringify(body) - }); - }; - - var toRetrieveUrl = function toRetrieveUrl(options, id) { - return [options.client.url(), options.resource, encodeURIComponent(id), options.action].filter(function (e) { - return e !== undefined; - }).join("/"); - }; - - var retrieveMethod = function retrieveMethod(options) { - var client = options.client; - return function (id, request) { - return client.config.agent.http({ - method: "GET", - url: toRetrieveUrl(options, id), - query: toStringMap(request.query), - header: toHeader$1(request, client), - timeout: toTimeout(request, client) - }).then(function (response) { - var error = parse(response); - if (error) throw error; - return response; - }); - }; - }; - var listMethod = function listMethod(options) { - var client = options.client, - resource = options.resource; - return function (request) { - return client.config.agent.http({ - method: "GET", - url: "".concat(client.url(), "/").concat(resource), - query: toStringMap(request.query), - header: toHeader$1(request, client), - timeout: toTimeout(request, client) - }).then(function (response) { - var error = parse(response); - if (error) throw error; - return response; - }); - }; - }; - - var resource$2 = "addresses"; - var list = function list(client, request) { - return listMethod({ - resource: resource$2, - client: client - })(request); - }; - - var resource$1 = "keys"; - var retrieve$1 = function retrieve(client, apiKey, request) { - return retrieveMethod({ - resource: resource$1, - client: client - })(apiKey, request); - }; - - var resource = "postcodes"; - var retrieve = function retrieve(client, postcode, request) { - return retrieveMethod({ - resource: resource, - client: client - })(postcode, request); - }; - - /** - * @module Helper Methods - */ - /** - * Lookup Postcode - * - * Search for addresses given a postcode. Postcode queries are case and space insensitive - * - * Invalid postcodes return an empty array address result `[]` - * - * [API Documentation for /postcodes](https://ideal-postcodes.co.uk/documentation/postcodes#postcode) - */ - - var lookupPostcode = function lookupPostcode(options) { - var queryOptions = toAddressIdQuery(options); - var page = options.page; - if (page !== undefined) queryOptions.query.page = page.toString(); - return retrieve(options.client, options.postcode, queryOptions).then(function (response) { - return response.body.result; - }).catch(function (error) { - if (error instanceof IdpcPostcodeNotFoundError) return []; - throw error; - }); - }; - /** - * Lookup Address - * - * Search for an address given a query - * - * [API Documentation for /addresses](https://ideal-postcodes.co.uk/documentation/addresses#query) - */ - - var lookupAddress = function lookupAddress(options) { - var header = {}; - var query = { - query: options.query - }; - var client = options.client; - appendAuthorization({ - client: client, - header: header, - options: options - }); - appendIp({ - header: header, - options: options - }); - appendFilter({ - query: query, - options: options - }); - appendTags({ - client: client, - query: query, - options: options - }); - appendPage({ - query: query, - options: options - }); - var queryOptions = { - header: header, - query: query - }; - if (options.timeout !== undefined) queryOptions.timeout = options.timeout; - return list(client, queryOptions).then(function (response) { - return response.body.result.hits; - }); - }; - /** - * Generates a request object. Bundles together commonly used header/query extractions: - * - Authorization (api_key, licensee, user_token) - * - Source IP forwarding - * - Result filtering - * - Tagging - */ - - var toAddressIdQuery = function toAddressIdQuery(options) { - var header = {}; - var query = {}; - var client = options.client; - appendAuthorization({ - client: client, - header: header, - options: options - }); - appendIp({ - header: header, - options: options - }); - appendFilter({ - query: query, - options: options - }); - appendTags({ - client: client, - query: query, - options: options - }); - var request = { - header: header, - query: query - }; - if (options.timeout !== undefined) request.timeout = options.timeout; - return request; - }; - /** - * Check Key Availability - * - * Checks if a key can bey used - * - * [API Documentation for /keys]()https://ideal-postcodes.co.uk/documentation/keys#key) - */ - - var checkKeyUsability = function checkKeyUsability(options) { - var client = options.client, - timeout = options.timeout; - var api_key = options.api_key || options.client.config.api_key; - var licensee = options.licensee; - var query; - - if (licensee === undefined) { - query = {}; - } else { - query = { - licensee: licensee - }; - } - - var queryOptions = { - query: query, - header: {} - }; - if (timeout !== undefined) queryOptions.timeout = timeout; - return retrieve$1(client, api_key, queryOptions).then(function (response) { - return response.body.result; - }); // Assert that we're retrieving public key information as no user_token provided - }; - - var axios$2 = {exports: {}}; - - var bind$6 = function bind(fn, thisArg) { - return function wrap() { - var args = new Array(arguments.length); - - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } - - return fn.apply(thisArg, args); - }; - }; - - var bind$5 = bind$6; // utils is a library of generic helper functions non-specific to axios - - var toString = Object.prototype.toString; - /** - * Determine if a value is an Array - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an Array, otherwise false - */ - - function isArray(val) { - return toString.call(val) === '[object Array]'; - } - /** - * Determine if a value is undefined - * - * @param {Object} val The value to test - * @returns {boolean} True if the value is undefined, otherwise false - */ - - - function isUndefined(val) { - return typeof val === 'undefined'; - } - /** - * Determine if a value is a Buffer - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Buffer, otherwise false - */ - - - function isBuffer(val) { - return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); - } - /** - * Determine if a value is an ArrayBuffer - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an ArrayBuffer, otherwise false - */ - - - function isArrayBuffer(val) { - return toString.call(val) === '[object ArrayBuffer]'; - } - /** - * Determine if a value is a FormData - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an FormData, otherwise false - */ - - - function isFormData(val) { - return typeof FormData !== 'undefined' && val instanceof FormData; - } - /** - * Determine if a value is a view on an ArrayBuffer - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false - */ - - - function isArrayBufferView(val) { - var result; - - if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) { - result = ArrayBuffer.isView(val); - } else { - result = val && val.buffer && val.buffer instanceof ArrayBuffer; - } - - return result; - } - /** - * Determine if a value is a String - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a String, otherwise false - */ - - - function isString(val) { - return typeof val === 'string'; - } - /** - * Determine if a value is a Number - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Number, otherwise false - */ - - - function isNumber(val) { - return typeof val === 'number'; - } - /** - * Determine if a value is an Object - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an Object, otherwise false - */ - - - function isObject(val) { - return val !== null && _typeof(val) === 'object'; - } - /** - * Determine if a value is a plain Object - * - * @param {Object} val The value to test - * @return {boolean} True if value is a plain Object, otherwise false - */ - - - function isPlainObject(val) { - if (toString.call(val) !== '[object Object]') { - return false; - } - - var prototype = Object.getPrototypeOf(val); - return prototype === null || prototype === Object.prototype; - } - /** - * Determine if a value is a Date - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Date, otherwise false - */ - - - function isDate(val) { - return toString.call(val) === '[object Date]'; - } - /** - * Determine if a value is a File - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a File, otherwise false - */ - - - function isFile(val) { - return toString.call(val) === '[object File]'; - } - /** - * Determine if a value is a Blob - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Blob, otherwise false - */ - - - function isBlob(val) { - return toString.call(val) === '[object Blob]'; - } - /** - * Determine if a value is a Function - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Function, otherwise false - */ - - - function isFunction(val) { - return toString.call(val) === '[object Function]'; - } - /** - * Determine if a value is a Stream - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Stream, otherwise false - */ - - - function isStream(val) { - return isObject(val) && isFunction(val.pipe); - } - /** - * Determine if a value is a URLSearchParams object - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a URLSearchParams object, otherwise false - */ - - - function isURLSearchParams(val) { - return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; - } - /** - * Trim excess whitespace off the beginning and end of a string - * - * @param {String} str The String to trim - * @returns {String} The String freed of excess whitespace - */ - - - function trim(str) { - return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, ''); - } - /** - * Determine if we're running in a standard browser environment - * - * This allows axios to run in a web worker, and react-native. - * Both environments support XMLHttpRequest, but not fully standard globals. - * - * web workers: - * typeof window -> undefined - * typeof document -> undefined - * - * react-native: - * navigator.product -> 'ReactNative' - * nativescript - * navigator.product -> 'NativeScript' or 'NS' - */ - - - function isStandardBrowserEnv() { - if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || navigator.product === 'NativeScript' || navigator.product === 'NS')) { - return false; - } - - return typeof window !== 'undefined' && typeof document !== 'undefined'; - } - /** - * Iterate over an Array or an Object invoking a function for each item. - * - * If `obj` is an Array callback will be called passing - * the value, index, and complete array for each item. - * - * If 'obj' is an Object callback will be called passing - * the value, key, and complete object for each property. - * - * @param {Object|Array} obj The object to iterate - * @param {Function} fn The callback to invoke for each item - */ - - - function forEach(obj, fn) { - // Don't bother if no value provided - if (obj === null || typeof obj === 'undefined') { - return; - } // Force an array if not already something iterable - - - if (_typeof(obj) !== 'object') { - /*eslint no-param-reassign:0*/ - obj = [obj]; - } - - if (isArray(obj)) { - // Iterate over array values - for (var i = 0, l = obj.length; i < l; i++) { - fn.call(null, obj[i], i, obj); - } - } else { - // Iterate over object keys - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - fn.call(null, obj[key], key, obj); - } - } - } - } - /** - * Accepts varargs expecting each argument to be an object, then - * immutably merges the properties of each object and returns result. - * - * When multiple objects contain the same key the later object in - * the arguments list will take precedence. - * - * Example: - * - * ```js - * var result = merge({foo: 123}, {foo: 456}); - * console.log(result.foo); // outputs 456 - * ``` - * - * @param {Object} obj1 Object to merge - * @returns {Object} Result of all merge properties - */ - - - function merge() { - var result = {}; - - function assignValue(val, key) { - if (isPlainObject(result[key]) && isPlainObject(val)) { - result[key] = merge(result[key], val); - } else if (isPlainObject(val)) { - result[key] = merge({}, val); - } else if (isArray(val)) { - result[key] = val.slice(); - } else { - result[key] = val; - } - } - - for (var i = 0, l = arguments.length; i < l; i++) { - forEach(arguments[i], assignValue); - } - - return result; - } - /** - * Extends object a by mutably adding to it the properties of object b. - * - * @param {Object} a The object to be extended - * @param {Object} b The object to copy properties from - * @param {Object} thisArg The object to bind function to - * @return {Object} The resulting value of object a - */ - - - function extend(a, b, thisArg) { - forEach(b, function assignValue(val, key) { - if (thisArg && typeof val === 'function') { - a[key] = bind$5(val, thisArg); - } else { - a[key] = val; - } - }); - return a; - } - /** - * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) - * - * @param {string} content with BOM - * @return {string} content value without BOM - */ - - - function stripBOM(content) { - if (content.charCodeAt(0) === 0xFEFF) { - content = content.slice(1); - } - - return content; - } - - var utils$d = { - isArray: isArray, - isArrayBuffer: isArrayBuffer, - isBuffer: isBuffer, - isFormData: isFormData, - isArrayBufferView: isArrayBufferView, - isString: isString, - isNumber: isNumber, - isObject: isObject, - isPlainObject: isPlainObject, - isUndefined: isUndefined, - isDate: isDate, - isFile: isFile, - isBlob: isBlob, - isFunction: isFunction, - isStream: isStream, - isURLSearchParams: isURLSearchParams, - isStandardBrowserEnv: isStandardBrowserEnv, - forEach: forEach, - merge: merge, - extend: extend, - trim: trim, - stripBOM: stripBOM - }; - - var utils$c = utils$d; - - function encode(val) { - return encodeURIComponent(val).replace(/%3A/gi, ':').replace(/%24/g, '$').replace(/%2C/gi, ',').replace(/%20/g, '+').replace(/%5B/gi, '[').replace(/%5D/gi, ']'); - } - /** - * Build a URL by appending params to the end - * - * @param {string} url The base of the url (e.g., http://www.google.com) - * @param {object} [params] The params to be appended - * @returns {string} The formatted url - */ - - - var buildURL$2 = function buildURL(url, params, paramsSerializer) { - /*eslint no-param-reassign:0*/ - if (!params) { - return url; - } - - var serializedParams; - - if (paramsSerializer) { - serializedParams = paramsSerializer(params); - } else if (utils$c.isURLSearchParams(params)) { - serializedParams = params.toString(); - } else { - var parts = []; - utils$c.forEach(params, function serialize(val, key) { - if (val === null || typeof val === 'undefined') { - return; - } - - if (utils$c.isArray(val)) { - key = key + '[]'; - } else { - val = [val]; - } - - utils$c.forEach(val, function parseValue(v) { - if (utils$c.isDate(v)) { - v = v.toISOString(); - } else if (utils$c.isObject(v)) { - v = JSON.stringify(v); - } - - parts.push(encode(key) + '=' + encode(v)); - }); - }); - serializedParams = parts.join('&'); - } - - if (serializedParams) { - var hashmarkIndex = url.indexOf('#'); - - if (hashmarkIndex !== -1) { - url = url.slice(0, hashmarkIndex); - } - - url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; - } - - return url; - }; - - var utils$b = utils$d; - - function InterceptorManager$1() { - this.handlers = []; - } - /** - * Add a new interceptor to the stack - * - * @param {Function} fulfilled The function to handle `then` for a `Promise` - * @param {Function} rejected The function to handle `reject` for a `Promise` - * - * @return {Number} An ID used to remove interceptor later - */ - - - InterceptorManager$1.prototype.use = function use(fulfilled, rejected, options) { - this.handlers.push({ - fulfilled: fulfilled, - rejected: rejected, - synchronous: options ? options.synchronous : false, - runWhen: options ? options.runWhen : null - }); - return this.handlers.length - 1; - }; - /** - * Remove an interceptor from the stack - * - * @param {Number} id The ID that was returned by `use` - */ - - - InterceptorManager$1.prototype.eject = function eject(id) { - if (this.handlers[id]) { - this.handlers[id] = null; - } - }; - /** - * Iterate over all the registered interceptors - * - * This method is particularly useful for skipping over any - * interceptors that may have become `null` calling `eject`. - * - * @param {Function} fn The function to call for each interceptor - */ - - - InterceptorManager$1.prototype.forEach = function forEach(fn) { - utils$b.forEach(this.handlers, function forEachHandler(h) { - if (h !== null) { - fn(h); - } - }); - }; - - var InterceptorManager_1 = InterceptorManager$1; - - var utils$a = utils$d; - - var normalizeHeaderName$1 = function normalizeHeaderName(headers, normalizedName) { - utils$a.forEach(headers, function processHeader(value, name) { - if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { - headers[normalizedName] = value; - delete headers[name]; - } - }); - }; - - /** - * Update an Error with the specified config, error code, and response. - * - * @param {Error} error The error to update. - * @param {Object} config The config. - * @param {string} [code] The error code (for example, 'ECONNABORTED'). - * @param {Object} [request] The request. - * @param {Object} [response] The response. - * @returns {Error} The error. - */ - - - var enhanceError$2 = function enhanceError(error, config, code, request, response) { - error.config = config; - - if (code) { - error.code = code; - } - - error.request = request; - error.response = response; - error.isAxiosError = true; - - error.toJSON = function toJSON() { - return { - // Standard - message: this.message, - name: this.name, - // Microsoft - description: this.description, - number: this.number, - // Mozilla - fileName: this.fileName, - lineNumber: this.lineNumber, - columnNumber: this.columnNumber, - stack: this.stack, - // Axios - config: this.config, - code: this.code, - status: this.response && this.response.status ? this.response.status : null - }; - }; - - return error; - }; - - var enhanceError$1 = enhanceError$2; - /** - * Create an Error with the specified message, config, error code, request and response. - * - * @param {string} message The error message. - * @param {Object} config The config. - * @param {string} [code] The error code (for example, 'ECONNABORTED'). - * @param {Object} [request] The request. - * @param {Object} [response] The response. - * @returns {Error} The created error. - */ - - var createError$2 = function createError(message, config, code, request, response) { - var error = new Error(message); - return enhanceError$1(error, config, code, request, response); - }; - - var createError$1 = createError$2; - /** - * Resolve or reject a Promise based on response status. - * - * @param {Function} resolve A function that resolves the promise. - * @param {Function} reject A function that rejects the promise. - * @param {object} response The response. - */ - - var settle$1 = function settle(resolve, reject, response) { - var validateStatus = response.config.validateStatus; - - if (!response.status || !validateStatus || validateStatus(response.status)) { - resolve(response); - } else { - reject(createError$1('Request failed with status code ' + response.status, response.config, null, response.request, response)); - } - }; - - var utils$9 = utils$d; - var cookies$1 = utils$9.isStandardBrowserEnv() ? // Standard browser envs support document.cookie - function standardBrowserEnv() { - return { - write: function write(name, value, expires, path, domain, secure) { - var cookie = []; - cookie.push(name + '=' + encodeURIComponent(value)); - - if (utils$9.isNumber(expires)) { - cookie.push('expires=' + new Date(expires).toGMTString()); - } - - if (utils$9.isString(path)) { - cookie.push('path=' + path); - } - - if (utils$9.isString(domain)) { - cookie.push('domain=' + domain); - } - - if (secure === true) { - cookie.push('secure'); - } - - document.cookie = cookie.join('; '); - }, - read: function read(name) { - var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); - return match ? decodeURIComponent(match[3]) : null; - }, - remove: function remove(name) { - this.write(name, '', Date.now() - 86400000); - } - }; - }() : // Non standard browser env (web workers, react-native) lack needed support. - function nonStandardBrowserEnv() { - return { - write: function write() {}, - read: function read() { - return null; - }, - remove: function remove() {} - }; - }(); - - /** - * Determines whether the specified URL is absolute - * - * @param {string} url The URL to test - * @returns {boolean} True if the specified URL is absolute, otherwise false - */ - - - var isAbsoluteURL$1 = function isAbsoluteURL(url) { - // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). - // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed - // by any combination of letters, digits, plus, period, or hyphen. - return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); - }; - - /** - * Creates a new URL by combining the specified URLs - * - * @param {string} baseURL The base URL - * @param {string} relativeURL The relative URL - * @returns {string} The combined URL - */ - - - var combineURLs$1 = function combineURLs(baseURL, relativeURL) { - return relativeURL ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') : baseURL; - }; - - var isAbsoluteURL = isAbsoluteURL$1; - var combineURLs = combineURLs$1; - /** - * Creates a new URL by combining the baseURL with the requestedURL, - * only when the requestedURL is not already an absolute URL. - * If the requestURL is absolute, this function returns the requestedURL untouched. - * - * @param {string} baseURL The base URL - * @param {string} requestedURL Absolute or relative URL to combine - * @returns {string} The combined full path - */ - - var buildFullPath$1 = function buildFullPath(baseURL, requestedURL) { - if (baseURL && !isAbsoluteURL(requestedURL)) { - return combineURLs(baseURL, requestedURL); - } - - return requestedURL; - }; - - var utils$8 = utils$d; // Headers whose duplicates are ignored by node - // c.f. https://nodejs.org/api/http.html#http_message_headers - - var ignoreDuplicateOf = ['age', 'authorization', 'content-length', 'content-type', 'etag', 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', 'last-modified', 'location', 'max-forwards', 'proxy-authorization', 'referer', 'retry-after', 'user-agent']; - /** - * Parse headers into an object - * - * ``` - * Date: Wed, 27 Aug 2014 08:58:49 GMT - * Content-Type: application/json - * Connection: keep-alive - * Transfer-Encoding: chunked - * ``` - * - * @param {String} headers Headers needing to be parsed - * @returns {Object} Headers parsed into an object - */ - - var parseHeaders$1 = function parseHeaders(headers) { - var parsed = {}; - var key; - var val; - var i; - - if (!headers) { - return parsed; - } - - utils$8.forEach(headers.split('\n'), function parser(line) { - i = line.indexOf(':'); - key = utils$8.trim(line.substr(0, i)).toLowerCase(); - val = utils$8.trim(line.substr(i + 1)); - - if (key) { - if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { - return; - } - - if (key === 'set-cookie') { - parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); - } else { - parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; - } - } - }); - return parsed; - }; - - var utils$7 = utils$d; - var isURLSameOrigin$1 = utils$7.isStandardBrowserEnv() ? // Standard browser envs have full support of the APIs needed to test - // whether the request URL is of the same origin as current location. - function standardBrowserEnv() { - var msie = /(msie|trident)/i.test(navigator.userAgent); - var urlParsingNode = document.createElement('a'); - var originURL; - /** - * Parse a URL to discover it's components - * - * @param {String} url The URL to be parsed - * @returns {Object} - */ - - function resolveURL(url) { - var href = url; - - if (msie) { - // IE needs attribute set twice to normalize properties - urlParsingNode.setAttribute('href', href); - href = urlParsingNode.href; - } - - urlParsingNode.setAttribute('href', href); // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils - - return { - href: urlParsingNode.href, - protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', - host: urlParsingNode.host, - search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', - hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', - hostname: urlParsingNode.hostname, - port: urlParsingNode.port, - pathname: urlParsingNode.pathname.charAt(0) === '/' ? urlParsingNode.pathname : '/' + urlParsingNode.pathname - }; - } - - originURL = resolveURL(window.location.href); - /** - * Determine if a URL shares the same origin as the current location - * - * @param {String} requestURL The URL to test - * @returns {boolean} True if URL shares the same origin, otherwise false - */ - - return function isURLSameOrigin(requestURL) { - var parsed = utils$7.isString(requestURL) ? resolveURL(requestURL) : requestURL; - return parsed.protocol === originURL.protocol && parsed.host === originURL.host; - }; - }() : // Non standard browser envs (web workers, react-native) lack needed support. - function nonStandardBrowserEnv() { - return function isURLSameOrigin() { - return true; - }; - }(); - - /** - * A `Cancel` is an object that is thrown when an operation is canceled. - * - * @class - * @param {string=} message The message. - */ - - - function Cancel$3(message) { - this.message = message; - } - - Cancel$3.prototype.toString = function toString() { - return 'Cancel' + (this.message ? ': ' + this.message : ''); - }; - - Cancel$3.prototype.__CANCEL__ = true; - var Cancel_1 = Cancel$3; - - var utils$6 = utils$d; - var settle = settle$1; - var cookies = cookies$1; - var buildURL$1 = buildURL$2; - var buildFullPath = buildFullPath$1; - var parseHeaders = parseHeaders$1; - var isURLSameOrigin = isURLSameOrigin$1; - var createError = createError$2; - var defaults$5 = defaults_1; - var Cancel$2 = Cancel_1; - - var xhr = function xhrAdapter(config) { - return new Promise(function dispatchXhrRequest(resolve, reject) { - var requestData = config.data; - var requestHeaders = config.headers; - var responseType = config.responseType; - var onCanceled; - - function done() { - if (config.cancelToken) { - config.cancelToken.unsubscribe(onCanceled); - } - - if (config.signal) { - config.signal.removeEventListener('abort', onCanceled); - } - } - - if (utils$6.isFormData(requestData)) { - delete requestHeaders['Content-Type']; // Let the browser set it - } - - var request = new XMLHttpRequest(); // HTTP basic authentication - - if (config.auth) { - var username = config.auth.username || ''; - var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; - requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); - } - - var fullPath = buildFullPath(config.baseURL, config.url); - request.open(config.method.toUpperCase(), buildURL$1(fullPath, config.params, config.paramsSerializer), true); // Set the request timeout in MS - - request.timeout = config.timeout; - - function onloadend() { - if (!request) { - return; - } // Prepare the response - - - var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; - var responseData = !responseType || responseType === 'text' || responseType === 'json' ? request.responseText : request.response; - var response = { - data: responseData, - status: request.status, - statusText: request.statusText, - headers: responseHeaders, - config: config, - request: request - }; - settle(function _resolve(value) { - resolve(value); - done(); - }, function _reject(err) { - reject(err); - done(); - }, response); // Clean up request - - request = null; - } - - if ('onloadend' in request) { - // Use onloadend if available - request.onloadend = onloadend; - } else { - // Listen for ready state to emulate onloadend - request.onreadystatechange = function handleLoad() { - if (!request || request.readyState !== 4) { - return; - } // The request errored out and we didn't get a response, this will be - // handled by onerror instead - // With one exception: request that using file: protocol, most browsers - // will return status as 0 even though it's a successful request - - - if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { - return; - } // readystate handler is calling before onerror or ontimeout handlers, - // so we should call onloadend on the next 'tick' - - - setTimeout(onloadend); - }; - } // Handle browser request cancellation (as opposed to a manual cancellation) - - - request.onabort = function handleAbort() { - if (!request) { - return; - } - - reject(createError('Request aborted', config, 'ECONNABORTED', request)); // Clean up request - - request = null; - }; // Handle low level network errors - - - request.onerror = function handleError() { - // Real errors are hidden from us by the browser - // onerror should only fire if it's a network error - reject(createError('Network Error', config, null, request)); // Clean up request - - request = null; - }; // Handle timeout - - - request.ontimeout = function handleTimeout() { - var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded'; - var transitional = config.transitional || defaults$5.transitional; - - if (config.timeoutErrorMessage) { - timeoutErrorMessage = config.timeoutErrorMessage; - } - - reject(createError(timeoutErrorMessage, config, transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED', request)); // Clean up request - - request = null; - }; // Add xsrf header - // This is only done if running in a standard browser environment. - // Specifically not if we're in a web worker, or react-native. - - - if (utils$6.isStandardBrowserEnv()) { - // Add xsrf header - var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? cookies.read(config.xsrfCookieName) : undefined; - - if (xsrfValue) { - requestHeaders[config.xsrfHeaderName] = xsrfValue; - } - } // Add headers to the request - - - if ('setRequestHeader' in request) { - utils$6.forEach(requestHeaders, function setRequestHeader(val, key) { - if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { - // Remove Content-Type if data is undefined - delete requestHeaders[key]; - } else { - // Otherwise add header to the request - request.setRequestHeader(key, val); - } - }); - } // Add withCredentials to request if needed - - - if (!utils$6.isUndefined(config.withCredentials)) { - request.withCredentials = !!config.withCredentials; - } // Add responseType to request if needed - - - if (responseType && responseType !== 'json') { - request.responseType = config.responseType; - } // Handle progress if needed - - - if (typeof config.onDownloadProgress === 'function') { - request.addEventListener('progress', config.onDownloadProgress); - } // Not all browsers support upload events - - - if (typeof config.onUploadProgress === 'function' && request.upload) { - request.upload.addEventListener('progress', config.onUploadProgress); - } - - if (config.cancelToken || config.signal) { - // Handle cancellation - // eslint-disable-next-line func-names - onCanceled = function onCanceled(cancel) { - if (!request) { - return; - } - - reject(!cancel || cancel && cancel.type ? new Cancel$2('canceled') : cancel); - request.abort(); - request = null; - }; - - config.cancelToken && config.cancelToken.subscribe(onCanceled); - - if (config.signal) { - config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled); - } - } - - if (!requestData) { - requestData = null; - } // Send the request - - - request.send(requestData); - }); - }; - - var utils$5 = utils$d; - var normalizeHeaderName = normalizeHeaderName$1; - var enhanceError = enhanceError$2; - var DEFAULT_CONTENT_TYPE = { - 'Content-Type': 'application/x-www-form-urlencoded' - }; - - function setContentTypeIfUnset(headers, value) { - if (!utils$5.isUndefined(headers) && utils$5.isUndefined(headers['Content-Type'])) { - headers['Content-Type'] = value; - } - } - - function getDefaultAdapter() { - var adapter; - - if (typeof XMLHttpRequest !== 'undefined') { - // For browsers use XHR adapter - adapter = xhr; - } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { - // For node use HTTP adapter - adapter = xhr; - } - - return adapter; - } - - function stringifySafely(rawValue, parser, encoder) { - if (utils$5.isString(rawValue)) { - try { - (parser || JSON.parse)(rawValue); - return utils$5.trim(rawValue); - } catch (e) { - if (e.name !== 'SyntaxError') { - throw e; - } - } - } - - return (encoder || JSON.stringify)(rawValue); - } - - var defaults$4 = { - transitional: { - silentJSONParsing: true, - forcedJSONParsing: true, - clarifyTimeoutError: false - }, - adapter: getDefaultAdapter(), - transformRequest: [function transformRequest(data, headers) { - normalizeHeaderName(headers, 'Accept'); - normalizeHeaderName(headers, 'Content-Type'); - - if (utils$5.isFormData(data) || utils$5.isArrayBuffer(data) || utils$5.isBuffer(data) || utils$5.isStream(data) || utils$5.isFile(data) || utils$5.isBlob(data)) { - return data; - } - - if (utils$5.isArrayBufferView(data)) { - return data.buffer; - } - - if (utils$5.isURLSearchParams(data)) { - setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); - return data.toString(); - } - - if (utils$5.isObject(data) || headers && headers['Content-Type'] === 'application/json') { - setContentTypeIfUnset(headers, 'application/json'); - return stringifySafely(data); - } - - return data; - }], - transformResponse: [function transformResponse(data) { - var transitional = this.transitional || defaults$4.transitional; - var silentJSONParsing = transitional && transitional.silentJSONParsing; - var forcedJSONParsing = transitional && transitional.forcedJSONParsing; - var strictJSONParsing = !silentJSONParsing && this.responseType === 'json'; - - if (strictJSONParsing || forcedJSONParsing && utils$5.isString(data) && data.length) { - try { - return JSON.parse(data); - } catch (e) { - if (strictJSONParsing) { - if (e.name === 'SyntaxError') { - throw enhanceError(e, this, 'E_JSON_PARSE'); - } - - throw e; - } - } - } - - return data; - }], - - /** - * A timeout in milliseconds to abort a request. If set to 0 (default) a - * timeout is not created. - */ - timeout: 0, - xsrfCookieName: 'XSRF-TOKEN', - xsrfHeaderName: 'X-XSRF-TOKEN', - maxContentLength: -1, - maxBodyLength: -1, - validateStatus: function validateStatus(status) { - return status >= 200 && status < 300; - }, - headers: { - common: { - 'Accept': 'application/json, text/plain, */*' - } - } - }; - utils$5.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { - defaults$4.headers[method] = {}; - }); - utils$5.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { - defaults$4.headers[method] = utils$5.merge(DEFAULT_CONTENT_TYPE); - }); - var defaults_1 = defaults$4; - - var utils$4 = utils$d; - var defaults$3 = defaults_1; - /** - * Transform the data for a request or a response - * - * @param {Object|String} data The data to be transformed - * @param {Array} headers The headers for the request or response - * @param {Array|Function} fns A single function or Array of functions - * @returns {*} The resulting transformed data - */ - - var transformData$1 = function transformData(data, headers, fns) { - var context = this || defaults$3; - /*eslint no-param-reassign:0*/ - - utils$4.forEach(fns, function transform(fn) { - data = fn.call(context, data, headers); - }); - return data; - }; - - var isCancel$1 = function isCancel(value) { - return !!(value && value.__CANCEL__); - }; - - var utils$3 = utils$d; - var transformData = transformData$1; - var isCancel = isCancel$1; - var defaults$2 = defaults_1; - var Cancel$1 = Cancel_1; - /** - * Throws a `Cancel` if cancellation has been requested. - */ - - function throwIfCancellationRequested(config) { - if (config.cancelToken) { - config.cancelToken.throwIfRequested(); - } - - if (config.signal && config.signal.aborted) { - throw new Cancel$1('canceled'); - } - } - /** - * Dispatch a request to the server using the configured adapter. - * - * @param {object} config The config that is to be used for the request - * @returns {Promise} The Promise to be fulfilled - */ - - - var dispatchRequest$1 = function dispatchRequest(config) { - throwIfCancellationRequested(config); // Ensure headers exist - - config.headers = config.headers || {}; // Transform request data - - config.data = transformData.call(config, config.data, config.headers, config.transformRequest); // Flatten headers - - config.headers = utils$3.merge(config.headers.common || {}, config.headers[config.method] || {}, config.headers); - utils$3.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], function cleanHeaderConfig(method) { - delete config.headers[method]; - }); - var adapter = config.adapter || defaults$2.adapter; - return adapter(config).then(function onAdapterResolution(response) { - throwIfCancellationRequested(config); // Transform response data - - response.data = transformData.call(config, response.data, response.headers, config.transformResponse); - return response; - }, function onAdapterRejection(reason) { - if (!isCancel(reason)) { - throwIfCancellationRequested(config); // Transform response data - - if (reason && reason.response) { - reason.response.data = transformData.call(config, reason.response.data, reason.response.headers, config.transformResponse); - } - } - - return Promise.reject(reason); - }); - }; - - var utils$2 = utils$d; - /** - * Config-specific merge-function which creates a new config-object - * by merging two configuration objects together. - * - * @param {Object} config1 - * @param {Object} config2 - * @returns {Object} New object resulting from merging config2 to config1 - */ - - var mergeConfig$2 = function mergeConfig(config1, config2) { - // eslint-disable-next-line no-param-reassign - config2 = config2 || {}; - var config = {}; - - function getMergedValue(target, source) { - if (utils$2.isPlainObject(target) && utils$2.isPlainObject(source)) { - return utils$2.merge(target, source); - } else if (utils$2.isPlainObject(source)) { - return utils$2.merge({}, source); - } else if (utils$2.isArray(source)) { - return source.slice(); - } - - return source; - } // eslint-disable-next-line consistent-return - - - function mergeDeepProperties(prop) { - if (!utils$2.isUndefined(config2[prop])) { - return getMergedValue(config1[prop], config2[prop]); - } else if (!utils$2.isUndefined(config1[prop])) { - return getMergedValue(undefined, config1[prop]); - } - } // eslint-disable-next-line consistent-return - - - function valueFromConfig2(prop) { - if (!utils$2.isUndefined(config2[prop])) { - return getMergedValue(undefined, config2[prop]); - } - } // eslint-disable-next-line consistent-return - - - function defaultToConfig2(prop) { - if (!utils$2.isUndefined(config2[prop])) { - return getMergedValue(undefined, config2[prop]); - } else if (!utils$2.isUndefined(config1[prop])) { - return getMergedValue(undefined, config1[prop]); - } - } // eslint-disable-next-line consistent-return - - - function mergeDirectKeys(prop) { - if (prop in config2) { - return getMergedValue(config1[prop], config2[prop]); - } else if (prop in config1) { - return getMergedValue(undefined, config1[prop]); - } - } - - var mergeMap = { - 'url': valueFromConfig2, - 'method': valueFromConfig2, - 'data': valueFromConfig2, - 'baseURL': defaultToConfig2, - 'transformRequest': defaultToConfig2, - 'transformResponse': defaultToConfig2, - 'paramsSerializer': defaultToConfig2, - 'timeout': defaultToConfig2, - 'timeoutMessage': defaultToConfig2, - 'withCredentials': defaultToConfig2, - 'adapter': defaultToConfig2, - 'responseType': defaultToConfig2, - 'xsrfCookieName': defaultToConfig2, - 'xsrfHeaderName': defaultToConfig2, - 'onUploadProgress': defaultToConfig2, - 'onDownloadProgress': defaultToConfig2, - 'decompress': defaultToConfig2, - 'maxContentLength': defaultToConfig2, - 'maxBodyLength': defaultToConfig2, - 'transport': defaultToConfig2, - 'httpAgent': defaultToConfig2, - 'httpsAgent': defaultToConfig2, - 'cancelToken': defaultToConfig2, - 'socketPath': defaultToConfig2, - 'responseEncoding': defaultToConfig2, - 'validateStatus': mergeDirectKeys - }; - utils$2.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) { - var merge = mergeMap[prop] || mergeDeepProperties; - var configValue = merge(prop); - utils$2.isUndefined(configValue) && merge !== mergeDirectKeys || (config[prop] = configValue); - }); - return config; - }; - - var data = { - "version": "0.24.0" - }; - - var VERSION = data.version; - var validators$1 = {}; // eslint-disable-next-line func-names - - ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function (type, i) { - validators$1[type] = function validator(thing) { - return _typeof(thing) === type || 'a' + (i < 1 ? 'n ' : ' ') + type; - }; - }); - var deprecatedWarnings = {}; - /** - * Transitional option validator - * @param {function|boolean?} validator - set to false if the transitional option has been removed - * @param {string?} version - deprecated version / removed since version - * @param {string?} message - some message with additional info - * @returns {function} - */ - - validators$1.transitional = function transitional(validator, version, message) { - function formatMessage(opt, desc) { - return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); - } // eslint-disable-next-line func-names - - - return function (value, opt, opts) { - if (validator === false) { - throw new Error(formatMessage(opt, ' has been removed' + (version ? ' in ' + version : ''))); - } - - if (version && !deprecatedWarnings[opt]) { - deprecatedWarnings[opt] = true; // eslint-disable-next-line no-console - - console.warn(formatMessage(opt, ' has been deprecated since v' + version + ' and will be removed in the near future')); - } - - return validator ? validator(value, opt, opts) : true; - }; - }; - /** - * Assert object's properties type - * @param {object} options - * @param {object} schema - * @param {boolean?} allowUnknown - */ - - - function assertOptions(options, schema, allowUnknown) { - if (_typeof(options) !== 'object') { - throw new TypeError('options must be an object'); - } - - var keys = Object.keys(options); - var i = keys.length; - - while (i-- > 0) { - var opt = keys[i]; - var validator = schema[opt]; - - if (validator) { - var value = options[opt]; - var result = value === undefined || validator(value, opt, options); - - if (result !== true) { - throw new TypeError('option ' + opt + ' must be ' + result); - } - - continue; - } - - if (allowUnknown !== true) { - throw Error('Unknown option ' + opt); - } - } - } - - var validator$1 = { - assertOptions: assertOptions, - validators: validators$1 - }; - - var utils$1 = utils$d; - var buildURL = buildURL$2; - var InterceptorManager = InterceptorManager_1; - var dispatchRequest = dispatchRequest$1; - var mergeConfig$1 = mergeConfig$2; - var validator = validator$1; - var validators = validator.validators; - /** - * Create a new instance of Axios - * - * @param {Object} instanceConfig The default config for the instance - */ - - function Axios$1(instanceConfig) { - this.defaults = instanceConfig; - this.interceptors = { - request: new InterceptorManager(), - response: new InterceptorManager() - }; - } - /** - * Dispatch a request - * - * @param {Object} config The config specific for this request (merged with this.defaults) - */ - - - Axios$1.prototype.request = function request(config) { - /*eslint no-param-reassign:0*/ - // Allow for axios('example/url'[, config]) a la fetch API - if (typeof config === 'string') { - config = arguments[1] || {}; - config.url = arguments[0]; - } else { - config = config || {}; - } - - config = mergeConfig$1(this.defaults, config); // Set config.method - - if (config.method) { - config.method = config.method.toLowerCase(); - } else if (this.defaults.method) { - config.method = this.defaults.method.toLowerCase(); - } else { - config.method = 'get'; - } - - var transitional = config.transitional; - - if (transitional !== undefined) { - validator.assertOptions(transitional, { - silentJSONParsing: validators.transitional(validators.boolean), - forcedJSONParsing: validators.transitional(validators.boolean), - clarifyTimeoutError: validators.transitional(validators.boolean) - }, false); - } // filter out skipped interceptors - - - var requestInterceptorChain = []; - var synchronousRequestInterceptors = true; - this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { - if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { - return; - } - - synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; - requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); - }); - var responseInterceptorChain = []; - this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { - responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); - }); - var promise; - - if (!synchronousRequestInterceptors) { - var chain = [dispatchRequest, undefined]; - Array.prototype.unshift.apply(chain, requestInterceptorChain); - chain = chain.concat(responseInterceptorChain); - promise = Promise.resolve(config); - - while (chain.length) { - promise = promise.then(chain.shift(), chain.shift()); - } - - return promise; - } - - var newConfig = config; - - while (requestInterceptorChain.length) { - var onFulfilled = requestInterceptorChain.shift(); - var onRejected = requestInterceptorChain.shift(); - - try { - newConfig = onFulfilled(newConfig); - } catch (error) { - onRejected(error); - break; - } - } - - try { - promise = dispatchRequest(newConfig); - } catch (error) { - return Promise.reject(error); - } - - while (responseInterceptorChain.length) { - promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift()); - } - - return promise; - }; - - Axios$1.prototype.getUri = function getUri(config) { - config = mergeConfig$1(this.defaults, config); - return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, ''); - }; // Provide aliases for supported request methods - - - utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { - /*eslint func-names:0*/ - Axios$1.prototype[method] = function (url, config) { - return this.request(mergeConfig$1(config || {}, { - method: method, - url: url, - data: (config || {}).data - })); - }; - }); - utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { - /*eslint func-names:0*/ - Axios$1.prototype[method] = function (url, data, config) { - return this.request(mergeConfig$1(config || {}, { - method: method, - url: url, - data: data - })); - }; - }); - var Axios_1 = Axios$1; - - var Cancel = Cancel_1; - /** - * A `CancelToken` is an object that can be used to request cancellation of an operation. - * - * @class - * @param {Function} executor The executor function. - */ - - function CancelToken(executor) { - if (typeof executor !== 'function') { - throw new TypeError('executor must be a function.'); - } - - var resolvePromise; - this.promise = new Promise(function promiseExecutor(resolve) { - resolvePromise = resolve; - }); - var token = this; // eslint-disable-next-line func-names - - this.promise.then(function (cancel) { - if (!token._listeners) return; - var i; - var l = token._listeners.length; - - for (i = 0; i < l; i++) { - token._listeners[i](cancel); - } - - token._listeners = null; - }); // eslint-disable-next-line func-names - - this.promise.then = function (onfulfilled) { - var _resolve; // eslint-disable-next-line func-names - - - var promise = new Promise(function (resolve) { - token.subscribe(resolve); - _resolve = resolve; - }).then(onfulfilled); - - promise.cancel = function reject() { - token.unsubscribe(_resolve); - }; - - return promise; - }; - - executor(function cancel(message) { - if (token.reason) { - // Cancellation has already been requested - return; - } - - token.reason = new Cancel(message); - resolvePromise(token.reason); - }); - } - /** - * Throws a `Cancel` if cancellation has been requested. - */ - - - CancelToken.prototype.throwIfRequested = function throwIfRequested() { - if (this.reason) { - throw this.reason; - } - }; - /** - * Subscribe to the cancel signal - */ - - - CancelToken.prototype.subscribe = function subscribe(listener) { - if (this.reason) { - listener(this.reason); - return; - } - - if (this._listeners) { - this._listeners.push(listener); - } else { - this._listeners = [listener]; - } - }; - /** - * Unsubscribe from the cancel signal - */ - - - CancelToken.prototype.unsubscribe = function unsubscribe(listener) { - if (!this._listeners) { - return; - } - - var index = this._listeners.indexOf(listener); - - if (index !== -1) { - this._listeners.splice(index, 1); - } - }; - /** - * Returns an object that contains a new `CancelToken` and a function that, when called, - * cancels the `CancelToken`. - */ - - - CancelToken.source = function source() { - var cancel; - var token = new CancelToken(function executor(c) { - cancel = c; - }); - return { - token: token, - cancel: cancel - }; - }; - - var CancelToken_1 = CancelToken; - - /** - * Syntactic sugar for invoking a function and expanding an array for arguments. - * - * Common use case would be to use `Function.prototype.apply`. - * - * ```js - * function f(x, y, z) {} - * var args = [1, 2, 3]; - * f.apply(null, args); - * ``` - * - * With `spread` this example can be re-written. - * - * ```js - * spread(function(x, y, z) {})([1, 2, 3]); - * ``` - * - * @param {Function} callback - * @returns {Function} - */ - - - var spread = function spread(callback) { - return function wrap(arr) { - return callback.apply(null, arr); - }; - }; - - /** - * Determines whether the payload is an error thrown by Axios - * - * @param {*} payload The value to test - * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false - */ - - - var isAxiosError = function isAxiosError(payload) { - return _typeof(payload) === 'object' && payload.isAxiosError === true; - }; - - var utils = utils$d; - var bind$4 = bind$6; - var Axios = Axios_1; - var mergeConfig = mergeConfig$2; - var defaults$1 = defaults_1; - /** - * Create an instance of Axios - * - * @param {Object} defaultConfig The default config for the instance - * @return {Axios} A new instance of Axios - */ - - function createInstance(defaultConfig) { - var context = new Axios(defaultConfig); - var instance = bind$4(Axios.prototype.request, context); // Copy axios.prototype to instance - - utils.extend(instance, Axios.prototype, context); // Copy context to instance - - utils.extend(instance, context); // Factory for creating new instances - - instance.create = function create(instanceConfig) { - return createInstance(mergeConfig(defaultConfig, instanceConfig)); - }; - - return instance; - } // Create the default instance to be exported - - - var axios$1 = createInstance(defaults$1); // Expose Axios class to allow class inheritance - - axios$1.Axios = Axios; // Expose Cancel & CancelToken - - axios$1.Cancel = Cancel_1; - axios$1.CancelToken = CancelToken_1; - axios$1.isCancel = isCancel$1; - axios$1.VERSION = data.version; // Expose all/spread - - axios$1.all = function all(promises) { - return Promise.all(promises); - }; - - axios$1.spread = spread; // Expose isAxiosError - - axios$1.isAxiosError = isAxiosError; - axios$2.exports = axios$1; // Allow use of default import syntax in TypeScript - - axios$2.exports.default = axios$1; - - var axios = axios$2.exports; - - var IdealPostcodesError = IdealPostcodesError$1; - /** - * Converts a Got header object to one that can be used by the client - * - * @hidden - */ - - var toHeader = function toHeader(gotHeaders) { - return Object.keys(gotHeaders).reduce(function (headers, key) { - var val = gotHeaders[key]; - - if (typeof val === "string") { - headers[key] = val; - } else if (Array.isArray(val)) { - headers[key] = val.join(","); - } - - return headers; - }, {}); - }; - /** - * Adapts got responses to a format consumable by core-interface - * - * @hidden - */ - - var toHttpResponse = function toHttpResponse(httpRequest, response) { - return { - httpRequest: httpRequest, - body: response.data, - httpStatus: response.status || 0, - header: toHeader(response.headers), - metadata: { - response: response - } - }; - }; - /** - * Catch non-response errors (e.g. network failure, DNS failure, timeout) - * wrap in our Error class and return - * - * @hidden - */ - - - var handleError = function handleError(error) { - var idpcError = new IdealPostcodesError({ - message: "[".concat(error.name, "] ").concat(error.message), - httpStatus: 0, - metadata: { - axios: error - } - }); - return Promise.reject(idpcError); - }; // Don't throw errors for any HTTP status code - // Allow core-interface to absorb these and emit own errors - - - var validateStatus = function validateStatus() { - return true; - }; - /** - * Agent - * - * @hidden - */ - - - var Agent = /*#__PURE__*/function () { - function Agent() { - _classCallCheck(this, Agent); - - this.Axios = axios.create({ - validateStatus: validateStatus - }); - } - - _createClass(Agent, [{ - key: "requestWithBody", - value: function requestWithBody(httpRequest) { - var body = httpRequest.body, - method = httpRequest.method, - timeout = httpRequest.timeout, - url = httpRequest.url, - header = httpRequest.header, - query = httpRequest.query; - return this.Axios.request({ - url: url, - method: method, - headers: header, - params: query, - data: body, - timeout: timeout - }).then(function (response) { - return toHttpResponse(httpRequest, response); - }).catch(handleError); - } - }, { - key: "request", - value: function request(httpRequest) { - var method = httpRequest.method, - timeout = httpRequest.timeout, - url = httpRequest.url, - header = httpRequest.header, - query = httpRequest.query; - return this.Axios.request({ - url: url, - method: method, - headers: header, - params: query, - timeout: timeout - }).then(function (response) { - return toHttpResponse(httpRequest, response); - }).catch(handleError); - } - }, { - key: "http", - value: function http(httpRequest) { - if (httpRequest.body !== undefined) return this.requestWithBody(httpRequest); - return this.request(httpRequest); - } - }]); - - return Agent; - }(); - - function ownKeys$3(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - - function _objectSpread$3(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$3(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$3(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - - function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } - - function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } - var Client = /*#__PURE__*/function (_CoreInterface) { - _inherits(Client, _CoreInterface); - - var _super = _createSuper(Client); - - /** - * Client constructor extends CoreInterface - */ - function Client(config) { - _classCallCheck(this, Client); - - var agent = new Agent(); - return _super.call(this, _objectSpread$3({ - agent: agent - }, config)); - } - - return Client; - }(Client$1); - - /** - * @module Utility - */ - /** - * Formats an address as a suggestion to be displayed in postcode lookup select - * menu - */ - - var postcodeSearchFormatter = function postcodeSearchFormatter(address) { - var result = [address.line_1]; - if (address.line_2 !== "") result.push(address.line_2); - return result.join(" "); - }; - /** - * Formats an address as a suggestion to be displayed in address search select - * menu - */ - - var addressSearchFormatter = function addressSearchFormatter(address) { - var result = [address.line_1]; - if (address.line_2 !== "") result.push(address.line_2); - result.push(address.post_town); - result.push(address.postcode_outward); - return result.join(", "); - }; - /** - * @hidden - */ - - var preventDefault = function preventDefault(e) { - if (e.preventDefault) e.preventDefault(); - return false; - }; - /** - * Drains select elment of options - * - * @hidden - */ - - var removeOptions = function removeOptions(e) { - var i; - var L = e.options.length - 1; - - for (i = L; i >= 0; i--) { - e.remove(i); - } - }; - - function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - - function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - /** - * @hidden - */ - - var NOOP$2 = function NOOP() {}; - /** - * @hidden - */ - - - var returnFalse = function returnFalse() { - return false; - }; - /** - * Keypress listener on input field - * - * @hidden - */ - - - var keypress = function keypress(event) { - if (toKey$1(event) === "Enter") { - event.preventDefault(); - this.handleClick(); - return false; - } - - return; - }; - /** - * Button Click handler - * - * @hidden - */ - - var click = function click(event) { - event.preventDefault(); - this.options.onButtonTrigger.call(this); - this.handleClick(); - return false; - }; - /** - * Select change handler - * - * @hidden - */ - - var selectEvent = function selectEvent() { - var value = parseInt(this.select.value, 10); - if (isNaN(value)) return; - this.selectAddress(value); - }; - /** - * Default Controller configuration - */ - - var defaults = { - // Client - apiKey: "", - checkKey: true, - context: "", - // DOM - outputScope: null, - // Callbacks - onButtonTrigger: NOOP$2, - onSearchCompleted: NOOP$2, - onAddressesRetrieved: NOOP$2, - onAddressSelected: NOOP$2, - onSelectCreated: NOOP$2, - onSelectRemoved: NOOP$2, - onLookupTriggered: NOOP$2, - shouldLookupTrigger: function shouldLookupTrigger() { - return true; - }, - onSearchError: NOOP$2, - onLoaded: NOOP$2, - onFailedCheck: NOOP$2, - onRemove: NOOP$2, - onAddressPopulated: NOOP$2, - onUnhide: NOOP$2, - // Input - input: null, - inputId: null, - inputClass: "idpc-input", - inputAriaLabel: "Search a postcode to retrieve your address", - placeholder: "Search your postcode", - // Button - button: null, - buttonId: null, - buttonLabel: "Find my Address", - buttonClass: "idpc-button", - // Select - selectContainer: null, - selectId: null, - selectClass: "idpc-select", - selectContainerId: null, - selectContainerClass: "idpc-select-container", - selectAriaLabel: "Select your address", - // Hide / unhide - unhide: null, - unhideClass: "idpc-unhide", - // Message - message: null, - messageId: null, - messageClass: "idpc-error", - msgSelect: "Please select your address", - msgDisabled: "Finding addresses...", - msgNotFound: "Your postcode could not be found. Please type in your address", - msgAddressNotFound: "We could not find a match for your address. Please type in your address", - msgError: "Sorry, we weren't able to get the address you were looking for. Please type in your address", - msgUnhide: "Enter address manually", - // Plugin behaviour - cooloff: 500, - removeOrganisation: false, - selectSinglePremise: false, - titleizePostTown: true, - postcodeSearchFormatter: postcodeSearchFormatter, - addressSearchFormatter: addressSearchFormatter, - outputFields: {}, - strictlyPostcodes: true, - limit: 10, - inputStyle: {}, - buttonStyle: {}, - messageStyle: {}, - selectStyle: {}, - contextStyle: {}, - hide: [], - autocomplete: "none", - populateCounty: true, - populateOrganisation: true - }; - /** - * A Postcode Lookup Controller instances manages the state of a postcode or address search widget and updates the DOM accordingly - * - * To detach from the DOM call use the `#removeAll()` method - */ - - var Controller = /*#__PURE__*/function () { - function Controller(options) { - var _this = this; - - _classCallCheck(this, Controller); - - this.prevContext = null; // Merge user config with any defaults - - this.options = _objectSpread$2(_objectSpread$2(_objectSpread$2({}, { - scope: window.document, - document: window.document - }), defaults), options); - this.client = new Client(_objectSpread$2(_objectSpread$2({}, this.options), {}, { - api_key: this.options.apiKey - })); // Scope the operations of this controller to a document or DOM subtree - - this.scope = getScope$2(this.options.scope); // Assign a parent Document for elem creation - - this.document = getDocument$1(this.scope); // Assign a document or DOM subtree to scope outputs. Defaults to controller scope - - this.outputScope = this.findOrCreate(this.options.outputScope, function () { - return _this.scope; - }); - this.data = []; - this.lastLookup = ""; // Cache container element for Postcode Lookup controller instance - - this.context = this.findOrCreate(this.options.context); // Set context styles if configured - - this.prevContext = setStyle$1(this.context, this.options.contextStyle); - this.keypress = keypress.bind(this); - this.click = click.bind(this); - this.selectEvent = selectEvent.bind(this); - this.unhideEvent = this.unhideFields.bind(this); // Create DOM elements - - this.input = this.createInput(); - this.button = this.createButton(); - this.message = this.createMessage(); - this.select = this.createSelect(); - this.selectContainer = this.createContainer(); - this.unhide = this.createUnhide(); - this.init(); - } - /** - * Retrieve Element - * - If string, assumes is valid and returns first match within scope - * - If null, invokes the create method to return a default - * - If HTMLElement returns instance - * - * @hidden - */ - - - _createClass(Controller, [{ - key: "findOrCreate", - value: function findOrCreate(q, create) { - if (isString$5(q)) return this.scope.querySelector(q); - if (create && q === null) return create(); - return q; - } - /** - * Creates a clickable element that can trigger unhiding of fields - */ - - }, { - key: "createUnhide", - value: function createUnhide() { - var _this2 = this; - - var e = this.findOrCreate(this.options.unhide, function () { - var e = _this2.document.createElement("p"); - - e.innerText = _this2.options.msgUnhide; - e.setAttribute("role", "button"); - e.setAttribute("tabindex", "0"); - if (_this2.options.unhideClass) e.className = _this2.options.unhideClass; - return e; - }); - e.addEventListener("click", this.unhideEvent); - return e; - } - /** - * Removes unhide elem from DOM - */ - - }, { - key: "unmountUnhide", - value: function unmountUnhide() { - this.unhide.removeEventListener("click", this.unhideEvent); - if (!this.options.unhide && this.options.hide.length) remove$1(this.unhide); - } - /** - * Creates select container instance - * - * @hidden - */ - - }, { - key: "createContainer", - value: function createContainer() { - var _this3 = this; - - return this.findOrCreate(this.options.selectContainer, function () { - var c = _this3.options; - - var div = _this3.document.createElement("div"); - - if (c.selectContainerId) div.id = c.selectContainerId; - if (c.selectContainerClass) div.className = c.selectContainerClass; - div.setAttribute("aria-live", "polite"); - hide$1(div); - return div; - }); - } - /** - * Removes select container from DOM - */ - - }, { - key: "unmountContainer", - value: function unmountContainer() { - remove$1(this.selectContainer); - } - /** - * Create input field and binds event listeners - * - * - If a selector (this.input) is specified, that input is used - * - If no selector specified, a new input field is generated and added to context - * - * @hidden - */ - - }, { - key: "createInput", - value: function createInput() { - var _this4 = this; - - var input = this.findOrCreate(this.options.input, function () { - var i = _this4.document.createElement("input"); - - var c = _this4.options; - i.type = "text"; - if (c.inputId) i.id = c.inputId; - if (c.inputClass) i.className = c.inputClass; - if (c.placeholder) i.placeholder = c.placeholder; - if (c.inputAriaLabel) i.setAttribute("aria-label", c.inputAriaLabel); - if (c.autocomplete) i.setAttribute("autocomplete", c.autocomplete); - setStyle$1(i, _this4.options.inputStyle); - return i; - }); - input.addEventListener("keypress", this.keypress); - input.addEventListener("submit", returnFalse); - return input; - } - /** - * Removes address input artefacts from DOM - * - Removes event listeners from input field - * - Removes input field, unless input field is provided by the user - */ - - }, { - key: "unmountInput", - value: function unmountInput() { - this.input.removeEventListener("keypress", this.keypress); - this.input.removeEventListener("submit", returnFalse); - if (this.options.input === null) remove$1(this.input); - } - /** - * Creates button and binds event listeners - * - * @hidden - */ - - }, { - key: "createButton", - value: function createButton() { - var _this5 = this; - - var button = this.findOrCreate(this.options.button, function () { - var b = _this5.document.createElement("button"); - - var c = _this5.options; - b.type = "button"; - if (c.buttonLabel) b.innerText = c.buttonLabel; - if (c.buttonId) b.id = c.buttonId; - if (c.buttonClass) b.className = c.buttonClass; - setStyle$1(b, _this5.options.buttonStyle); - b.onclick = preventDefault; - return b; - }); - button.addEventListener("submit", returnFalse); - button.addEventListener("click", this.click); - return button; - } - /** - * unmountButton - * - Remove listener events - * - Remove button from DOM if generated by this controller - */ - - }, { - key: "unmountButton", - value: function unmountButton() { - this.button.removeEventListener("submit", returnFalse); - this.button.removeEventListener("click", this.click); - if (this.options.button === null) remove$1(this.button); - } - /** - * Mounts message container - * - * @hidden - */ - - }, { - key: "createMessage", - value: function createMessage() { - var _this6 = this; - - return this.findOrCreate(this.options.message, function () { - var p = _this6.document.createElement("p"); - - var c = _this6.options; - if (c.messageClass) p.className = c.messageClass; - if (c.messageId) p.id = c.messageId; - p.setAttribute("role", "alert"); - setStyle$1(p, _this6.options.messageStyle); - hide$1(p); - return p; - }); - } - /** - * Removes message container from DOM - */ - - }, { - key: "unmountMessage", - value: function unmountMessage() { - if (this.options.message === null) remove$1(this.message); - } - /** - * Creates Select HTML Element - */ - - }, { - key: "createSelect", - value: function createSelect() { - var select = this.document.createElement("select"); - var c = this.options; - if (c.selectId) select.id = c.selectId; - if (c.selectClass) select.className = c.selectClass; - setStyle$1(select, this.options.selectStyle); - if (c.selectAriaLabel) select.setAttribute("aria-label", c.selectAriaLabel); - select.addEventListener("change", this.selectEvent); - return select; - } - /** - * Mounts dropdown menu to DOM and attach event listeners - * - * Removes dropdown from DOM if data is undefined - */ - - }, { - key: "mountSelect", - value: function mountSelect(data) { - if (data) this.data = data; - removeOptions(this.select); // Add initial select message - - this.select.appendChild(this.createOption("ideal", this.options.msgSelect)); // Add address options - - for (var i = 0; i < this.data.length; i += 1) { - this.select.appendChild(this.createOption(i.toString(), this.formatAddress(this.data[i]))); - } - - this.selectContainer.appendChild(this.select); - show$1(this.selectContainer); - this.options.onSelectCreated.call(this, this.select); - } - /** - * Remove dropdown from DOM - */ - - }, { - key: "unmountSelect", - value: function unmountSelect() { - remove$1(this.select); - hide$1(this.selectContainer); - this.options.onSelectRemoved.call(this); - } - /** - * Selects an address by its offset `i` in the list of address results - */ - - }, { - key: "selectAddress", - value: function selectAddress(i) { - var address = this.data[i]; - if (!address) return; - this.populateAddress(address); - this.options.onAddressSelected.call(this, address); - } - /** - * Callback for address search click event - * - * @hidden - */ - - }, { - key: "handleClick", - value: function handleClick() { - if (!this.options.shouldLookupTrigger.call(this)) return false; - this.options.onLookupTriggered.call(this); - var term = this.input.value; - if (this.lastLookup === term) return false; - this.lastLookup = term; - this.reset(); - this.disableButton(); - this.executeSearch(term); - return false; - } - /** - * Prevents lookup button from being triggered - */ - - }, { - key: "disableButton", - value: function disableButton(message) { - // Cancel if custom button - if (this.options.button) return; - this.button.setAttribute("disabled", "true"); - this.button.innerText = message || this.options.msgDisabled; - } - /** - * Enables lookup button to trigger searches - */ - - }, { - key: "enableButton", - value: function enableButton() { - // Cancel if custom button - if (this.options.button) return; - this.button.removeAttribute("disabled"); - this.button.innerText = this.options.buttonLabel; - } - /** - * Allows lookup button to be triggered and applies a cooloff timer if configured - */ - - }, { - key: "enableLookup", - value: function enableLookup() { - var _this7 = this; - - if (this.options.button) return; - var cooloff = this.options.cooloff; - if (cooloff === 0) return this.enableButton(); - setTimeout(function () { - return _this7.enableButton(); - }, cooloff); - } - /** - * Resets address search fields - * - Removes any existing address selection dropdown - * - Removes any visiable messages - */ - - }, { - key: "reset", - value: function reset() { - this.unmountSelect(); - this.hideMessage(); - } - /** - * Removes all elements from DOM including dropdown, input, button and any error message - * - Remove all event listeners - * - Remove non-custom elements DOM - */ - - }, { - key: "removeAll", - value: function removeAll() { - this.unmountInput(); - this.unmountButton(); - this.unmountContainer(); - this.unmountMessage(); - this.unmountUnhide(); - restoreStyle$1(this.context, this.prevContext); - this.options.onRemove.call(this); - } - /** - * Returns not found message - * - * @hidden - */ - - }, { - key: "notFoundMessage", - value: function notFoundMessage() { - return this.options.strictlyPostcodes ? this.options.msgNotFound : this.options.msgAddressNotFound; - } - /** - * Triggers a search based on term and mounts addresses to DOM in the address - * dropdown - * - * Validate search term and then trigger postcode lookup - * - On successful search, display results in a dropdown menu - * - On successful search but no addresses, show error message - * - On failed search, show error message - */ - - }, { - key: "executeSearch", - value: function executeSearch(term) { - var _this8 = this; - - this.enableLookup(); - var query = this.options.strictlyPostcodes ? this.searchPostcode(term) : this.searchAddress(term); - query.then(function (addresses) { - _this8.options.onSearchCompleted.call(_this8, null, addresses); - - if (addresses.length === 0) return _this8.setMessage(_this8.notFoundMessage()); // Cache last search term - - _this8.lastLookup = term; - _this8.data = addresses; // Invoke successful address search callback - - _this8.options.onAddressesRetrieved.call(_this8, addresses); - - if (_this8.options.selectSinglePremise && addresses.length === 1) return _this8.selectAddress(0); - - _this8.mountSelect(addresses); - }).catch(function (error) { - _this8.setMessage(_this8.options.msgError); - - _this8.options.onSearchCompleted.call(_this8, null, []); - - _this8.options.onSearchError.call(_this8, error); - }); - } - /** - * Invoke postcode lookup - * - * @hidden - */ - - }, { - key: "searchPostcode", - value: function searchPostcode(postcode) { - return lookupPostcode({ - client: this.client, - postcode: postcode - }); - } - /** - * Invoke an address search - * - * @hidden - */ - - }, { - key: "searchAddress", - value: function searchAddress(query) { - return lookupAddress({ - client: this.client, - query: query, - limit: this.options.limit - }); - } - /** - * Formats address according to whether text or postcode search is active - * - * @hidden - */ - - }, { - key: "formatAddress", - value: function formatAddress(address) { - var formatter = this.options.strictlyPostcodes ? this.options.postcodeSearchFormatter : this.options.addressSearchFormatter; - return formatter(address); - } - }, { - key: "createOption", - value: function createOption(value, text) { - var option = this.document.createElement("option"); - option.text = text; - option.value = value; - return option; - } - /** - * Sets the error message - * - * Removes error message from DOM if undefined - */ - - }, { - key: "setMessage", - value: function setMessage(message) { - if (!this.message) return; - if (message === undefined) return this.hideMessage(); - show$1(this.message); - this.message.innerText = message; - } - /** - * Hides any messages - */ - - }, { - key: "hideMessage", - value: function hideMessage() { - if (!this.message) return; - this.message.innerText = ""; - hide$1(this.message); - } - /** - * Call to initially render the DOM elements - * - * This will perform an optional keyCheck if required - */ - - }, { - key: "init", - value: function init() { - var _this9 = this; - - var initPlugin = function initPlugin() { - _this9.render(); - - _this9.hideFields(); - - _this9.options.onLoaded.call(_this9); - }; - - if (!this.options.checkKey) return initPlugin(); - checkKeyUsability({ - client: this.client - }).then(function (_ref) { - var available = _ref.available; - if (!available) return Promise.reject("Key not available"); - return initPlugin(); - }).catch(function (error) { - if (_this9.options.onFailedCheck) _this9.options.onFailedCheck(error); - }); - } - /** - * Writes a selected to the input fields specified in the controller config - */ - - }, { - key: "populateAddress", - value: function populateAddress(address) { - this.unhideFields(); - var outputFields = this.options.outputFields; - - var config = _objectSpread$2(_objectSpread$2({}, this.options), {}, { - scope: this.outputScope - }); - - populateAddress$1({ - outputFields: outputFields, - address: address, - config: config - }); - - this.options.onAddressPopulated.call(this, address); - } - }, { - key: "hiddenFields", - value: function hiddenFields() { - var _this10 = this; - - return this.options.hide.map(function (e) { - if (isString$5(e)) return toHtmlElem$1(_this10.scope, e); - return e; - }).filter(function (e) { - return e !== null; - }); - } - /** - * Hides fields marked for hiding - */ - - }, { - key: "hideFields", - value: function hideFields() { - this.hiddenFields().forEach(hide$1); - } - /** - * Unhides fields marked for hiding and triggers callback - */ - - }, { - key: "unhideFields", - value: function unhideFields() { - this.hiddenFields().forEach(show$1); - this.options.onUnhide.call(this); - } - /** - * Empties context and appends postcode lookup input, button, message field - * and select container - * - * Does not render element if a custom element has been provided - */ - - }, { - key: "render", - value: function render() { - this.context.innerHTML = ""; - if (!this.options.input) this.context.appendChild(this.input); - if (!this.options.button) this.context.appendChild(this.button); - if (!this.options.selectContainer) this.context.appendChild(this.selectContainer); - if (!this.options.message) this.context.appendChild(this.message); - if (!this.options.unhide && this.options.hide.length) this.context.appendChild(this.unhide); - } - }]); - - return Controller; - }(); - - /** - * @module Setup - */ - /** - * Creates Postcode lookup field and button when called on
- * - * First argument `context` is a query selector string which designates where on the DOM the plugin will be instantiated - * - * Second argument `config` allows for advanced configuration of the plugin - * - * When invoked, an instance of the Postcode Lookup controller is stored in contollers - * - * Returns an instance of Postcode Lookup controller unless `checkKey: true`. If key checking is enabled, controller can be accessed by the `onLoaded` callback - * - * @example - * - *```javascript - * PostcodeLookup.setup({ - * context: "#container", - * apiKey: "foo", - * output_fields: { - * line_1: "#address_line_1", - * line_2: "#address_line_2", - * line_3: "#address_line_3", - * post_town: "#post_town", - * postcode: "#postcode", - * } - * }); - *``` - */ - - var setup = function setup(config) { - var controller = new Controller(config); - controllers.push(controller); - return controller; - }; - /** - * Caches all instances of the plugin created via `setup` - */ - - var controllers = []; - - function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - - function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - - var isTrue = function isTrue() { - return true; - }; - - var NOOP$1 = function NOOP() {}; - - var getAnchors = function getAnchors(config) { - var scope = getScope$2(config.scope || null); - var matches = scope.querySelectorAll(config.anchor || config.context || config.scope); - return toArray$1(matches).filter(function (e) { - return !loaded$1(e); - }); - }; - /** - * Dynamically apply PostcodeLookup - * when relevant html configuration appear - * - Exits if page test is fails - * - Not binding when context is null or already have controller bound - * - Use controller bind to build solution - */ - - - var watch = function watch(config) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var _options$pageTest = options.pageTest, - pageTest = _options$pageTest === void 0 ? isTrue : _options$pageTest, - _options$onError = options.onError, - onError = _options$onError === void 0 ? NOOP$1 : _options$onError, - _options$onBindAttemp = options.onBindAttempt, - onBindAttempt = _options$onBindAttemp === void 0 ? NOOP$1 : _options$onBindAttemp, - _options$onBind = options.onBind, - onBind = _options$onBind === void 0 ? NOOP$1 : _options$onBind, - anchor = options.anchor, - _options$onAnchorFoun = options.onAnchorFound, - onAnchorFound = _options$onAnchorFoun === void 0 ? NOOP$1 : _options$onAnchorFoun, - _options$getScope = options.getScope, - getScope = _options$getScope === void 0 ? getScope$2 : _options$getScope; - var controller; - - var bind = function bind() { - try { - onBindAttempt(config); - getAnchors(_objectSpread$1({ - anchor: anchor - }, config)).forEach(function (anchor) { - if (!pageTest()) return; - var scope = getScope(anchor); - onAnchorFound({ - anchor: anchor, - scope: scope, - config: config - }); //deploy solution - - controller = setup(config); - markLoaded$1(anchor); - onBind(controller); - }); - } catch (error) { - onError(error); - } - }; // @ts-expect-error - - - var _watchChange = watchChange({ - config: config, - bind: bind - }), - start = _watchChange.start, - stop = _watchChange.stop; //start watching changes - - - start(); - return { - start: start, - stop: stop, - controller: controller - }; - }; - - /** - * @module Postcode-Lookup Exports - */ - /** - * Namespace that exports Postcode Lookup methods and classes - */ - - var PostcodeLookup = { - controllers: controllers, - setup: setup, - Controller: Controller, - defaults: defaults, - watch: watch - }; - - function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - - function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - var hoistCountry = function hoistCountry(config, outputFields, linesIdentifier) { - if (config.hoistCountry !== true) return; - if (!outputFields.country) return; - if (!outputFields.line_1) return; - var elem = getParent$1(outputFields.country, "div", function (e) { - return e.classList.contains("field"); - }); - if (!elem) return; - var target = getLinesContainer(outputFields, linesIdentifier); - if (!target) return; - - if (!elem.hasAttribute("country-hoist")) { - elem.setAttribute("country-hoist", "true"); - insertBefore({ - elem: elem, - target: target - }); - } - }; - var getLinesContainer = function getLinesContainer(_ref, linesIdentifier) { - var line_1 = _ref.line_1; - if (line_1 === null) return null; - var parentScope = linesIdentifier ? linesIdentifier.parentScope : "fieldset"; - var parentTest = linesIdentifier ? linesIdentifier.parentTest : function (e) { - return e.classList.contains("field"); - }; - return getParent$1(line_1, parentScope, parentTest); - }; - var SUPPORTED_COUNTRIES = ["England", "Scotland", "Wales", "Northern Ireland", "Channel Islands", "Isle of Man", "United Kingdom", "Jersey", "Guernsey", "GB", "IM", "JE", "GG"]; - var EXTENDED_COUNTRIES = ["United States of America", "US"]; - var supportedCountries = function supportedCountries(extended) { - //@ts-expect-error - if (extended) return SUPPORTED_COUNTRIES.concat(EXTENDED_COUNTRIES); - return SUPPORTED_COUNTRIES; - }; - var countryIsSupported = function countryIsSupported(e) { - var extended = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - var country = e.value; - return supportedCountries(extended).reduce(function (prev, supported) { - if (country === supported) return true; - return prev; - }, false); - }; - var addLookupLabel = function addLookupLabel(postcodeField) { - var span = document.createElement("span"); - span.innerText = "Search your Postcode"; - var elem = document.createElement("label"); - elem.className = "label"; - elem.setAttribute("for", "idpc_postcode_lookup"); - elem.appendChild(span); - insertBefore({ - target: postcodeField.firstChild, - elem: elem - }); - return elem; - }; - - var NOOP = function NOOP() {}; - - var watchCountry = function watchCountry(_ref2, activate, deactivate) { - var country = _ref2.country; - var extended = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; - if (!country) return NOOP; - - var checkCountry = function checkCountry(target) { - if (countryIsSupported(target, extended)) return activate(); - deactivate(); - }; - - country.addEventListener("change", function (event) { - checkCountry(event.target); - }); - return checkCountry(country); - }; - - var getFields = function getFields(outputFields, scope) { - var result = {}; - Object.keys(outputFields).forEach(function (key) { - //@ts-expect-error - result[key] = toElem$1(outputFields[key], scope); - }); - return result; - }; - - var setupPostcodeLookup = function setupPostcodeLookup(config, outputFields) { - var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - var linesIdentifier = arguments.length > 3 ? arguments[3] : undefined; - if (config.postcodeLookup !== true) return; - PostcodeLookup.watch(_objectSpread({ - apiKey: config.apiKey, - checkKey: true, - context: "div.idpc_lookup", - outputFields: outputFields, - selectStyle: { - "margin-top": "5px", - "margin-bottom": "5px" - }, - buttonStyle: { - "position": "absolute", - "right": 0 - }, - contextStyle: { - "position": "relative" - }, - onLoaded: function onLoaded() { - var _this = this; - - // Add search label - var label = addLookupLabel(this.context); - watchCountry(this.options.outputFields, function () { - label.hidden = false; - _this.context.style.display = "block"; - }, function () { - label.hidden = true; - _this.context.style.display = "none"; - }); - } - }, config.postcodeLookupOverride), _objectSpread({ - getScope: function getScope(anchor) { - return getParent$1(anchor, "FORM"); - }, - anchor: outputFields.line_2, - onAnchorFound: function onAnchorFound(options) { - var _target$parentElement; - - var scope = options.scope; - var targets = getFields(outputFields, scope); - var target = getLinesContainer(targets, linesIdentifier); //@ts-expect-error - - options.config.outputFields = targets; - if (target === null) return; - hoistCountry(config, targets, linesIdentifier); - if ((_target$parentElement = target.parentElement) !== null && _target$parentElement !== void 0 && _target$parentElement.querySelector('.idpc_lookup[idpc="true"]')) return; - var postcodeField = document.createElement("div"); - postcodeField.className = "idpc_lookup field"; - options.config.context = postcodeField; - return insertBefore({ - target: target, - elem: postcodeField - }); - } - }, options)); - }; - var setupAutocomplete = /*#__PURE__*/function () { - var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(config, outputFields) { - var options, - linesIdentifier, - _args = arguments; - return _regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - options = _args.length > 2 && _args[2] !== undefined ? _args[2] : {}; - linesIdentifier = _args.length > 3 ? _args[3] : undefined; - console.log(config, outputFields, options); - - if (!(config.autocomplete !== true)) { - _context.next = 5; - break; - } - - return _context.abrupt("return"); - - case 5: - if (!(outputFields.line_1 === undefined)) { - _context.next = 7; - break; - } - - return _context.abrupt("return"); - - case 7: - _context.next = 9; - return AddressFinder.watch(_objectSpread({ - apiKey: config.apiKey, - checkKey: true, - onLoaded: function onLoaded() { - var _this2 = this; - - //@ts-expect-error - this.options.outputFields = getFields(outputFields, this.scope); //@ts-expect-error - - //@ts-expect-error - hoistCountry(config, this.options.outputFields, linesIdentifier); - watchCountry(this.options.outputFields, function () { - return _this2.attach(); - }, function () { - return _this2.detach(); - }, true); - }, - outputFields: outputFields - }, config.autocompleteOverride), options); - - case 9: - case "end": - return _context.stop(); - } - } - }, _callee); - })); - - return function setupAutocomplete(_x, _x2) { - return _ref3.apply(this, arguments); - }; - }(); - var includes = function includes(haystack, needle) { - return haystack.indexOf(needle) !== -1; - }; - - var selectors$1 = { - line_1: '[name="street[0]"]', - line_2: '[name="street[1]"]', - line_3: '[name="street[2]"]', - postcode: '[name="postcode"]', - post_town: '[name="city"]', - organisation_name: '[name="company"]', - county: '[name="region"]', - country: '[name="country_id"]' - }; - var pageTest$3 = function pageTest() { - return includes(window.location.pathname, "/checkout"); - }; - var getScope = function getScope(anchor) { - return getParent$1(anchor, "form"); - }; - var bind$3 = function bind(config) { - setupAutocomplete(config, selectors$1, { - pageTest: pageTest$3, - getScope: getScope - }); - setupPostcodeLookup(config, selectors$1, { - pageTest: pageTest$3, - getScope: getScope - }); - }; - - var pageTest$2 = function pageTest() { - return includes(window.location.pathname, "/checkout"); - }; - - var bind$2 = function bind(config) { - setupAutocomplete(config, selectors$1, { - pageTest: pageTest$2 - }); - setupPostcodeLookup(config, selectors$1, { - pageTest: pageTest$2 - }); - }; - - var selectors = { - line_1: "#street_1", - line_2: "#street_2", - line_3: "#street_3", - organisation_name: "#company", - post_town: "#city", - county: "#region", - country: "#country", - postcode: '[name="postcode"]' - }; - var linesIdentifier = { - parentScope: "div", - parentTest: function parentTest(e) { - return e.classList.contains("field"); - } - }; - - var pageTest$1 = function pageTest() { - return includes(window.location.pathname, "/multishipping"); - }; - - var bind$1 = function bind(config) { - setupAutocomplete(config, selectors, { - pageTest: pageTest$1 - }, linesIdentifier); - setupPostcodeLookup(config, selectors, { - pageTest: pageTest$1 - }, linesIdentifier); - }; - - var pageTest = function pageTest() { - return includes(window.location.pathname, "/customer/address"); - }; - - var bind = function bind(config) { - setupAutocomplete(config, selectors, { - pageTest: pageTest - }); - setupPostcodeLookup(config, selectors, { - pageTest: pageTest - }, linesIdentifier); - }; - - window.idpcStart = function () { - [bind$2, bind$3, bind, bind$1].forEach(function (bind) { - var conf = config(); - if (conf) bind(conf); - }); - }; - -})(); +!function(){"use strict";function t(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}var e=function(t){return"string"==typeof t},n=function(t){return t.setAttribute("idpc","true")},r=function(){return!0},o=function(t,e){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:r,o=t,i=e.toUpperCase();"HTML"!==o.tagName;){if(o.tagName===i&&n(o))return o;if(null===o.parentNode)return null;o=o.parentNode}return null},i=function(t){var e=t.elem,n=t.target,r=n.parentNode;if(null!==r)return r.insertBefore(e,n),e},s=function(t,n){return e(t)?n.querySelector(t):t},a=function(){return window.document},u=function(t){return e(t)?a().querySelector(t):null===t?a():t},c=function(t,e){var n=t.getAttribute("style");return Object.keys(e).forEach((function(n){return t.style[n]=e[n]})),n},l=function(t){return t.style.display="none",t},f=function(t){return t.style.display="",t},p=function(t){null!==t&&null!==t.parentNode&&t.parentNode.removeChild(t)},h=function(t,e,n){for(var r=t.querySelectorAll(e),o=0;o=1&&e<=31||127==e||0==r&&e>=48&&e<=57||1==r&&e>=48&&e<=57&&45==i?"\\"+e.toString(16)+" ":(0!=r||1!=n||45!=e)&&(e>=128||45==e||95==e||e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122)?t.charAt(r):"\\"+t.charAt(r):o+="οΏ½";return o},g=function(t,e){return t.dispatchEvent(function(t){var e=t.event,n=t.bubbles,r=void 0===n||n,o=t.cancelable,i=void 0===o||o;if("function"==typeof window.Event)return new window.Event(e,{bubbles:r,cancelable:i});var s=document.createEvent("Event");return s.initEvent(e,r,i),s}({event:e}))},b=function(t){return null!==t&&t instanceof HTMLSelectElement},w=function(t){return null!==t&&t instanceof HTMLInputElement},O=function(t){return null!==t&&t instanceof HTMLTextAreaElement},S=function(t,e){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];t&&(w(t)||O(t))&&C({e:t,value:e,skipTrigger:n})},E=function(t,e){return null!==e&&null!==t.querySelector('[value="'.concat(e,'"]'))},j=function(t,e){var n=Object.getOwnPropertyDescriptor(t.constructor.prototype,"value");void 0!==n&&(void 0!==n.set&&n.set.call(t,e))},C=function(t){null!==t.value&&(function(t){var e=t.e,n=t.value,r=t.skipTrigger;null!==n&&b(e)&&(j(e,n),r||g(e,"select"),g(e,"change"))}(t),function(t){var e=t.e,n=t.value,r=t.skipTrigger;null!==n&&(w(e)||O(e))&&(j(e,n),r||g(e,"input"),g(e,"change"))}(t))},x=function(t){return/^GY/.test(t.postcode)?"GG":/^JE/.test(t.postcode)?"JE":null},k="United Kingdom",P="Isle of Man",A="England",T="Scotland",_="Wales",L="Northern Ireland",N="Channel Islands",D=function(t){var e=t.country;if(e===A)return k;if(e===T)return k;if(e===_)return k;if(e===L)return k;if(e===P)return P;if(e===N){var n=x(t);if("GG"===n)return"Guernsey";if("JE"===n)return"Jersey"}return null},R=function(t,e){if(t){if(b(t)){var n=function(t){var e=t.country;return e===A||e===T||e===_||e===L?"GB":e===P?"IM":e===N?x(t):null}(e);E(t,n)&&C({e:t,value:n});var r=D(e);E(t,r)&&C({e:t,value:r})}if(w(t)){var o=D(e);C({e:t,value:o})}}},U={};function q(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n=e||n<0||h&&t-f>=i}function g(){var t=Date.now();if(m(t))return function(t){if(a=void 0,d&&r)return v(t);return r=o=void 0,s}(t);a=setTimeout(g,function(t){var n=t-f,r=e-(t-u);return h?Math.min(r,i-n):r}(t))}function b(){for(var t=Date.now(),n=m(t),i=arguments.length,c=new Array(i),l=0;l=0;--r){var o=this.tryEntries[r],i=o.completion;if("root"===o.tryLoc)return n("end");if(o.tryLoc<=this.prev){var s=mt.call(o,"catchLoc"),a=mt.call(o,"finallyLoc");if(s&&a){if(this.prev=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&mt.call(r,"finallyLoc")&&this.prev=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),Mt(n),Pt}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var o=r.arg;Mt(n)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,n){return this.delegate={iterator:Ht(t),resultName:e,nextLoc:n},"next"===this.method&&(this.arg=vt),Pt}};var zt={wrap:St,isGeneratorFunction:qt,AsyncIterator:Ft,mark:function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,_t):(t.__proto__=_t,Ot in t||(t[Ot]="GeneratorFunction")),t.prototype=Object.create(Rt),t},awrap:function(t){return{__await:t}},async:function(t,e,n,r,o){void 0===o&&(o=Promise);var i=new Ft(St(t,e,n,r),o);return qt(e)?i:i.next().then((function(t){return t.done?t.value:i.next()}))},keys:function(t){var e=[];for(var n in t)e.push(n);return e.reverse(),function n(){for(;e.length;){var r=e.pop();if(r in t)return n.value=r,n.done=!1,n}return n.done=!0,n}},values:Ht};function Kt(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function Wt(t,e){for(var n=0;n=e||n<0||f&&t-c>=i}function y(){var t=xe();if(v(t))return m(t);a=setTimeout(y,function(t){var n=e-(t-u);return f?Ae(n,i-(t-c)):n}(t))}function m(t){return a=void 0,p&&r?h(t):(r=o=void 0,s)}function g(){var t=xe(),n=v(t);if(r=arguments,o=this,u=t,n){if(void 0===a)return d(u);if(f)return clearTimeout(a),a=setTimeout(y,e),h(u)}return void 0===a&&(a=setTimeout(y,e)),s}return e=ke(e)||0,Ce(n)&&(l=!!n.leading,i=(f="maxWait"in n)?Pe(ke(n.maxWait)||0,e):i,p="trailing"in n?!!n.trailing:p),g.cancel=function(){void 0!==a&&clearTimeout(a),c=0,r=u=o=a=void 0},g.flush=function(){return void 0===a?s:m(xe())},g},_e=function(t,e){return t.id=e,t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.setAttribute("aria-atomic","true"),t};function Le(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function Ne(e){for(var n=1;n0&&(e[n]=o),e}),{})},Be=function(t){return"string"==typeof t},Ie=function(t){var e=[];return function(t){return Array.isArray(t)}(t)?(t.forEach((function(t){Me(t)&&e.push(t.toString()),Be(t)&&e.push(t)})),e.join(",")):Me(t)?t.toString():Be(t)?t:""},Me=function(t){return"number"==typeof t},Ge=function(t,e){var n=t.timeout;return Me(n)?n:e.config.timeout},He=function(t,e){var n=t.header,r=void 0===n?{}:n;return qe(qe({},e.config.header),Fe(r))};function Je(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function ze(t,e){return ze=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t},ze(t,e)}function Ke(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&ze(t,e)}function We(t,e){if(e&&("object"===lt(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return Je(t)}function Ve(t){return Ve=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},Ve(t)}function Ye(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function $e(t,e,n){return $e=Ye()?Reflect.construct:function(t,e,n){var r=[null];r.push.apply(r,e);var o=new(Function.bind.apply(t,r));return n&&ze(o,n.prototype),o},$e.apply(null,arguments)}function Xe(t){var e="function"==typeof Map?new Map:void 0;return Xe=function(t){if(null===t||(n=t,-1===Function.toString.call(n).indexOf("[native code]")))return t;var n;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,r)}function r(){return $e(t,arguments,Ve(this).constructor)}return r.prototype=Object.create(t.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),ze(r,t)},Xe(t)}function Qe(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var n,r=Ve(t);if(e){var o=Ve(this).constructor;n=Reflect.construct(r,arguments,o)}else n=r.apply(this,arguments);return We(this,n)}}var Ze=function(t){Ke(n,t);var e=Qe(n);function n(t){var r;Kt(this,n);var o=(this instanceof n?this.constructor:void 0).prototype;(r=e.call(this)).__proto__=o;var i=t.message,s=t.httpStatus,a=t.metadata,u=void 0===a?{}:a;return r.message=i,r.name="Ideal Postcodes Error",r.httpStatus=s,r.metadata=u,Error.captureStackTrace&&Error.captureStackTrace(Je(r),n),r}return n}(Xe(Error)),tn=function(t){Ke(n,t);var e=Qe(n);function n(t){var r;return Kt(this,n),(r=e.call(this,{httpStatus:t.httpStatus,message:t.body.message})).response=t,r}return n}(Ze),en=function(t){Ke(n,t);var e=Qe(n);function n(){return Kt(this,n),e.apply(this,arguments)}return n}(tn),nn=function(t){Ke(n,t);var e=Qe(n);function n(){return Kt(this,n),e.apply(this,arguments)}return n}(tn),rn=function(t){Ke(n,t);var e=Qe(n);function n(){return Kt(this,n),e.apply(this,arguments)}return n}(nn),on=function(t){Ke(n,t);var e=Qe(n);function n(){return Kt(this,n),e.apply(this,arguments)}return n}(tn),sn=function(t){Ke(n,t);var e=Qe(n);function n(){return Kt(this,n),e.apply(this,arguments)}return n}(on),an=function(t){Ke(n,t);var e=Qe(n);function n(){return Kt(this,n),e.apply(this,arguments)}return n}(on),un=function(t){Ke(n,t);var e=Qe(n);function n(){return Kt(this,n),e.apply(this,arguments)}return n}(tn),cn=function(t){Ke(n,t);var e=Qe(n);function n(){return Kt(this,n),e.apply(this,arguments)}return n}(un),ln=function(t){Ke(n,t);var e=Qe(n);function n(){return Kt(this,n),e.apply(this,arguments)}return n}(un),fn=function(t){Ke(n,t);var e=Qe(n);function n(){return Kt(this,n),e.apply(this,arguments)}return n}(un),pn=function(t){Ke(n,t);var e=Qe(n);function n(){return Kt(this,n),e.apply(this,arguments)}return n}(un),hn=function(t){Ke(n,t);var e=Qe(n);function n(){return Kt(this,n),e.apply(this,arguments)}return n}(tn),dn=function(t){return null!==(e=t)&&"object"===lt(e)&&("string"==typeof t.message&&"number"==typeof t.code);var e},vn=function(t){var e=t.httpStatus,n=t.body;if(!function(t){return!(t<200||t>=300)}(e)){if(dn(n)){var r=n.code;if(4010===r)return new rn(t);if(4040===r)return new cn(t);if(4042===r)return new ln(t);if(4044===r)return new fn(t);if(4046===r)return new pn(t);if(4020===r)return new sn(t);if(4021===r)return new an(t);if(404===e)return new un(t);if(400===e)return new en(t);if(402===e)return new on(t);if(401===e)return new nn(t);if(500===e)return new hn(t)}return new Ze({httpStatus:e,message:JSON.stringify(n)})}},yn=function(t,e){return[t.client.url(),t.resource,encodeURIComponent(e),t.action].filter((function(t){return void 0!==t})).join("/")},mn=function(t){var e=t.client;return function(n,r){return e.config.agent.http({method:"GET",url:yn(t,n),query:Fe(r.query),header:He(r,e),timeout:Ge(r,e)}).then((function(t){var e=vn(t);if(e)throw e;return t}))}},gn=function(t){var e=t.client,n=t.timeout,r=t.api_key||t.client.config.api_key,o=t.licensee,i={query:void 0===o?{}:{licensee:o},header:{}};return void 0!==n&&(i.timeout=n),function(t,e,n){return mn({resource:"keys",client:t})(e,n)}(e,r,i).then((function(t){return t.body.result}))},bn="autocomplete/addresses",wn=function(t,e){return function(t){var e=t.client,n=t.resource;return function(t){return e.config.agent.http({method:"GET",url:"".concat(e.url(),"/").concat(n),query:Fe(t.query),header:He(t,e),timeout:Ge(t,e)}).then((function(t){var e=vn(t);if(e)throw e;return t}))}}({resource:bn,client:t})(e)},On={exports:{}},Sn=function(t,e){return function(){for(var n=new Array(arguments.length),r=0;r=0)return;o[e]="set-cookie"===e?(o[e]?o[e]:[]).concat([n]):o[e]?o[e]+", "+n:n}})),o):o},ir=$n,sr=Mn,ar=mr,ur=Qn,cr=function(t){return new Promise((function(e,n){var r,o=t.data,i=t.headers,s=t.responseType;function a(){t.cancelToken&&t.cancelToken.unsubscribe(r),t.signal&&t.signal.removeEventListener("abort",r)}Zn.isFormData(o)&&delete i["Content-Type"];var u=new XMLHttpRequest;if(t.auth){var c=t.auth.username||"",l=t.auth.password?unescape(encodeURIComponent(t.auth.password)):"";i.Authorization="Basic "+btoa(c+":"+l)}var f=rr(t.baseURL,t.url);function p(){if(u){var r="getAllResponseHeaders"in u?or(u.getAllResponseHeaders()):null,o={data:s&&"text"!==s&&"json"!==s?u.response:u.responseText,status:u.status,statusText:u.statusText,headers:r,config:t,request:u};tr((function(t){e(t),a()}),(function(t){n(t),a()}),o),u=null}}if(u.open(t.method.toUpperCase(),nr(f,t.params,t.paramsSerializer),!0),u.timeout=t.timeout,"onloadend"in u?u.onloadend=p:u.onreadystatechange=function(){u&&4===u.readyState&&(0!==u.status||u.responseURL&&0===u.responseURL.indexOf("file:"))&&setTimeout(p)},u.onabort=function(){u&&(n(sr("Request aborted",t,"ECONNABORTED",u)),u=null)},u.onerror=function(){n(sr("Network Error",t,null,u)),u=null},u.ontimeout=function(){var e=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",r=t.transitional||ar.transitional;t.timeoutErrorMessage&&(e=t.timeoutErrorMessage),n(sr(e,t,r.clarifyTimeoutError?"ETIMEDOUT":"ECONNABORTED",u)),u=null},Zn.isStandardBrowserEnv()){var h=(t.withCredentials||ir(f))&&t.xsrfCookieName?er.read(t.xsrfCookieName):void 0;h&&(i[t.xsrfHeaderName]=h)}"setRequestHeader"in u&&Zn.forEach(i,(function(t,e){void 0===o&&"content-type"===e.toLowerCase()?delete i[e]:u.setRequestHeader(e,t)})),Zn.isUndefined(t.withCredentials)||(u.withCredentials=!!t.withCredentials),s&&"json"!==s&&(u.responseType=t.responseType),"function"==typeof t.onDownloadProgress&&u.addEventListener("progress",t.onDownloadProgress),"function"==typeof t.onUploadProgress&&u.upload&&u.upload.addEventListener("progress",t.onUploadProgress),(t.cancelToken||t.signal)&&(r=function(t){u&&(n(!t||t&&t.type?new ur("canceled"):t),u.abort(),u=null)},t.cancelToken&&t.cancelToken.subscribe(r),t.signal&&(t.signal.aborted?r():t.signal.addEventListener("abort",r))),o||(o=null),u.send(o)}))},lr=_n,fr=function(t,e){Fn.forEach(t,(function(n,r){r!==e&&r.toUpperCase()===e.toUpperCase()&&(t[e]=n,delete t[r])}))},pr=Bn,hr={"Content-Type":"application/x-www-form-urlencoded"};function dr(t,e){!lr.isUndefined(t)&&lr.isUndefined(t["Content-Type"])&&(t["Content-Type"]=e)}var vr,yr={transitional:{silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},adapter:(("undefined"!=typeof XMLHttpRequest||"undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process))&&(vr=cr),vr),transformRequest:[function(t,e){return fr(e,"Accept"),fr(e,"Content-Type"),lr.isFormData(t)||lr.isArrayBuffer(t)||lr.isBuffer(t)||lr.isStream(t)||lr.isFile(t)||lr.isBlob(t)?t:lr.isArrayBufferView(t)?t.buffer:lr.isURLSearchParams(t)?(dr(e,"application/x-www-form-urlencoded;charset=utf-8"),t.toString()):lr.isObject(t)||e&&"application/json"===e["Content-Type"]?(dr(e,"application/json"),function(t,e,n){if(lr.isString(t))try{return(e||JSON.parse)(t),lr.trim(t)}catch(t){if("SyntaxError"!==t.name)throw t}return(n||JSON.stringify)(t)}(t)):t}],transformResponse:[function(t){var e=this.transitional||yr.transitional,n=e&&e.silentJSONParsing,r=e&&e.forcedJSONParsing,o=!n&&"json"===this.responseType;if(o||r&&lr.isString(t)&&t.length)try{return JSON.parse(t)}catch(t){if(o){if("SyntaxError"===t.name)throw pr(t,this,"E_JSON_PARSE");throw t}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};lr.forEach(["delete","get","head"],(function(t){yr.headers[t]={}})),lr.forEach(["post","put","patch"],(function(t){yr.headers[t]=lr.merge(hr)}));var mr=yr,gr=_n,br=mr,wr=function(t){return!(!t||!t.__CANCEL__)},Or=_n,Sr=function(t,e,n){var r=this||br;return gr.forEach(n,(function(n){t=n.call(r,t,e)})),t},Er=wr,jr=mr,Cr=Qn;function xr(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new Cr("canceled")}var kr=_n,Pr=function(t,e){e=e||{};var n={};function r(t,e){return kr.isPlainObject(t)&&kr.isPlainObject(e)?kr.merge(t,e):kr.isPlainObject(e)?kr.merge({},e):kr.isArray(e)?e.slice():e}function o(n){return kr.isUndefined(e[n])?kr.isUndefined(t[n])?void 0:r(void 0,t[n]):r(t[n],e[n])}function i(t){if(!kr.isUndefined(e[t]))return r(void 0,e[t])}function s(n){return kr.isUndefined(e[n])?kr.isUndefined(t[n])?void 0:r(void 0,t[n]):r(void 0,e[n])}function a(n){return n in e?r(t[n],e[n]):n in t?r(void 0,t[n]):void 0}var u={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:a};return kr.forEach(Object.keys(t).concat(Object.keys(e)),(function(t){var e=u[t]||o,r=e(t);kr.isUndefined(r)&&e!==a||(n[t]=r)})),n},Ar="0.24.0",Tr=Ar,_r={};["object","boolean","number","function","string","symbol"].forEach((function(t,e){_r[t]=function(n){return lt(n)===t||"a"+(e<1?"n ":" ")+t}}));var Lr={};_r.transitional=function(t,e,n){function r(t,e){return"[Axios v"+Tr+"] Transitional option '"+t+"'"+e+(n?". "+n:"")}return function(n,o,i){if(!1===t)throw new Error(r(o," has been removed"+(e?" in "+e:"")));return e&&!Lr[o]&&(Lr[o]=!0,console.warn(r(o," has been deprecated since v"+e+" and will be removed in the near future"))),!t||t(n,o,i)}};var Nr={assertOptions:function(t,e,n){if("object"!==lt(t))throw new TypeError("options must be an object");for(var r=Object.keys(t),o=r.length;o-- >0;){var i=r[o],s=e[i];if(s){var a=t[i],u=void 0===a||s(a,i,t);if(!0!==u)throw new TypeError("option "+i+" must be "+u)}else if(!0!==n)throw Error("Unknown option "+i)}},validators:_r},Dr=_n,Rr=Dn,Ur=qn,qr=function(t){return xr(t),t.headers=t.headers||{},t.data=Sr.call(t,t.data,t.headers,t.transformRequest),t.headers=Or.merge(t.headers.common||{},t.headers[t.method]||{},t.headers),Or.forEach(["delete","get","head","post","put","patch","common"],(function(e){delete t.headers[e]})),(t.adapter||jr.adapter)(t).then((function(e){return xr(t),e.data=Sr.call(t,e.data,e.headers,t.transformResponse),e}),(function(e){return Er(e)||(xr(t),e&&e.response&&(e.response.data=Sr.call(t,e.response.data,e.response.headers,t.transformResponse))),Promise.reject(e)}))},Fr=Pr,Br=Nr,Ir=Br.validators;function Mr(t){this.defaults=t,this.interceptors={request:new Ur,response:new Ur}}Mr.prototype.request=function(t){"string"==typeof t?(t=arguments[1]||{}).url=arguments[0]:t=t||{},(t=Fr(this.defaults,t)).method?t.method=t.method.toLowerCase():this.defaults.method?t.method=this.defaults.method.toLowerCase():t.method="get";var e=t.transitional;void 0!==e&&Br.assertOptions(e,{silentJSONParsing:Ir.transitional(Ir.boolean),forcedJSONParsing:Ir.transitional(Ir.boolean),clarifyTimeoutError:Ir.transitional(Ir.boolean)},!1);var n=[],r=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(r=r&&e.synchronous,n.unshift(e.fulfilled,e.rejected))}));var o,i=[];if(this.interceptors.response.forEach((function(t){i.push(t.fulfilled,t.rejected)})),!r){var s=[qr,void 0];for(Array.prototype.unshift.apply(s,n),s=s.concat(i),o=Promise.resolve(t);s.length;)o=o.then(s.shift(),s.shift());return o}for(var a=t;n.length;){var u=n.shift(),c=n.shift();try{a=u(a)}catch(t){c(t);break}}try{o=qr(a)}catch(t){return Promise.reject(t)}for(;i.length;)o=o.then(i.shift(),i.shift());return o},Mr.prototype.getUri=function(t){return t=Fr(this.defaults,t),Rr(t.url,t.params,t.paramsSerializer).replace(/^\?/,"")},Dr.forEach(["delete","get","head","options"],(function(t){Mr.prototype[t]=function(e,n){return this.request(Fr(n||{},{method:t,url:e,data:(n||{}).data}))}})),Dr.forEach(["post","put","patch"],(function(t){Mr.prototype[t]=function(e,n,r){return this.request(Fr(r||{},{method:t,url:e,data:n}))}}));var Gr=Mr,Hr=Qn;function Jr(t){if("function"!=typeof t)throw new TypeError("executor must be a function.");var e;this.promise=new Promise((function(t){e=t}));var n=this;this.promise.then((function(t){if(n._listeners){var e,r=n._listeners.length;for(e=0;e1&&void 0!==arguments[1]?arguments[1]:{},r=this.retrieve(t);if(r)return Promise.resolve(r);var o=wn(this.client,{query:ao({query:t,api_key:this.client.config.api_key},n)}).then((function(n){var r=n.body.result.hits;return e.store(t,r),r}));return this.store(t,o),o}},{key:"resolve",value:function(t){return(e=this.client,n=t.id,r={query:{api_key:this.client.config.api_key}},mn({resource:bn,client:e,action:"gbr"})(n,r)).then((function(t){return t.body.result}));var e,n,r}}]),t}(),co=function(t){return"string"==typeof t},lo=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"idpc";return t.setAttribute(e,"true")},fo=function(){return!0},po=function(t,e){return co(t)?e.querySelector(t):t},ho=function(){return window.document},vo=function(t){return co(t)?ho().querySelector(t):null===t?ho():t},yo=function(t,e){var n=t.getAttribute("style");return Object.keys(e).forEach((function(n){return t.style[n]=e[n]})),n},mo=function(t){return t.style.display="none",t},go=function(t){return t.style.display="",t},bo=function(t,e,n){for(var r=t.querySelectorAll(e),o=0;o=1&&e<=31||127==e||0==r&&e>=48&&e<=57||1==r&&e>=48&&e<=57&&45==i?"\\"+e.toString(16)+" ":(0!=r||1!=n||45!=e)&&(e>=128||45==e||95==e||e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122)?t.charAt(r):"\\"+t.charAt(r):o+="οΏ½";return o},So=function(t,e){return t.dispatchEvent(function(t){var e=t.event,n=t.bubbles,r=void 0===n||n,o=t.cancelable,i=void 0===o||o;if("function"==typeof window.Event)return new window.Event(e,{bubbles:r,cancelable:i});var s=document.createEvent("Event");return s.initEvent(e,r,i),s}({event:e}))},Eo=function(t){return null!==t&&t instanceof HTMLSelectElement},jo=function(t){return null!==t&&t instanceof HTMLInputElement},Co=function(t){return null!==t&&t instanceof HTMLTextAreaElement},xo=function(t,e){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];t&&(jo(t)||Co(t))&&Ao({e:t,value:e,skipTrigger:n})},ko=function(t,e){return null!==e&&null!==t.querySelector('[value="'.concat(e,'"]'))},Po=function(t,e){var n=Object.getOwnPropertyDescriptor(t.constructor.prototype,"value");void 0!==n&&(void 0!==n.set&&n.set.call(t,e))},Ao=function(t){null!==t.value&&(function(t){var e=t.e,n=t.value,r=t.skipTrigger;null!==n&&Eo(e)&&(Po(e,n),r||So(e,"select"),So(e,"change"))}(t),function(t){var e=t.e,n=t.value,r=t.skipTrigger;null!==n&&(jo(e)||Co(e))&&(Po(e,n),r||So(e,"input"),So(e,"change"))}(t))},To=function(t){return/^GY/.test(t.postcode)?"GG":/^JE/.test(t.postcode)?"JE":null},_o="United Kingdom",Lo="Isle of Man",No="England",Do="Scotland",Ro="Wales",Uo="Northern Ireland",qo="Channel Islands",Fo=function(t){var e=t.country;if(e===No)return _o;if(e===Do)return _o;if(e===Ro)return _o;if(e===Uo)return _o;if(e===Lo)return Lo;if(e===qo){var n=To(t);if("GG"===n)return"Guernsey";if("JE"===n)return"Jersey"}return null},Bo=function(t,e){if(t){if(Eo(t)){var n=function(t){var e=t.country;return e===No||e===Do||e===Ro||e===Uo?"GB":e===Lo?"IM":e===qo?To(t):null}(e);ko(t,n)&&Ao({e:t,value:n});var r=Fo(e);ko(t,r)&&Ao({e:t,value:r})}if(jo(t)){var o=Fo(e);Ao({e:t,value:o})}}},Io={};"undefined"!=typeof window&&(window.idpcGlobal?Io=window.idpcGlobal:window.idpcGlobal=Io);var Mo=function(){return Io};function Go(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function Ho(e){for(var n=1;n0)&&!(r=i.next()).done;)s.push(r.value)}catch(t){o={error:t}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return s}!function(t){t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped"}(Jo||(Jo={}));var ri={type:"xstate.init"};function oi(t){return void 0===t?[]:[].concat(t)}function ii(t,e){return"string"==typeof(t="string"==typeof t&&e&&e[t]?e[t]:t)?{type:t}:"function"==typeof t?{type:t.name,exec:t}:t}function si(t){return function(e){return t===e}}function ai(t){return"string"==typeof t?{type:t}:t}function ui(t,e){return{value:t,context:e,actions:[],changed:!1,matches:si(t)}}function ci(t,e,n){var r=e,o=!1;return[t.filter((function(t){if("xstate.assign"===t.type){o=!0;var e=Object.assign({},r);return"function"==typeof t.assignment?e=t.assignment(r,n):Object.keys(t.assignment).forEach((function(o){e[o]="function"==typeof t.assignment[o]?t.assignment[o](r,n):t.assignment[o]})),r=e,!1}return!0})),r,o]}function li(t,e){void 0===e&&(e={});var n=ni(ci(oi(t.states[t.initial].entry).map((function(t){return ii(t,e.actions)})),t.context,ri),2),r=n[0],o=n[1],i={config:t,_options:e,initialState:{value:t.initial,actions:r,context:o,matches:si(t.initial)},transition:function(e,n){var r,o,s="string"==typeof e?{value:e,context:t.context}:e,a=s.value,u=s.context,c=ai(n),l=t.states[a];if(l.on){var f=oi(l.on[c.type]);try{for(var p=function(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}(f),h=p.next();!h.done;h=p.next()){var d=h.value;if(void 0===d)return ui(a,u);var v="string"==typeof d?{target:d}:d,y=v.target,m=v.actions,g=void 0===m?[]:m,b=v.cond,w=void 0===b?function(){return!0}:b,O=void 0===y,S=null!=y?y:a,E=t.states[S];if(w(u,c)){var j=ni(ci((O?oi(g):[].concat(l.exit,g,E.entry).filter((function(t){return t}))).map((function(t){return ii(t,i._options.actions)})),u,c),3),C=j[0],x=j[1],k=j[2],P=null!=y?y:a;return{value:P,context:x,actions:C,changed:y!==a||C.length>0||k,matches:si(P)}}}}catch(t){r={error:t}}finally{try{h&&!h.done&&(o=p.return)&&o.call(p)}finally{if(r)throw r.error}}}return ui(a,u)}};return i}var fi=function(t,e){return t.actions.forEach((function(n){var r=n.exec;return r&&r(t.context,e)}))};function pi(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function hi(e){for(var n=1;n0}},{target:"notifying"}]}},notifying:{entry:["renderNotice"],exit:["clearAnnouncement"],on:hi(hi(hi(hi(hi({},vi),yi),mi),di),Oi)},suggesting_country:{entry:["renderContexts","gotoCurrent","expand","addCountryHint"],exit:["resetCurrent","gotoCurrent","contract","clearHint"],on:hi(hi(hi(hi(hi(hi({},vi),mi),gi),bi),wi),{},{INPUT:{actions:["countryInput"]},SELECT_COUNTRY:{target:"notifying",actions:["selectCountry"]}})},suggesting:{entry:["renderSuggestions","gotoCurrent","expand","addHint"],exit:["resetCurrent","gotoCurrent","contract","clearHint"],on:hi(hi(hi(hi(hi(hi(hi(hi(hi({},vi),yi),mi),di),Oi),gi),bi),wi),{},{SELECT_ADDRESS:{target:"closed",actions:["selectAddress"]}})}}},{actions:{addHint:function(){e.setPlaceholder(e.options.msgPlaceholder)},addCountryHint:function(){e.setPlaceholder(e.options.msgPlaceholderCountry)},clearHint:function(){e.unsetPlaceholder()},gotoCurrent:function(){e.goToCurrent()},resetCurrent:function(){e.current=-1},input:function(t,n){"INPUT"===n.type&&e.retrieveSuggestions(n.event)},countryInput:function(){},clearAnnouncement:function(){e.announce("")},renderContexts:function(t,n){"CHANGE_COUNTRY"===n.type&&e.renderContexts()},renderSuggestions:function(t,n){"SUGGEST"===n.type&&e.renderSuggestions()},updateSuggestions:function(t,n){"SUGGEST"===n.type&&e.updateSuggestions(n.suggestions)},close:function(t,n){if("CLOSE"===n.type)return e.close(n.reason);e.close()},open:function(){e.open()},expand:function(){e.ariaExpand()},contract:function(){e.ariaContract()},updateMessage:function(t,n){"NOTIFY"===n.type&&(e.notification=n.notification)},renderNotice:function(){e.renderNotice()},next:function(){e.next()},previous:function(){e.previous()},selectCountry:function(t,n){if("SELECT_COUNTRY"===n.type){var r=n.contextDetails;r&&(e.applyContext(r),e.notification="Country switched to ".concat(r.name," ").concat(r.icon))}},selectAddress:function(t,n){if("SELECT_ADDRESS"===n.type){var r=n.suggestion;r&&e.applySuggestion(r)}}}});return function(t){var e=t.initialState,n=Jo.NotStarted,r=new Set,o={_machine:t,send:function(o){n===Jo.Running&&(e=t.transition(e,o),fi(e,ai(o)),r.forEach((function(t){return t(e)})))},subscribe:function(t){return r.add(t),t(e),{unsubscribe:function(){return r.delete(t)}}},start:function(r){if(r){var i="object"==lt(r)?r:{context:t.config.context,value:r};e={value:i.value,actions:[],context:i.context,matches:si(i.value)}}return n=Jo.Running,fi(e,ri),o},stop:function(){return n=Jo.Stopped,r.clear(),o},get state(){return e},get status(){return n}};return o}(n)};function Ei(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function ji(e){for(var n=1;n0&&!e.some((function(t){return t===r})))return"continue";var o=t[r],a=o.name,u=o.icon;n.push({code:r,name:a,icon:u})},i=0,s=r;i0&&void 0!==arguments[0]?arguments[0]:"idpc_";return function(){var e=Mo();return e.idGen||(e.idGen={}),void 0===e.idGen[t]&&(e.idGen[t]=0),e.idGen[t]+=1,"".concat(t).concat(e.idGen[t])}}("idpcaf"),this.container=this.options.document.createElement("div"),this.container.className=this.options.containerClass,this.container.id=this.ids(),this.container.setAttribute("aria-haspopup","listbox"),this.message=this.options.document.createElement("li"),this.message.textContent=this.options.msgInitial,this.message.className=this.options.messageClass,this.countryToggle=this.options.document.createElement("span"),this.countryToggle.className=this.options.countryToggleClass,this.countryToggle.addEventListener("mousedown",_i(this)),this.countryIcon=this.options.document.createElement("span"),this.countryIcon.className="idpc_icon",this.countryIcon.innerText=this.currentContext().icon,this.countryMessage=this.options.document.createElement("span"),this.countryMessage.innerText="Select Country",this.countryMessage.className="idpc_country",this.countryToggle.appendChild(this.countryMessage),this.countryToggle.appendChild(this.countryIcon),this.toolbar=this.options.document.createElement("div"),this.toolbar.className=this.options.toolbarClass,this.toolbar.appendChild(this.countryToggle),this.options.hideToolbar&&mo(this.toolbar),this.list=this.options.document.createElement("ul"),this.list.className=this.options.listClass,this.list.id=this.ids(),this.list.setAttribute("aria-label",this.options.msgList),this.list.setAttribute("role","listbox"),this.mainComponent=this.options.document.createElement("div"),this.mainComponent.appendChild(this.list),this.mainComponent.appendChild(this.toolbar),this.mainComponent.className=this.options.mainClass,mo(this.mainComponent),this.unhideEvent=this.unhideFields.bind(this),this.unhide=this.createUnhide(),!(r=co(this.options.inputField)?this.scope.querySelector(this.options.inputField):this.options.inputField))throw new Error("Address Finder: Unable to find valid input field");this.input=r,this.input.setAttribute("autocomplete",this.options.autocomplete),this.input.setAttribute("aria-autocomplete","list"),this.input.setAttribute("aria-controls",this.list.id),this.input.setAttribute("aria-autocomplete","list"),this.input.setAttribute("aria-activedescendant",""),this.input.setAttribute("autocorrect","off"),this.input.setAttribute("autocapitalize","off"),this.input.setAttribute("spellcheck","false"),this.input.id||(this.input.id=this.ids()),this.ariaAnchor().setAttribute("role","combobox"),this.ariaAnchor().setAttribute("aria-expanded","false"),this.ariaAnchor().setAttribute("aria-owns",this.list.id),this.placeholderCache=this.input.placeholder,this.inputListener=Ti(this),this.blurListener=Pi(this),this.focusListener=Ai(this),this.keydownListener=Li(this);var i=function(t){var e=t.document,n=t.idA,r=t.idB,o=e.createElement("div");o.setAttribute("style","border:0px;padding:0px;clip:rect(0px,0px,0px,0px);height:1px;margin-bottom:-1px;margin-right:-1px;overflow:hidden;position:absolute;white-space:nowrap;width:1px");var i=_e(e.createElement("div"),n),s=_e(e.createElement("div"),r);o.appendChild(i),o.appendChild(s);var a=!0,u=Te((function(t){var e=a?i:s,n=a?s:i;a=!a,e.textContent=t,n.textContent=""}),1500,{});return{container:o,announce:u}}({idA:this.ids(),idB:this.ids(),document:this.options.document}),s=i.container,a=i.announce;this.announce=a,this.alerts=s,this.inputStyle=yo(this.input,this.options.inputStyle),yo(this.container,this.options.containerStyle),yo(this.list,this.options.listStyle);var u=function(t){var e,n=t.input;if(!1===t.options.alignToInput)return{};try{var r=t.options.document.defaultView;if(!r)return{};e=r.getComputedStyle(n).marginBottom}catch(t){return{}}if(!e)return{};var o=parseInt(e.replace("px",""),10);return isNaN(o)||0===o?{}:{marginTop:-1*o+t.options.offset+"px"}}(this);yo(this.mainComponent,ji(ji({},u),this.options.mainStyle)),this.fsm=Si({c:this}),this.init()}return Vt(t,[{key:"setPlaceholder",value:function(t){this.input.placeholder=t}},{key:"unsetPlaceholder",value:function(){if(void 0===this.placeholderCache)return this.input.removeAttribute("placeholder");this.input.placeholder=this.placeholderCache}},{key:"currentContext",value:function(){var t=this.options.contexts[this.context];return{code:this.context,name:t.name,icon:t.icon}}},{key:"load",value:function(){this.attach(),function(t){var e=t.options.injectStyle;if(e){var n=Mo();if(n.afstyle||(n.afstyle={}),co(e)&&!n.afstyle[e]){n.afstyle[e]=!0;var r=function(t,e){var n=e.createElement("link");return n.type="text/css",n.rel="stylesheet",n.href=t,n}(e,t.document);return t.document.head.appendChild(r),r}!0!==e||n.afstyle[""]||(n.afstyle[""]=!0,function(t,e){var n=e.createElement("style");n.type="text/css",n.appendChild(e.createTextNode(t)),e.head.appendChild(n)}(".idpc_af.hidden{display:none}div.idpc_autocomplete{position:relative;margin:0!important;padding:0;border:0;color:#28282b;text-rendering:optimizeLegibility;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}div.idpc_autocomplete>input{display:block}div.idpc_af{position:absolute;left:0;z-index:2000;min-width:100%;box-sizing:border-box;border-radius:3px;background:#fff;border:1px solid rgba(0,0,0,.3);box-shadow:.05em .2em .6em rgba(0,0,0,.2);text-shadow:none;padding:0;margin-top:2px}div.idpc_af>ul{list-style:none;padding:0;max-height:250px;overflow-y:scroll;margin:0!important}div.idpc_af>ul>li{position:relative;padding:.2em .5em;cursor:pointer;margin:0!important}div.idpc_toolbar{padding:.3em .5em;border-top:1px solid rgba(0,0,0,.3);text-align:right}div.idpc_af>ul>li:hover{background-color:#e5e4e2}div.idpc_af>ul>li.idpc_error{padding:.5em;text-align:center;cursor:default!important}div.idpc_af>ul>li.idpc_error:hover{background:#fff;cursor:default!important}div.idpc_af>ul>li[aria-selected=true]{background-color:#e5e4e2;z-index:3000}div.idpc_autocomplete>.idpc-unhide{font-size:.9em;text-decoration:underline;cursor:pointer}div.idpc_af>div>span{padding:.2em .5em;border-radius:3px;cursor:pointer;font-size:110%}span.idpc_icon{font-size:1.2em;line-height:1em;vertical-align:middle}div.idpc_toolbar>span span.idpc_country{margin-right:.3em;max-width:0;font-size:.9em;-webkit-transition:max-width .5s ease-out;transition:max-width .5s ease-out;display:inline-block;vertical-align:middle;white-space:nowrap;overflow:hidden}div.idpc_autocomplete>div>div>span:hover span.idpc_country{max-width:7em}div.idpc_autocomplete>div>div>span:hover{background-color:#e5e4e2;-webkit-transition:background-color .5s ease;-ms-transition:background-color .5s ease;transition:background-color .5s ease}",t.document))}}(this),this.options.onLoaded.call(this)}},{key:"init",value:function(){var t=this;return new Promise((function(e){if(!t.options.checkKey)return t.load(),void e();gn({client:t.client,api_key:t.options.apiKey}).then((function(n){if(!n.available)throw new Error("Key currently not usable");t.load(),e()})).catch((function(n){t.options.onFailedCheck.call(t,n),e()}))}))}},{key:"renderContexts",value:function(){var t=this;this.list.innerHTML="",this.contextSuggestions.forEach((function(e,n){var r=e.name,o=t.options.document.createElement("li");o.textContent=r,o.setAttribute("aria-selected","false"),o.setAttribute("tabindex","-1"),o.setAttribute("aria-posinset","".concat(n+1)),o.setAttribute("aria-setsize",t.contextSuggestions.length.toString()),o.setAttribute("role","option"),yo(o,t.options.liStyle),o.addEventListener("mousedown",(function(n){n.preventDefault(),t.options.onMouseDown.call(t,n),t.fsm.send({type:"SELECT_COUNTRY",contextDetails:e})})),o.id="".concat(t.list.id,"_").concat(n),t.list.appendChild(o)})),this.announce("".concat(this.contextSuggestions.length," countries available"))}},{key:"renderSuggestions",value:function(){var t=this;this.list.innerHTML="";var e=this.suggestions;e.forEach((function(n,r){var o=t.options.document.createElement("li");o.textContent=n.suggestion,o.setAttribute("aria-selected","false"),o.setAttribute("tabindex","-1"),o.setAttribute("title",n.suggestion),o.setAttribute("aria-posinset","".concat(r+1)),o.setAttribute("aria-setsize",e.length.toString()),o.setAttribute("role","option"),yo(o,t.options.liStyle),o.addEventListener("mousedown",(function(e){e.preventDefault(),t.options.onMouseDown.call(t,e),t.fsm.send({type:"SELECT_ADDRESS",suggestion:n})})),o.id="".concat(t.list.id,"_").concat(r),t.list.appendChild(o)})),this.announce("".concat(e.length," addresses available"))}},{key:"goToCurrent",value:function(){var t=this.list.children;this.input.setAttribute("aria-activedescendant","");for(var e=0;e0&&null==this.options.unhide&&this.container.appendChild(this.unhide)),this.fsm.start(),this.options.onMounted.call(this),this.hideFields(),this}},{key:"detach",value:function(){if(this.fsm.status!==Jo.Running)return this;this.input.removeEventListener("input",this.inputListener),this.input.removeEventListener("blur",this.blurListener),this.input.removeEventListener("focus",this.focusListener),this.input.removeEventListener("keydown",this.keydownListener),this.container.removeChild(this.mainComponent),this.container.removeChild(this.alerts);var t,e,n=this.container.parentNode;return n&&(n.insertBefore(this.input,this.container),n.removeChild(this.container)),this.unmountUnhide(),this.unhideFields(),this.fsm.stop(),t=this.input,e=this.inputStyle,t.setAttribute("style",e||""),this.options.onRemove.call(this),this.unsetPlaceholder(),this}},{key:"setMessage",value:function(t){return this.fsm.send({type:"NOTIFY",notification:t}),this}},{key:"ariaAnchor",value:function(){return"1.0"===this.options.aria?this.input:this.container}},{key:"query",value:function(){return this.input.value}},{key:"setSuggestions",value:function(t,e){return e!==this.query()?this:0===t.length?this.setMessage(this.options.msgNoMatch):(this.fsm.send({type:"SUGGEST",suggestions:t}),this)}},{key:"close",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"blur";mo(this.mainComponent),"esc"===t&&xo(this.input,""),this.options.onClose.call(this,t)}},{key:"updateSuggestions",value:function(t){this.suggestions=t,this.current=-1}},{key:"applyContext",value:function(t){var e=t.code;this.context=e,this.countryIcon.innerText=t.icon,this.announce("Country switched to ".concat(t.name))}},{key:"renderNotice",value:function(){this.list.innerHTML="",this.input.setAttribute("aria-activedescendant",""),this.message.textContent=this.notification,this.announce(this.notification),this.list.appendChild(this.message)}},{key:"open",value:function(){go(this.mainComponent),this.options.onOpen.call(this)}},{key:"next",value:function(){return this.current+1>this.list.children.length-1?this.current=0:this.current+=1,this}},{key:"previous",value:function(){return this.current-1<0?this.current=this.list.children.length-1:this.current+=-1,this}},{key:"scrollToView",value:function(t){var e=t.offsetTop,n=this.list.scrollTop;en+r&&(this.list.scrollTop=e-r+o),this}},{key:"goto",value:function(t){var e=this.list.children,n=e[t];return t>-1&&e.length>0?this.scrollToView(n):this.scrollToView(e[0]),this}},{key:"opened",value:function(){return!this.closed()}},{key:"closed",value:function(){return this.fsm.state.matches("closed")}},{key:"createUnhide",value:function(){var t=this,e=Ni(this.scope,this.options.unhide,(function(){var e=t.options.document.createElement("p");return e.innerText=t.options.msgUnhide,e.setAttribute("role","button"),e.setAttribute("tabindex","0"),t.options.unhideClass&&(e.className=t.options.unhideClass),e}));return e.addEventListener("click",this.unhideEvent),e}},{key:"unmountUnhide",value:function(){var t;this.unhide.removeEventListener("click",this.unhideEvent),null==this.options.unhide&&this.options.hide.length&&(null!==(t=this.unhide)&&null!==t.parentNode&&t.parentNode.removeChild(t))}},{key:"hiddenFields",value:function(){var t=this;return this.options.hide.map((function(e){return co(e)?(n=t.options.scope,(r=e)?n.querySelector(r):null):e;var n,r})).filter((function(t){return null!==t}))}},{key:"hideFields",value:function(){this.hiddenFields().forEach(mo)}},{key:"unhideFields",value:function(){this.hiddenFields().forEach(go),this.options.onUnhide.call(this)}}]),t}(),Pi=function(t){return function(){t.options.onBlur.call(t),t.fsm.send({type:"CLOSE",reason:"blur"})}},Ai=function(t){return function(e){t.options.onFocus.call(t),t.fsm.send("AWAKE")}},Ti=function(t){return function(e){if(":c"===t.query().toLowerCase())return xo(t.input,""),t.fsm.send({type:"CHANGE_COUNTRY"});t.fsm.send({type:"INPUT",event:e})}},_i=function(t){return function(e){e.preventDefault(),t.fsm.send({type:"CHANGE_COUNTRY"})}},Li=function(t){return function(e){var n=ei(e);if("Enter"===n&&e.preventDefault(),t.options.onKeyDown.call(t,e),t.closed())return t.fsm.send("AWAKE");if(t.fsm.state.matches("suggesting_country")){if("Enter"===n){var r=t.contextSuggestions[t.current];r&&t.fsm.send({type:"SELECT_COUNTRY",contextDetails:r})}"Backspace"===n&&t.fsm.send({type:"INPUT",event:e}),"ArrowUp"===n&&(e.preventDefault(),t.fsm.send("PREVIOUS")),"ArrowDown"===n&&(e.preventDefault(),t.fsm.send("NEXT"))}if(t.fsm.state.matches("suggesting")){if("Enter"===n){var o=t.suggestions[t.current];o&&t.fsm.send({type:"SELECT_ADDRESS",suggestion:o})}"Backspace"===n&&t.fsm.send({type:"INPUT",event:e}),"ArrowUp"===n&&(e.preventDefault(),t.fsm.send("PREVIOUS")),"ArrowDown"===n&&(e.preventDefault(),t.fsm.send("NEXT"))}"Escape"===n&&t.fsm.send({type:"CLOSE",reason:"esc"}),"Home"===n&&t.fsm.send({type:"RESET"}),"End"===n&&t.fsm.send({type:"RESET"})}},Ni=function(t,e,n){return co(e)?t.querySelector(e):n&&null===e?n():e},Di=function(t){var e=new ki(t);return Ri.push(e),e},Ri=[];function Ui(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function qi(e){for(var n=1;n1&&void 0!==arguments[1]?arguments[1]:"idpc";return"true"===t.getAttribute(e)}(t,e)}))},Ii=function(t){return function(t,e){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:fo,r=t,o=e.toUpperCase();"HTML"!==r.tagName;){if(r.tagName===o&&n(r))return r;if(null===r.parentNode)return null;r=r.parentNode}return null}(t,"FORM")},Mi=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=new io({api_key:t.apiKey}),r=e.pageTest,o=void 0===r?Fi:r;return o()?gn({client:n}).then((function(n){if(!n.available)return null;var r=e.getScope,i=void 0===r?Ii:r,s=e.interval,a=void 0===s?1e3:s,u=e.anchor,c=e.onBind,l=void 0===c?Ci:c,f=e.onAnchorFound,p=void 0===f?Ci:f,h=e.onBindAttempt,d=void 0===h?Ci:h,v=e.immediate,y=void 0===v||v,m=e.marker,g=void 0===m?"idpc":m,b=function(){d({config:t,options:e}),Bi(qi({anchor:u},t),g).forEach((function(e){var n=i(e);if(n){var r=qi(qi({scope:n},t),{},{checkKey:!1});p({anchor:e,scope:n,config:r});var o=Di(r);lo(e,g),l(o)}}))},w=wo({bind:b,pageTest:o,interval:a}),O=w.start,S=w.stop;return y&&O(),{start:O,stop:S,bind:b}})).catch((function(t){return e.onError&&e.onError(t),null})):Promise.resolve(null)};function Gi(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function Hi(e){for(var n=1;n0&&(e[n]=o),e}),{})},Yi=function(t){return"string"==typeof t},$i=function(t){var e=[];return function(t){return Array.isArray(t)}(t)?(t.forEach((function(t){Xi(t)&&e.push(t.toString()),Yi(t)&&e.push(t)})),e.join(",")):Xi(t)?t.toString():Yi(t)?t:""},Xi=function(t){return"number"==typeof t},Qi=function(t,e){var n=t.timeout;return Xi(n)?n:e.config.timeout},Zi=function(t,e){var n=t.header,r=void 0===n?{}:n;return Wi(Wi({},e.config.header),Vi(r))},ts=function(t){var e=t.header,n=t.options,r=t.client;return e.Authorization=function(t,e){var n=[],r=e.api_key||t.config.api_key;n.push(["api_key",r]);var o=e.licensee;void 0!==o&&n.push(["licensee",o]);var i=e.user_token;return void 0!==i&&n.push(["user_token",i]),"IDEALPOSTCODES ".concat(es(n))}(r,n),e},es=function(t){return t.map((function(t){var e=F(t,2),n=e[0],r=e[1];return"".concat(n,'="').concat(r,'"')})).join(" ")},ns=function(t){var e=t.header,n=t.options.sourceIp;return void 0!==n&&(e["IDPC-Source-IP"]=n),e},rs=function(t){var e=t.query,n=t.options.filter;return void 0!==n&&(e.filter=n.join(",")),e},os=function(t){var e,n=t.client,r=t.query,o=t.options;return n.config.tags.length&&(e=n.config.tags),o.tags&&(e=o.tags),void 0!==e&&(r.tags=e.join(",")),r};function is(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var n,r=Ve(t);if(e){var o=Ve(this).constructor;n=Reflect.construct(r,arguments,o)}else n=r.apply(this,arguments);return We(this,n)}}var ss=function(t){Ke(n,t);var e=is(n);function n(t){var r;Kt(this,n);var o=(this instanceof n?this.constructor:void 0).prototype;(r=e.call(this)).__proto__=o;var i=t.message,s=t.httpStatus,a=t.metadata,u=void 0===a?{}:a;return r.message=i,r.name="Ideal Postcodes Error",r.httpStatus=s,r.metadata=u,Error.captureStackTrace&&Error.captureStackTrace(Je(r),n),r}return n}(Xe(Error)),as=function(t){Ke(n,t);var e=is(n);function n(t){var r;return Kt(this,n),(r=e.call(this,{httpStatus:t.httpStatus,message:t.body.message})).response=t,r}return n}(ss),us=function(t){Ke(n,t);var e=is(n);function n(){return Kt(this,n),e.apply(this,arguments)}return n}(as),cs=function(t){Ke(n,t);var e=is(n);function n(){return Kt(this,n),e.apply(this,arguments)}return n}(as),ls=function(t){Ke(n,t);var e=is(n);function n(){return Kt(this,n),e.apply(this,arguments)}return n}(cs),fs=function(t){Ke(n,t);var e=is(n);function n(){return Kt(this,n),e.apply(this,arguments)}return n}(as),ps=function(t){Ke(n,t);var e=is(n);function n(){return Kt(this,n),e.apply(this,arguments)}return n}(fs),hs=function(t){Ke(n,t);var e=is(n);function n(){return Kt(this,n),e.apply(this,arguments)}return n}(fs),ds=function(t){Ke(n,t);var e=is(n);function n(){return Kt(this,n),e.apply(this,arguments)}return n}(as),vs=function(t){Ke(n,t);var e=is(n);function n(){return Kt(this,n),e.apply(this,arguments)}return n}(ds),ys=function(t){Ke(n,t);var e=is(n);function n(){return Kt(this,n),e.apply(this,arguments)}return n}(ds),ms=function(t){Ke(n,t);var e=is(n);function n(){return Kt(this,n),e.apply(this,arguments)}return n}(ds),gs=function(t){Ke(n,t);var e=is(n);function n(){return Kt(this,n),e.apply(this,arguments)}return n}(ds),bs=function(t){Ke(n,t);var e=is(n);function n(){return Kt(this,n),e.apply(this,arguments)}return n}(as),ws=function(t){return null!==(e=t)&&"object"===lt(e)&&("string"==typeof t.message&&"number"==typeof t.code);var e},Os=function(t){var e=t.httpStatus,n=t.body;if(!function(t){return!(t<200||t>=300)}(e)){if(ws(n)){var r=n.code;if(4010===r)return new ls(t);if(4040===r)return new vs(t);if(4042===r)return new ys(t);if(4044===r)return new ms(t);if(4046===r)return new gs(t);if(4020===r)return new ps(t);if(4021===r)return new hs(t);if(404===e)return new ds(t);if(400===e)return new us(t);if(402===e)return new fs(t);if(401===e)return new cs(t);if(500===e)return new bs(t)}return new ss({httpStatus:e,message:JSON.stringify(n)})}},Ss=function(t,e){return[t.client.url(),t.resource,encodeURIComponent(e),t.action].filter((function(t){return void 0!==t})).join("/")},Es=function(t){var e=t.client;return function(n,r){return e.config.agent.http({method:"GET",url:Ss(t,n),query:Vi(r.query),header:Zi(r,e),timeout:Qi(r,e)}).then((function(t){var e=Os(t);if(e)throw e;return t}))}},js=function(t,e){return function(t){var e=t.client,n=t.resource;return function(t){return e.config.agent.http({method:"GET",url:"".concat(e.url(),"/").concat(n),query:Vi(t.query),header:Zi(t,e),timeout:Qi(t,e)}).then((function(t){var e=Os(t);if(e)throw e;return t}))}}({resource:"addresses",client:t})(e)},Cs=function(t){var e,n,r,o=xs(t),i=t.page;return void 0!==i&&(o.query.page=i.toString()),(e=t.client,n=t.postcode,r=o,Es({resource:"postcodes",client:e})(n,r)).then((function(t){return t.body.result})).catch((function(t){if(t instanceof vs)return[];throw t}))},xs=function(t){var e={},n={},r=t.client;ts({client:r,header:e,options:t}),ns({header:e,options:t}),rs({query:n,options:t}),os({client:r,query:n,options:t});var o={header:e,query:n};return void 0!==t.timeout&&(o.timeout=t.timeout),o},ks=function(t){var e=t.client,n=t.timeout,r=t.api_key||t.client.config.api_key,o=t.licensee,i={query:void 0===o?{}:{licensee:o},header:{}};return void 0!==n&&(i.timeout=n),function(t,e,n){return Es({resource:"keys",client:t})(e,n)}(e,r,i).then((function(t){return t.body.result}))},Ps={exports:{}},As=function(t,e){return function(){for(var n=new Array(arguments.length),r=0;r=0)return;o[e]="set-cookie"===e?(o[e]?o[e]:[]).concat([n]):o[e]?o[e]+", "+n:n}})),o):o},pa=ra,ha=Vs,da=Ea,va=ia,ya=function(t){return new Promise((function(e,n){var r,o=t.data,i=t.headers,s=t.responseType;function a(){t.cancelToken&&t.cancelToken.unsubscribe(r),t.signal&&t.signal.removeEventListener("abort",r)}sa.isFormData(o)&&delete i["Content-Type"];var u=new XMLHttpRequest;if(t.auth){var c=t.auth.username||"",l=t.auth.password?unescape(encodeURIComponent(t.auth.password)):"";i.Authorization="Basic "+btoa(c+":"+l)}var f=la(t.baseURL,t.url);function p(){if(u){var r="getAllResponseHeaders"in u?fa(u.getAllResponseHeaders()):null,o={data:s&&"text"!==s&&"json"!==s?u.response:u.responseText,status:u.status,statusText:u.statusText,headers:r,config:t,request:u};aa((function(t){e(t),a()}),(function(t){n(t),a()}),o),u=null}}if(u.open(t.method.toUpperCase(),ca(f,t.params,t.paramsSerializer),!0),u.timeout=t.timeout,"onloadend"in u?u.onloadend=p:u.onreadystatechange=function(){u&&4===u.readyState&&(0!==u.status||u.responseURL&&0===u.responseURL.indexOf("file:"))&&setTimeout(p)},u.onabort=function(){u&&(n(ha("Request aborted",t,"ECONNABORTED",u)),u=null)},u.onerror=function(){n(ha("Network Error",t,null,u)),u=null},u.ontimeout=function(){var e=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded",r=t.transitional||da.transitional;t.timeoutErrorMessage&&(e=t.timeoutErrorMessage),n(ha(e,t,r.clarifyTimeoutError?"ETIMEDOUT":"ECONNABORTED",u)),u=null},sa.isStandardBrowserEnv()){var h=(t.withCredentials||pa(f))&&t.xsrfCookieName?ua.read(t.xsrfCookieName):void 0;h&&(i[t.xsrfHeaderName]=h)}"setRequestHeader"in u&&sa.forEach(i,(function(t,e){void 0===o&&"content-type"===e.toLowerCase()?delete i[e]:u.setRequestHeader(e,t)})),sa.isUndefined(t.withCredentials)||(u.withCredentials=!!t.withCredentials),s&&"json"!==s&&(u.responseType=t.responseType),"function"==typeof t.onDownloadProgress&&u.addEventListener("progress",t.onDownloadProgress),"function"==typeof t.onUploadProgress&&u.upload&&u.upload.addEventListener("progress",t.onUploadProgress),(t.cancelToken||t.signal)&&(r=function(t){u&&(n(!t||t&&t.type?new va("canceled"):t),u.abort(),u=null)},t.cancelToken&&t.cancelToken.subscribe(r),t.signal&&(t.signal.aborted?r():t.signal.addEventListener("abort",r))),o||(o=null),u.send(o)}))},ma=Fs,ga=function(t,e){zs.forEach(t,(function(n,r){r!==e&&r.toUpperCase()===e.toUpperCase()&&(t[e]=n,delete t[r])}))},ba=Ks,wa={"Content-Type":"application/x-www-form-urlencoded"};function Oa(t,e){!ma.isUndefined(t)&&ma.isUndefined(t["Content-Type"])&&(t["Content-Type"]=e)}var Sa={transitional:{silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},adapter:function(){var t;return("undefined"!=typeof XMLHttpRequest||"undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process))&&(t=ya),t}(),transformRequest:[function(t,e){return ga(e,"Accept"),ga(e,"Content-Type"),ma.isFormData(t)||ma.isArrayBuffer(t)||ma.isBuffer(t)||ma.isStream(t)||ma.isFile(t)||ma.isBlob(t)?t:ma.isArrayBufferView(t)?t.buffer:ma.isURLSearchParams(t)?(Oa(e,"application/x-www-form-urlencoded;charset=utf-8"),t.toString()):ma.isObject(t)||e&&"application/json"===e["Content-Type"]?(Oa(e,"application/json"),function(t,e,n){if(ma.isString(t))try{return(e||JSON.parse)(t),ma.trim(t)}catch(t){if("SyntaxError"!==t.name)throw t}return(n||JSON.stringify)(t)}(t)):t}],transformResponse:[function(t){var e=this.transitional||Sa.transitional,n=e&&e.silentJSONParsing,r=e&&e.forcedJSONParsing,o=!n&&"json"===this.responseType;if(o||r&&ma.isString(t)&&t.length)try{return JSON.parse(t)}catch(t){if(o){if("SyntaxError"===t.name)throw ba(t,this,"E_JSON_PARSE");throw t}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};ma.forEach(["delete","get","head"],(function(t){Sa.headers[t]={}})),ma.forEach(["post","put","patch"],(function(t){Sa.headers[t]=ma.merge(wa)}));var Ea=Sa,ja=Fs,Ca=Ea,xa=function(t){return!(!t||!t.__CANCEL__)},ka=Fs,Pa=function(t,e,n){var r=this||Ca;return ja.forEach(n,(function(n){t=n.call(r,t,e)})),t},Aa=xa,Ta=Ea,_a=ia;function La(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new _a("canceled")}var Na=Fs,Da=function(t,e){e=e||{};var n={};function r(t,e){return Na.isPlainObject(t)&&Na.isPlainObject(e)?Na.merge(t,e):Na.isPlainObject(e)?Na.merge({},e):Na.isArray(e)?e.slice():e}function o(n){return Na.isUndefined(e[n])?Na.isUndefined(t[n])?void 0:r(void 0,t[n]):r(t[n],e[n])}function i(t){if(!Na.isUndefined(e[t]))return r(void 0,e[t])}function s(n){return Na.isUndefined(e[n])?Na.isUndefined(t[n])?void 0:r(void 0,t[n]):r(void 0,e[n])}function a(n){return n in e?r(t[n],e[n]):n in t?r(void 0,t[n]):void 0}var u={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:a};return Na.forEach(Object.keys(t).concat(Object.keys(e)),(function(t){var e=u[t]||o,r=e(t);Na.isUndefined(r)&&e!==a||(n[t]=r)})),n},Ra="0.24.0",Ua=Ra,qa={};["object","boolean","number","function","string","symbol"].forEach((function(t,e){qa[t]=function(n){return lt(n)===t||"a"+(e<1?"n ":" ")+t}}));var Fa={};qa.transitional=function(t,e,n){function r(t,e){return"[Axios v"+Ua+"] Transitional option '"+t+"'"+e+(n?". "+n:"")}return function(n,o,i){if(!1===t)throw new Error(r(o," has been removed"+(e?" in "+e:"")));return e&&!Fa[o]&&(Fa[o]=!0,console.warn(r(o," has been deprecated since v"+e+" and will be removed in the near future"))),!t||t(n,o,i)}};var Ba={assertOptions:function(t,e,n){if("object"!==lt(t))throw new TypeError("options must be an object");for(var r=Object.keys(t),o=r.length;o-- >0;){var i=r[o],s=e[i];if(s){var a=t[i],u=void 0===a||s(a,i,t);if(!0!==u)throw new TypeError("option "+i+" must be "+u)}else if(!0!==n)throw Error("Unknown option "+i)}},validators:qa},Ia=Fs,Ma=Ms,Ga=Js,Ha=function(t){return La(t),t.headers=t.headers||{},t.data=Pa.call(t,t.data,t.headers,t.transformRequest),t.headers=ka.merge(t.headers.common||{},t.headers[t.method]||{},t.headers),ka.forEach(["delete","get","head","post","put","patch","common"],(function(e){delete t.headers[e]})),(t.adapter||Ta.adapter)(t).then((function(e){return La(t),e.data=Pa.call(t,e.data,e.headers,t.transformResponse),e}),(function(e){return Aa(e)||(La(t),e&&e.response&&(e.response.data=Pa.call(t,e.response.data,e.response.headers,t.transformResponse))),Promise.reject(e)}))},Ja=Da,za=Ba,Ka=za.validators;function Wa(t){this.defaults=t,this.interceptors={request:new Ga,response:new Ga}}Wa.prototype.request=function(t){"string"==typeof t?(t=arguments[1]||{}).url=arguments[0]:t=t||{},(t=Ja(this.defaults,t)).method?t.method=t.method.toLowerCase():this.defaults.method?t.method=this.defaults.method.toLowerCase():t.method="get";var e=t.transitional;void 0!==e&&za.assertOptions(e,{silentJSONParsing:Ka.transitional(Ka.boolean),forcedJSONParsing:Ka.transitional(Ka.boolean),clarifyTimeoutError:Ka.transitional(Ka.boolean)},!1);var n=[],r=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(r=r&&e.synchronous,n.unshift(e.fulfilled,e.rejected))}));var o,i=[];if(this.interceptors.response.forEach((function(t){i.push(t.fulfilled,t.rejected)})),!r){var s=[Ha,void 0];for(Array.prototype.unshift.apply(s,n),s=s.concat(i),o=Promise.resolve(t);s.length;)o=o.then(s.shift(),s.shift());return o}for(var a=t;n.length;){var u=n.shift(),c=n.shift();try{a=u(a)}catch(t){c(t);break}}try{o=Ha(a)}catch(t){return Promise.reject(t)}for(;i.length;)o=o.then(i.shift(),i.shift());return o},Wa.prototype.getUri=function(t){return t=Ja(this.defaults,t),Ma(t.url,t.params,t.paramsSerializer).replace(/^\?/,"")},Ia.forEach(["delete","get","head","options"],(function(t){Wa.prototype[t]=function(e,n){return this.request(Ja(n||{},{method:t,url:e,data:(n||{}).data}))}})),Ia.forEach(["post","put","patch"],(function(t){Wa.prototype[t]=function(e,n,r){return this.request(Ja(r||{},{method:t,url:e,data:n}))}}));var Va=Wa,Ya=ia;function $a(t){if("function"!=typeof t)throw new TypeError("executor must be a function.");var e;this.promise=new Promise((function(t){e=t}));var n=this;this.promise.then((function(t){if(n._listeners){var e,r=n._listeners.length;for(e=0;e=0;e--)t.remove(e)}(this.select),this.select.appendChild(this.createOption("ideal",this.options.msgSelect));for(var e=0;e1&&void 0!==arguments[1]?arguments[1]:{},o=r.pageTest,i=void 0===o?xu:o,s=r.onError,a=void 0===s?ku:s,c=r.onBindAttempt,l=void 0===c?ku:c,f=r.onBind,p=void 0===f?ku:f,h=r.anchor,d=r.onAnchorFound,v=void 0===d?ku:d,y=r.getScope,m=void 0===y?u:y,g=function(){try{l(t),Pu(Cu({anchor:h},t)).forEach((function(r){if(i()){var o=m(r);v({anchor:r,scope:o,config:t}),e=Su(t),n(r),p(e)}}))}catch(t){a(t)}},b=ht({config:t,bind:g}),w=b.start,O=b.stop;return w(),{start:w,stop:O,controller:e}};function Tu(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function _u(e){for(var n=1;n1&&void 0!==arguments[1]&&arguments[1],n=t.value;return Uu(e).reduce((function(t,e){return n===e||t}),!1)},Fu=function(t){var e=document.createElement("span");e.innerText="Search your Postcode";var n=document.createElement("label");return n.className="label",n.setAttribute("for","idpc_postcode_lookup"),n.appendChild(e),i({target:t.firstChild,elem:n}),n},Bu=function(){},Iu=function(t,e,n){var r=t.country,o=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(!r)return Bu;var i=function(t){if(qu(t,o))return e();n()};return r.addEventListener("change",(function(t){i(t.target)})),i(r)},Mu=function(t,e){var n={};return Object.keys(t).forEach((function(r){n[r]=s(t[r],e)})),n},Gu=function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=arguments.length>3?arguments[3]:void 0;!0===t.postcodeLookup&&Au(_u({apiKey:t.apiKey,checkKey:!0,context:"div.idpc_lookup",outputFields:e,selectStyle:{"margin-top":"5px","margin-bottom":"5px"},buttonStyle:{position:"absolute",right:0},contextStyle:{position:"relative"},onLoaded:function(){var t=this,e=Fu(this.context);Iu(this.options.outputFields,(function(){e.hidden=!1,t.context.style.display="block"}),(function(){e.hidden=!0,t.context.style.display="none"}))}},t.postcodeLookupOverride),_u({getScope:function(t){return o(t,"FORM")},anchor:e.line_2,onAnchorFound:function(n){var o,s=n.scope,a=Mu(e,s),u=Nu(a,r);if(n.config.outputFields=a,null!==u&&(Lu(t,a,r),null===(o=u.parentElement)||void 0===o||!o.querySelector('.idpc_lookup[idpc="true"]'))){var c=document.createElement("div");return c.className="idpc_lookup field",n.config.context=c,i({target:u,elem:c})}}},n))},Hu=function(){var t,e=(t=zt.mark((function t(e,n){var r,o,i=arguments;return zt.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(r=i.length>2&&void 0!==i[2]?i[2]:{},o=i.length>3?i[3]:void 0,!0===e.autocomplete){t.next=4;break}return t.abrupt("return");case 4:if(void 0!==n.line_1){t.next=6;break}return t.abrupt("return");case 6:return t.next=8,Mi(_u({apiKey:e.apiKey,checkKey:!0,onLoaded:function(){var t=this;this.options.outputFields=Mu(n,this.scope),Lu(e,this.options.outputFields,o),Iu(this.options.outputFields,(function(){return t.attach()}),(function(){return t.detach()}),!0)},outputFields:n},e.autocompleteOverride),r);case 8:case"end":return t.stop()}}),t)})),function(){var e=this,n=arguments;return new Promise((function(r,o){var i=t.apply(e,n);function s(t){dt(i,r,o,s,a,"next",t)}function a(t){dt(i,r,o,s,a,"throw",t)}s(void 0)}))});return function(t,n){return e.apply(this,arguments)}}(),Ju=function(t,e){return-1!==t.indexOf(e)},zu={line_1:'[name="street[0]"]',line_2:'[name="street[1]"]',line_3:'[name="street[2]"]',postcode:'[name="postcode"]',post_town:'[name="city"]',organisation_name:'[name="company"]',county:'[name="region"]',country:'[name="country_id"]'},Ku=function(){return Ju(window.location.pathname,"/checkout")},Wu=function(t){return o(t,"form")},Vu=function(t){Hu(t,zu,{pageTest:Ku,getScope:Wu}),Gu(t,zu,{pageTest:Ku,getScope:Wu})},Yu=function(){return Ju(window.location.pathname,"/checkout")},$u=function(t){Hu(t,zu,{pageTest:Yu}),Gu(t,zu,{pageTest:Yu})},Xu={line_1:"#street_1",line_2:"#street_2",line_3:"#street_3",organisation_name:"#company",post_town:"#city",county:"#region",country:"#country",postcode:'[name="postcode"]'},Qu={parentScope:"div",parentTest:function(t){return t.classList.contains("field")}},Zu=function(){return Ju(window.location.pathname,"/multishipping")},tc=function(t){Hu(t,Xu,{pageTest:Zu},Qu),Gu(t,Xu,{pageTest:Zu},Qu)},ec=function(){return Ju(window.location.pathname,"/customer/address")},nc=function(t){Hu(t,Xu,{pageTest:ec}),Gu(t,Xu,{pageTest:ec},Qu)},rc=function(){return!0},oc=function(t){(t.customFields||[]).forEach((function(e){Hu(t,e,{pageTest:rc}),Gu(t,e,{pageTest:rc})}))};window.idpcStart=function(){[$u,Vu,nc,tc,oc].forEach((function(t){var e=function(){var t=window.idpcConfig;if(void 0!==t)return v(v({},y),t)}();e&&t(e)}))}}();